我正在尝试在sqlite中创建表,但是显示错误表示无法创建表。我有相同的代码,但数据库和表名称是不同的。字段相同。还有一个疑问。我无法在包含相同字段的同一数据库中创建不同的表。
DbAdapter.java
代码如下。
public class DbAdapter {
private static final String DATABASE_NAME="bible1";
private static final String DATABASE_TABLE="test1";
private static final int DATABASE_VERSION=1;
public static final String KEY_ID="_id";
public static final String UNITS="units";
public static final String CHAPTERS="chapters";
private static final String CREATE_DATABASE="create table test1 (_id integer primary key autoincrement, units text not null, chapters text not null);";
private SQLiteHelper sqLiteHelper;
private static SQLiteDatabase sqLiteDatabase;
private Context context;
//constructor
public DbAdapter(Context c){
context = c;
}
private static class SQLiteHelper extends SQLiteOpenHelper{
public SQLiteHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_DATABASE);
MakeUnits();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public DbAdapter open() throws SQLException{
try{
sqLiteHelper = new SQLiteHelper(context);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
}catch(NullPointerException ne){
Log.e("error in creating the table", "bye");
}
return this;
}
public void close(){
sqLiteHelper.close();
}
public static long MakeUnits()
{
ContentValues insert1 = new ContentValues();
insert1.put(UNITS, "Unit1");
insert1.put(CHAPTERS, "CHAPTER1");
return sqLiteDatabase.insert(DATABASE_TABLE,null,insert1);
}
public Cursor fetchAllNotes(){
return sqLiteDatabase.query(DATABASE_TABLE, new String[]{KEY_ID,UNITS,CHAPTERS}, null, null, null, null, null);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private DbAdapter Database;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listContent = (ListView) findViewById(android.R.id.list);
Database= new DbAdapter(this);
Database.open();
Cursor c = Database.fetchAllNotes();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
调用open()方法时出错。无法弄清楚。 在logcat中,标记中的错误是“创建表中的错误”
答案 0 :(得分:1)
您尝试在sqLiteDatabase.insert
内拨打MakeUnits
,但此sqLiteDatabase
变量在您致电getWritableDatabase
之前为空。您应该将db
传递给MakeUnits
并在db
上调用插入,而不是sqLiteDatabase
。
答案 1 :(得分:0)
数据库 getWritableDatabase()/ getReadableDatabase()
如果您没有可写数据库的权限,您将获得可读性 D b。
public SQLiteDatabase getWritableDB() {
try {
return helper.getWritableDatabase();
} catch (Exception e) {
return getReadableDB();
}
}
public SQLiteDatabase getReadableDB() {
return helper.getReadableDatabase();
}