我找到了this SQLiteOpenHelper 类的优秀示例,它的文档非常详细,我想我可以将它用于我的应用程序;问题是我仍在努力确定我的应用程序创建的数据库是否已经存在
我的应用程序有一个主要 Activity Java 类[想象中的名称]“ActivityMain
”,目前调用 void dbTest();
public void DBTest() {
SQLiteDatabase myDB = null;
/* Create a Database. */
try {
myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ DATABASE_TABLE
+ " (" + KEY_ID + " integer primary key autoincrement, "
+ KEY_SCRIPT_NAME + " text, " + KEY_SCRIPT_BODY + " text, "
+ KEY_SU_NEEDED + " short);");
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ DATABASE_TABLE
+ " (" + KEY_SCRIPT_NAME
+ ", " + KEY_SCRIPT_BODY
+ ", " + KEY_SU_NEEDED + ")"
+ " VALUES ('CPU information', 'cat /proc/cpuinfo', 1);");
/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);
int scriptName = c.getColumnIndex("name");
// Check if our result was valid.
c.moveToFirst();
// cursor left as it came from the database because it starts at the row before the first row
ArrayList<String> sData = new ArrayList<String>();
if (c != null) {
do {
String Name = c.getString(scriptName);
sData.add(Name);
} while (c.moveToNext());
}
ListView lv = (ListView) findViewById(R.id.mainListView);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, sData));
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
} catch (Exception e) {
Log.e("Error", "Error", e);
} finally {
if (myDB != null)
myDB.close();
}
在那里它创建数据库并插入一行然后将其显示回 ListView 中,目前这只会在每次启动应用程序时插入同一行,所以我想检查数据库是否已经存在。
我希望数据库以一些初始值开始,这就是我插入数据的原因,用户可以根据需要删除它
因此,在我的“ActivityMain
”类中,我想从我使用过的“DatabaseHelper
”类中调用 createDataBase();
方法来自链接的示例,但不能
是不是类似:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
try {
createDataBase();
catch(SQLiteException e){
// database doesn't exist yet.
return false;
}
我在“ActivityMain
”类中有一个 bool 函数,它工作正常,但我不确定这是正确的方法,实际上应该通过辅助类
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {
// database doesn't exist yet.
return false;
}
return checkDB != null ? true : false;
}
有人可以给我一些指示吗?
非常感谢:)
最佳答案
您可以通过使用来查明数据库文件是否存在
File dbFile = context.getDatabasePath(DATABASE_NAME);
if(dbFile.exists()){
// do something
}
这不会告诉您数据库是否有效或任何其他信息。
关于android - 数据库是否存在【如何调用类】,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14242207/