0

我正在为我的 android 项目创建数据库表,以下是帮助程序类。我能够创建数据库,当我尝试从方法 getSettings() 获取数据时,它显示一个错误,指出没有这样的表“设置”。

但是我在 onCreate 方法中创建了表。之后我调试并发现 OnCreate 方法没有调用。这是我的代码:

public class DataBaseHelper extends SQLiteOpenHelper 
{ 
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window 
//destination path (location) of our database on device 
private static String DB_PATH = "";  
private static String DB_NAME ="testDatabase";// Database name 
private SQLiteDatabase mDataBase;  
private final Context mContext; 

private final String SETTINGS_TABLE = "settings";
private final String SETTINGS_COLUMN_ID = "_id";
private final String SETTINGS_COLUMN_PROFILE_ID = "profileId";

private final String SETTINGS_TABLE_CREATE = "create table " + SETTINGS_TABLE
        + "(" + SETTINGS_COLUMN_ID + " integer primary key autoincrement, "
        + SETTINGS_COLUMN_PROFILE_ID + " varchar(100), );";
private final int SETTINGS_ID = 1;
   public DataBaseHelper(Context context)  
   { 
     super(context, DB_NAME, null, 1);// 1? its Database Version 
     DB_PATH = "/data/data/" + context.getPackageName() + "/databases/"; 
     this.mContext = context; 
  }    

 public void createDataBase() throws IOException 
 { 
   //If database not exists copy it from the assets 

boolean mDataBaseExist = checkDataBase(); 
if(!mDataBaseExist) 
{ 
    this.getWritableDatabase(); 
    this.close(); 
    try  
    { 
        //Copy the database from assests 
        copyDataBase(); 
        Log.e(TAG, "createDatabase database created"); 
    }  
    catch (IOException mIOException)  
    { 
        throw new Error("ErrorCopyingDataBase"); 
    } 
} 
} 
//Check that the database exists here: /data/data/your package/databases/Da Name 
private boolean checkDataBase() 
{ 
    File dbFile = new File(DB_PATH + DB_NAME); 
    //Log.v("dbFile", dbFile + "   "+ dbFile.exists()); 
    return dbFile.exists(); 
} 

//Copy the database from assets 
private void copyDataBase() throws IOException 
{ 
    InputStream mInput = mContext.getAssets().open(DB_NAME); 
    String outFileName = DB_PATH + DB_NAME; 
    OutputStream mOutput = new FileOutputStream(outFileName); 
    byte[] mBuffer = new byte[1024]; 
    int mLength; 
    while ((mLength = mInput.read(mBuffer))>0) 
    { 
        mOutput.write(mBuffer, 0, mLength); 
    } 
    mOutput.flush(); 
    mOutput.close(); 
    mInput.close(); 
} 

//Open the database, so we can query it 
public boolean openDataBase() throws SQLException 
{ 
    String mPath = DB_PATH + DB_NAME; 
    mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY); 
    mDataBase = getWritableDatabase();
    return mDataBase != null; 
} 

@Override 
public synchronized void close()  
{ 
    if(mDataBase != null) 
        mDataBase.close(); 
    super.close(); 
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    mDataBase = db;
    
    System.out.println("Oncreate table");
    try {
        db.execSQL(SETTINGS_TABLE_CREATE);
        InsertSettingsData();
        Log.d(TAG, "onCreate Success create SETTINGS_TABLE_CREATE");
    } catch (Exception e) {
        e.printStackTrace();
    }


}

private int InsertSettingsData() {
    // TODO Auto-generated method stub
    Log.d(TAG, "InsertConfigInitialData");

    try {
        ContentValues resourceTable = new ContentValues();
        resourceTable.put(SETTINGS_COLUMN_ID, SETTINGS_ID);
        resourceTable.put(SETTINGS_COLUMN_PROFILE_ID,
                "123456");
        
        int resourceId = (int) mDataBase.insert(SETTINGS_TABLE, null,
                resourceTable);
        if (resourceId >= 0) {
            return resourceId;
        }

    } catch (Exception e) {
        Log.d(TAG, "InsertConfigInitialData failed : " + e.toString());
        e.printStackTrace();
    }

    return -1;
    
}
public boolean UpdateConfigData() {
    Log.d(TAG, "UpdateConfigData");
    try {
        String condition = SETTINGS_COLUMN_ID + "=" + SETTINGS_ID;

        ContentValues resourceTable = new ContentValues();
        resourceTable.put(SETTINGS_COLUMN_PROFILE_ID,
                "34567");

        int totalUpdated = mDataBase.update(SETTINGS_TABLE,
                resourceTable, condition, null);
        if (totalUpdated > 0) {
            return true;
        } else {
            Log.d(TAG, "UpdateConfigData failed, no records updated");
        }
    } catch (Exception e) {
        Log.d(TAG, "UpdateConfigData failed : " + e.toString());
    }
    return false;
}

