【问题标题】:null pointer exception while creating sqlite database android创建sqlite数据库android时出现空指针异常
【发布时间】:2014-06-16 09:33:28
【问题描述】:

这里是代码。

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编程的新手。请帮助我。

【问题讨论】:

标签: android eclipse sqlite


【解决方案1】:

我认为您使用的是public class DatabaseManager extends android.app.Activity,这是错误的,请将其更改为public class DatabaseManager extends SQLiteOpenHelper

【讨论】:

    【解决方案2】:

    如上所述,更改类扩展的内容。

    你也不需要你的变量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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多