未创建SQLite database
。过去几个小时我一直在玩这个,但现在我累了很多。我在Log Cat
中没有收到任何错误或警告。这是我到目前为止所尝试的代码。将不胜感激。
public class MySQLiteHelper extends SQLiteOpenHelper{
final static String DB_NAME = "citiesdata.db";
final static String TABLE_NAME = "allcities";
final static String ID = "_id";
final static String CITY_CODE = "city_code";
final static int DB_VERSION = 1;
private SQLiteDatabase db;
Context cont;
public MySQLiteHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
cont = context;
Toast.makeText(cont, "constructor called", Toast.LENGTH_LONG).show();
}
@Override
public void onCreate(SQLiteDatabase db) {
Toast.makeText(cont, "onCreate method called", Toast.LENGTH_LONG).show();
String createTable = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + CITY_CODE + " TEXT);";
db.execSQL(createTable);
// INSERTING RECORDS IN DATABASE
SQLiteDatabase writableDB = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CITY_CODE, "333");
writableDB.insert(TABLE_NAME, null, values);
writableDB.close();
readCity();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Toast.makeText(cont, "onUpgrade method called", Toast.LENGTH_LONG).show();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void readCity(){
Toast.makeText(cont, "readCity method called", Toast.LENGTH_LONG).show();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
Toast.makeText(cont, cursor.getString(cursor.getColumnIndex(CITY_CODE)), Toast.LENGTH_LONG).show();
db.close();
}
}
在按钮上调用主UI线程中的构造函数,单击此按钮。
new MySQLiteHelper(MainActivity.this);
权限是......
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
提前多多感谢。
答案 0 :(得分:1)
最后我把问题直接射到脑袋里。但是怎么样?
SQLiteOpenHelper
的逻辑是,它不会通过仅创建其对象来调用onCreate
方法。
onCreate
方法。onUpgrade
方法。我在fillTable
类中创建了一个MySQLiteHelper
方法,我第一次尝试通过调用getWritableDatabase
的{{1}}方法来访问数据库。 SQLiteOpenHelper
方法的定义如下所示。
fillTable
创建名为fillTable方法的类的对象。
public void fillTable(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CITY_CODE, "333");
db.insert(TABLE_NAME, null, values);
db.close();
readCity();
}
感谢所有那些试图在评论中帮助我的人。
答案 1 :(得分:0)
public MySQLiteHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
cont = context;
SQLiteDatabase db = this.getReadableDatabase();
Toast.makeText(cont, "constructor called", Toast.LENGTH_LONG).show();
}
更改构造函数代码,它将起作用...