我在我的应用中使用数据库。为此,我用单个实例创建了sqlite数据库。但是当我运行应用程序时,没有创建任何表。我不知道是什么问题。
代码
public class DatabaseHelper extends SQLiteOpenHelper {
private static DatabaseHelper mInstance = null;
private static final String DATABASE_NAME = "MCQDemo";
private static final String DATABASE_TABLE = "LANGUAGETABLE";
private static final int DATABASE_VERSION = 1;
private Context mCxt;
public static DatabaseHelper getInstance(Context ctx) {
/**
* use the application context as suggested by CommonsWare.
* this will ensure that you dont accidentally leak an Activitys
* context (see this article for more information:
* http://developer.android.com/resources/articles/avoiding-memory-leaks.html)
*/
if (mInstance == null) {
mInstance = new DatabaseHelper(ctx.getApplicationContext());
}
return mInstance;
}
/**
* constructor should be private to prevent direct instantiation.
* make call to static factory method "getInstance()" instead.
*/
private DatabaseHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
this.mCxt = ctx;
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(LanguageTable.CreateTable());
} catch (SQLiteException e) {
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
LanguageTable
public class LanguageTable {
private SQLiteDatabase database;
private DatabaseHelper databaseHelper;
private Context context;
private static String TableName = "LANGUAGETABLE";
private boolean result;
private static String Language_Name = "language_name";
public LanguageTable(Context context) {
this.context = context;
databaseHelper = DatabaseHelper.getInstance(context);
}
public static String CreateTable() {
String query = "Create table " + TableName + " ( " +
Language_Name + " varchar " +
");";
return query;
}
public boolean insertLanguages(LanguageModel object) {
long result = 0;
if (object == null) {
return false;
} else {
database = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Language_Name, object.getLanguageName());
try {
result = database.insert(TableName, null, values);
} catch (SQLiteException e) {
}
database.close();
if (result == 1) {
return true;
} else {
return false;
}
}
}
}
所谓的屏幕
private void initialize() {
actionBar.hide();
languageTable = new LanguageTable(context);
tvMessage = (TextView) findViewById(R.id.tv_message);
rlRoot = (RelativeLayout) findViewById(R.id.rl_splash_root);
rlRoot.setOnClickListener(SplashScreen.this);
//
insertData();
}
private void insertData() {
arrLanguages = context.getResources().getStringArray(R.array.language_array);
for (int i = 0; i < arrLanguages.length; i++) {
languageModel = new LanguageModel(arrLanguages[i]);
result = languageTable.insertLanguages(languageModel);
}
}
请帮我找出问题所在。 感谢
答案 0 :(得分:2)
您需要在帮助程序上调用getWritableDatabase()
或getReadableDatabase()
来实际创建数据库文件。 When is SQLiteOpenHelper onCreate() / onUpgrade() run?
还要考虑删除帮助程序onCreate()
中的try-catch。如果出现问题,则需要抛出异常而不要忽略。