我一直在尝试从名为 Station 的数据库中检索一些数据,然后将其存储到数据库列表视图中。当我调用此活动时,应用程序将停止。
继承代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
SQLiteDatabase db = openOrCreateDatabase("Station.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor data_fetch = db.rawQuery("Select * From Station", null);
String[] station_array = new String[data_fetch.getCount()];
int i = 0;
while(data_fetch.moveToNext()){
String uname = data_fetch.getString(data_fetch.getColumnIndex("Station_name"));
station_array[i] = uname;
i++;
}
ArrayAdapter station_adapter = new ArrayAdapter<String>(this,R.layout.activity_list_view,station_array);
ListView station_listView = (ListView) findViewById(R.id.station_list);
station_listView.setAdapter(station_adapter);
}
该应用程序在我注释掉行
时有效Cursor data_fetch = db.rawQuery("Select * From Station", null);
这让我相信这条线是导致应用程序崩溃的那条线但是我发现它没有任何问题。
请注意,我已在之前的活动中创建数据并将数据插入数据库中。 任何提示都将不胜感激。谢谢你。
PS:我是新手,所以请告诉我是否还有其他重要内容我省略了!
答案 0 :(得分:0)
您必须像这样创建数据库助手类
public static class CitrusDatabaseHelper extends SQLiteOpenHelper {
CitrusDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(TABLE_NAME_CREATE_SQL);
// database = this.getReadableDatabase();
}
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// Recreate new database:
onCreate(_db);
}
}
这里TABLE_NAME_CREATE_SQL
就像这样
这是样本
private static final String TABLE_NAME_CREATE_SQL =
"create table " + TABLE_NAME
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text,"
+ KEY_EMAILID + " text,"
+ KEY_MOBILE_NUMBER + " text,"
+ KEY_PASSWORD + " text,"
+ KEY_USERID + " integer,"
+ KEY_IMAGE_PATH + " text,"
+ KEY_Notification + " integer,"
+ KEY_DOB + " text);";
然后你必须像这样访问你的数据库类
SQLiteDatabase db = new CitrusDatabaseHelper(context).getWritableDatabase();
Cursor data_fetch = db.rawQuery("Select * From Station", null);
处理光标就像这样
int i=0;
if (data_fetch.moveToFirst()) {
do {
String uname = data_fetch.getString(data_fetch.getColumnIndex("Station_name"));
station_array[i] = uname;
i++;
} while (data_fetch.moveToNext());
}
希望,它会帮助你