我有一个将联系人保存到SQlite数据库的应用程序。
我有一个Database.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 AUTOINCREMENTs" +
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);
}
}
从另一个类(扩展了Activity)我调用了createEntry()方法:
Boolean diditwork=true;
try{
Database entry = new Database(Main_Activity.this);
entry.open();
entry.createEntry(number , name);
entry.close();
}catch(Exception e ){
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();
}
}
但我有一个问题,logcat显示错误..“没有这样的表:MY_TABLE”
如何解决这个问题? 我必须调用onCreate(db)方法吗?
或者该做什么?
答案 0 :(得分:1)
您应该将关键字AUTOINCREMENTs更改为AUTOINCREMENT。你有额外的s。此外,您应该在列名称和声明之间留一个空格。我认为这会阻止创建表。