我正在创建一个包含三列的表。这是 Dasebase.java 类::
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) 方法????或者它在我插入新行时自动创建????