我想從.csv文件中提取數據,將其存儲到Sqlite數據庫第一次啓動應用程序時。然後從Sqlite數據庫中獲取數據並顯示在Expandable列表視圖中。但是,當我嘗試使用助手類對象調用DatabaseHelper類的方法時,我得到空指針異常。嘗試從Sqlite數據庫獲取數據與幫助器類對象時獲取空指針異常
DatabaseHelper
`public Cursor getExpandableData() {
String query = "SELECT * FROM Category GROUP BY categorydesc";
return db.rawQuery(query, null);
}`
public boolean insertContact(String[] rowData) {
// TODO Auto-generated method stub
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("DistrictCd", rowData[0]);
contentValues.put("ProspectId", rowData[1]);
contentValues.put("categorydesc", rowData[2]);
contentValues.put("BusinessName", rowData[3]);
contentValues.put("ph_Phone", rowData[4]);
contentValues.put("LandMark", rowData[5]);
contentValues.put("CategoryId", rowData[6]);
db.insert("Category", null, contentValues);
// check for data is inserted into db or not
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from Category", null);
int noOfRecords = cursor.getCount();
// if cursor holding some data then data is inserted successfully
if (noOfRecords != 0) {
return true;
} else {
return false;
}
}`
` NearByApp要求唯一的應用程序推出
`public class NearByApp extends Application {
public void onCreate() {SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// run only once when app has been launched for the 1st time
csvToSqlite();
// mark first time has runned.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}`
`public void csvToSqlite() {
//code for fetching data from .csv
String[] RowData = reader.split(",");
databaseHelper = new DatabaseHelper(context);
if (databaseHelper.insertContact(RowData) == true) {
Log.i("inside csvToSqlite()", " data inserted successfully");
} else {
Log.i("inside csvToSqlite()",
" data is not inserted into db");
}`
MainActivity
`protected void onCreate(Bundle savedInstanceState) {
// Group data//
databaseHelper = new DatabaseHelper(getApplicationContext());
Cursor cursor=databaseHelper.getExpandableData();`
}`
我收到例外
return db.rawQuery(query,null);
線
04-21 14:25:49.810:E/AndroidRuntime(25473):顯示java.lang.NullPointerException 04-21 14:25:49.810:致E/AndroidRuntime (25473):在com.example.nearbuy.database.DatabaseHelper.getExpandableData(DatabaseHelper.java:308)
請格式化/妥善縮進你的代碼!你得到的NPE是什麼?它從哪一行觸發?什麼是堆棧跟蹤? – alfasin
你能告訴我們你的日誌說什麼? – Joze
由於:java.lang.NullPointerException在com.example.nearbuy.database.DatabaseHelper.getExpandableData(DatabaseHelper.java:308) –