每次调用SQLiteOpenHelper onCreate

时间:2013-12-05 10:14:47

标签: android sqlite

我有一个SQLiteOpenHelper类的扩展。下面的代码。

    package com.Parapaparam.association;

    import java.io.IOException;
    import java.io.InputStream;

    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;

    public class DBHelper extends SQLiteOpenHelper {

    private static final String TAG = "Associations";

    private static Context myContext;
    private static final String DB_NAME = "association.db"; 
    private static final int DB_VERSION = 1;    
    private SQLiteDatabase db;


    public DBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);  
        myContext = context;        
    }   

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG, "- onCreate DB -");
        String text;           
        //InputStream is = this.getResources().openRawResource (R.raw.sql);
        try { 
            InputStream inStream = myContext.getResources().openRawResource(R.raw.db);

            int size = inStream.available();

            // Read the entire asset into a local byte buffer.
            byte[] buffer = new byte[size];
            inStream.read(buffer);
            inStream.close();

            // Convert the buffer into a string.
            text = new String(buffer);


        } catch (IOException e) {
            // Should never happen!         
            throw new RuntimeException(e);
        }

        String[] str = text.split(";");
            for (String s : str) { 
                Log.d(TAG, s);
                db.execSQL(s);           
            }
   }


    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub

    }

}

我有一个课程,它会调用我的数据库。

public class DBInteraction {
    private DBHelper dbHelper;
    private SQLiteDatabase db;      


    public DBInteraction(Context context) {
        dbHelper = new DBHelper(context);
    }

    private void openDB() {
        db = dbHelper.getWritableDatabase();
    }
}

每次在我的应用程序启动时,都会调用DBHelper onCreate方法。我有一个例外:

Caused by: android.database.sqlite.SQLiteException: table associations 
already exists: CREATE TABLE associations (_id INTEGER PRIMARY KEY, id_word 
INTEGER, association TEXT)

为什么每次创建数据库时都会调用onCreate方法?

为什么会这样?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。几分钟后寻找答案我删除了整个数据库,再次执行了应用程序(然后创建了一个新的数据库),之后我上传了包含所有数据的数据库。

当我上传好的数据库时,我使用了按钮"将文件推送到设备上"在DDMS中,而不是拖放。我想这可能是我的问题,也可能是你的问题。