2

我发现了这个SQLiteOpenHelper 类的优秀示例,它的文档非常好,我想我可以将它用于我的应用程序;问题是我仍在努力确定我的应用程序创建的数据库是否已经存在

我的应用程序有一个主要活动 Java 类 [想象中的命名] ' ActivityMain' 目前调用 voiddbTest();

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”类中,我想从链接的示例中使用的“”类中调用该createDataBase();方法,DatabaseHelper但不能

是不是像:

 @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可以正常工作,但我不确定这是不是正确的方法,实际上应该通过辅助类来完成所有这些

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;
}

有人可以给我一些指示吗?

非常感谢 :)

4

3 回答 3

1

教程很好,但不像官方 API 文档。始终阅读官方文档。教程,为了简单起见,总是省略一些东西(有时是重要的东西)。

如您所见,如果 DB 不存在,getReadableDatabse()和/或getWritableDatabase()将自动调用。onCreate()

这是我如何做到这一点的示例(未经测试,但应该向您展示如何做到这一点):

public class YourDBManager extends SQLiteOpenHelper {

    private SQLiteDatabase db = null;

    public YourDBManager(final Context context, final String dbName, final int dbVersion) {
        super(context, dbName, null, dbVersion);
        db = getWritableDatabase();
    }

    /** Initializes your DB */
    private void initializeDB(final SQLiteDatabase db) throws SQLException {
        // Do whatever you want to do to initialize your DB here
    }

    /** 
     * This method is NOT called directly by you but called by SQLiteOpenHelper, 
     * but by getReadableDatabase()/getWritableDatabase() in case it doesn't exist.
     * Here you do whatever you want to do to initialize the DB the first time it is created.
     */
    @Override
    public void onCreate(final SQLiteDatabase db) throws SQLException {
        Log.i(TAG, "=====DATABASE DOES NOT EXIST: CREATING IT======");
        initializeDB(db);
    }
}

public class YourActivity extends Activity {

    private YourDBManager dbMan = null;

    /** Do NOT call from UIThread! */
    private void initializeDBManager() {
        dbMan = new YourDBManager(this, "mydatabase", 1);
    }
}

希望这可以帮助。

于 2013-01-09T16:58:01.013 回答
1

您可以通过使用找出数据库文件是否存在

File dbFile = context.getDatabasePath(DATABASE_NAME);
if(dbFile.exists()){
// do something
}

这不会告诉您数据库是否有效或其他任何东西。

于 2013-01-09T19:07:03.097 回答
1

我认为你已经以正确的方式做事了。还有一些关于该主题的其他问题(例如查询 Android 数据库是否存在!Android - SQLite 数据库是否存在?)建议打开数据库,然后捕获异常以显示数据库不存在。

于 2013-01-09T21:01:11.600 回答