[英]null pointer exception while creating sqlite database android
这是代码。
public class DatabaseManager extends android.app.Activity
{
public SQLiteDatabase mydatabase ;
private static final Object MODE_PRIVATE = null;
public static final String TABLE_NAME = "Fests";
// this function is called first.
public void createDatabase()
{
try{
mydatabase = openOrCreateDatabase("fests",SQLiteDatabase.CREATE_IF_NECESSARY,null);
System.out.println("no probs with open function.");
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS Fests (FestId VARCHAR,Festname VARCHAR);");
}catch(Exception e)
{
Log.d("creating db","exception caught."+e);
}
}
我在第一行本身即openOrCreateDatabase函数中得到空指针异常,无法弄清原因。 我是android编程的新手,请帮助我。
我认为您正在使用public class DatabaseManager extends android.app.Activity
,将其更改为public class DatabaseManager extends SQLiteOpenHelper
,这是错误的
如上所述,更改您的课程扩展范围。
您也不需要变量mydatabase
。 该类中已经有一个名为database
的类。 如果您提供名称和版本,它将为您处理它的创建。
例如
private static final String DATABASE_NAME = "Name.db";
private static final int DATABASE_VERSION = 2;
/**
* this gets called automatically on opening the database
*
* @param context
*/
public DatabaseManager(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// if the database does not exist this method is called to create it
@Override
public void onCreate(SQLiteDatabase database) {
for (String CREATE_TABLE : CREATE_TABLES)
{
database.execSQL(CREATE_TABLE);
}
}
// when the version changes this method updates the version number and
// creates a log entry
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(SQLiteHelper.class.getName(), "Upgrading database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data");
for (String TABLE: TABLES)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
}
onCreate(db);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.