I am a newer in Android,now I code something about sqlite. There are some questions,I try many times to solve it,but I fail. I write the MySQLiteHelper class (extends SQLiteOpenHelper)
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String CLASSIFICATION = "CREATE TABLE IF NOT EXISTS classification(classification_id Integer primary key AUTOINCREMENT,classify VARCHAR)";
public static final String ACCOUNT = "CREATE TABLE IF NOT EXISTS account(account_id Integer primary key AUTOINCREMENT,username VARCHAR,password VARCHAR,classification_id Integer REFERENCES classification(classification_id))";
public MySQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context,name,factory,version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CLASSIFICATION);
db.execSQL(ACCOUNT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
And I write the MySQLiteDatabase class to operate the database ( in Singleton)
public class MySQLiteDatabase {
private static MySQLiteDatabase instance;
private SQLiteDatabase sqLiteDatabase;
private MySQLiteDatabase(Context context){
MySQLiteHelper helper = new MySQLiteHelper(context,"test.db",null,1);
sqLiteDatabase = helper.getWritableDatabase();
sqLiteDatabase.execSQL("INSERT INTO classification(classification_id,classify) VALUES(1,'QQ')");
}
public static MySQLiteDatabase getInstance(Context context){
if(null == instance){
instance = new MySQLiteDatabase(context);
}
return instance;
}
}
the questions: When I use the follow code to create the tables,it always create tables(but I want to create tables only once,so I make it Singleton)
my = MySQLiteDatabase.getInstance(SampleActivity.this);
why the follow code always execute?
if(null == instance){
instance = new MySQLiteDatabase(context);
}
please help me.
Aucun commentaire:
Enregistrer un commentaire