public SettingsObject getSettings() {
    Log.d(TAG, "LoadConfigs");
    SettingsObject settings = new SettingsObject();
    String condition = SETTINGS_COLUMN_ID + "=" + SETTINGS_ID;

    try {
        Cursor cursor = mDataBase.query(SETTINGS_TABLE, null,
                condition, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            SettingsObject.setProfile_id(cursor.getString(cursor
                    .getColumnIndex(SETTINGS_COLUMN_PROFILE_ID)));

            cursor.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.d(TAG, "LoadConfigs failed : " + e.getMessage());
    }
    return settings;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    
} 

} 

从我的活动课上,我这样打电话,

        DataBaseHelper myDbHelper = new DataBaseHelper(this);
    myDbHelper = new DataBaseHelper(this);
     
    try {
     
        myDbHelper.createDataBase();
     
    } 
    catch (IOException ioe)
    {
     
        throw new Error("Unable to create database");
     
    }
     
    try 
    {
     
        myDbHelper.openDataBase();
     
    }
    catch(SQLException sqle){
     
    throw sqle;
     
    }
    
    SettingsObject object = myDbHelper.getSettings();
    
    System.out.println("settings profile Id" + object.getProfile_id());
  

编辑

我可以通过以下方法调用创建数据库表吗?

       //Open the database, so we can query it 
     public boolean openDataBase() throws SQLException 
     { 
       String mPath = DB_PATH + DB_NAME; 
       //Log.v("mPath", mPath); 
       mDataBase = SQLiteDatabase.openDatabase(mPath, null,   SQLiteDatabase.CREATE_IF_NECESSARY); 
    //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); 
    mDataBase = getWritableDatabase();
    mDataBase.execSQL(SETTINGS_TABLE_CREATE);
    InsertSettingsData();
      return mDataBase != null; 
  } 
4

3 回答 3

3

您的创建表语法中有一个额外的字符,。您需要从语法中删除最后一个字符(逗号),

你的语法,

private final String SETTINGS_TABLE_CREATE = "create table " + SETTINGS_TABLE
        + "(" + SETTINGS_COLUMN_ID + " integer primary key autoincrement, "
        + SETTINGS_COLUMN_PROFILE_ID + " varchar(100), );";

将其更新为

private final String SETTINGS_TABLE_CREATE = "create table if not exists " + SETTINGS_TABLE
        + "(" + SETTINGS_COLUMN_ID + " integer primary key autoincrement, "
        + SETTINGS_COLUMN_PROFILE_ID + " varchar(100) );";

现在你的语法已经准备好了。

于 2013-02-15T04:36:25.923 回答
0

onCreate()将不会被调用,因为数据库已经存在——如果数据库不存在,您的代码显示您正在从资产中复制数据库,因此当您调用 SQLiteOpenHelper 时,它确实存在并被onCreate()跳过。在您的特殊情况下,您不能依赖 SQLiteOpenHelper 来调度正确的事件,而是需要从资产中复制,然后一次打开并修改架构。

你想要这样的东西:

boolean mDataBaseExist = checkDataBase(); 
if(!mDataBaseExist) 
{ 
    try  
    { 
        //Copy the database from assests 
        copyDataBase(); 
        Log.e(TAG, "createDatabase database created"); 
        SQLiteDatabase db = getWriteableDatabase();
        db.execSQL( ...create ddl... );

    }  
    catch (IOException mIOException)  
    { 
        throw new Error("ErrorCopyingDataBase"); 
    } 
} 
于 2013-02-15T04:54:57.780 回答
0

主要问题是 onCreate 没有被执行。

实际上,除非您在 SQLiteOpenHelper 类上调用 getWritableDatabase 或 getReadableDatabase 方法,否则根本不会调用 onCreate:

myDbHelper.getWritableDatabase();

或者

myDbHelper.getReadableDatabase();

onCreate 不是从它的构造函数中调用的,它是由 Android 框架在您尝试访问(读/写)数据库时调用的。

于 2013-02-15T04:56:49.493 回答