我正在創建一個包含三列的表格。這裏是Dasebase.java類::創建SQlite數據庫時出錯
package digicare.phonebook;
import android.R;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.view.View.OnCreateContextMenuListener;
public class Database {
private static final String DATABSE_NAME ="MY_DB";
private static final String DATABSE_TABLE ="MY_TABLE";
private static final int DATABASE_VERSION=1;
public static final String KEY_ID = "ID" ;
public static final String PHONE_NUM ="NUMBER";
public static final String PERSON_NAME="NAME";
public static final String DATABASE_CREATE =" CREATE TABLE " + DATABSE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
PHONE_NUM + " TEXT NOT NULL, "+
PERSON_NAME + " TEXT NOT NULL)" ;
private DatabaseHelper myHelper;
private final Context mycontext;
private SQLiteDatabase myDB;
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context) {
super(context, DATABSE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+ DATABSE_TABLE);
onCreate(db);
}
}
public Database(Context c){
mycontext=c;
}
public Database open() throws SQLException {
myHelper=new DatabaseHelper(mycontext);
myDB= myHelper.getWritableDatabase();
return this ;
}
public void close(){
myHelper.close();
}
public long createEntry(String number, String name) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues() ;
cv.put(PERSON_NAME, name);
cv.put(PHONE_NUM,number);
return myDB.insert(DATABSE_TABLE, null, cv);
}
}
從其他類我稱之爲createEntry()方法在數據庫中插入一行但該行logcat中給出了錯誤:「任何這樣的表:MY_TABLE」
通過我稱爲createEntry方法的代碼段:
btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String number =edtxt_num.getText().toString();
String name =edtxt_name.getText().toString();
//number and name
Boolean diditwork=true;
try{
Database entry = new Database(enter_data.this);
entry.open();
entry.createEntry(number , name);
entry.close();
}catch(Exception e){
Log.w("error", e.getMessage());
diditwork=false;
}finally{
if (diditwork){
Dialog d = new Dialog(getApplicationContext());
d.setTitle("Ring Manager");
TextView tv = new TextView(getApplicationContext()) ;
tv.setText("Saved");
d.setContentView(tv);
d.show();
}
}
}
});
我可以先創建表嗎?通過調用onCreate(db)方法?或者當我插入一個新行時自動創建?
創建表第一次調用getWriteable/getReadable數據庫。 –