我正在为我的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());
编辑1:
我可以使用以下方法调用创建数据库表吗?
//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;
}
答案 0 :(得分:3)
您的create table语法中有一个额外的字符,
。您需要从语法
你的语法,
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) );";
现在你的语法准备好了。
答案 1 :(得分: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");
}
}
答案 2 :(得分:0)
主要问题是onCreate没有被执行。
实际上,除非你在SQLiteOpenHelper类上调用getWritableDatabase或getReadableDatabase方法,否则根本不会调用onCreate:
myDbHelper.getWritableDatabase();
或
myDbHelper.getReadableDatabase();
onCreate不会从其构造函数中调用,当您尝试访问(读/写)数据库时,它会由Android框架调用。