获取sqlite singleton实例时出现NullPointer异常

时间:2013-10-17 18:11:38

标签: android database sqlite android-sqlite

下面是我的db helper类:

public class DbAllHelper extends SQLiteOpenHelper
{
        private SQLiteDatabase db;
        private static final String DATABASE_NAME = "myDb.db";
        private static final int DATABASE_VERSION = 1;
        private static DbAllHelper sInstance = null;

        public static DbAllHelper getInstance(Context context)
        {

                if (sInstance == null)
                {
                        sInstance = new DbAllHelper(context.getApplicationContext());
                }
                return sInstance;
        }

        private DbAllHelper(Context context)
        {
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {

                db.execSQL("CREATE TABLE " + usersTable + " "
                                + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " + //0
                                "surname TEXT, " + //1
                                "name TEXT); "); //2
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {

        }

        public void insertUser(String name, String surname)
        {
                ContentValues userCV = new ContentValues();
                contactCV.put("surname", surname);
                contactCV.put("name", name);
                db.insert(usersTable, null, userCV );
        }
}

每当我从我的活动中拨打DbAllHelper db = DbAllHelper.getInstance(this);时。 我得到以下nullpointer。

  

10-17 21:05:13.889:E / AndroidRuntime(10025):引起:java.lang.NullPointerException   10-17 21:05:13.889:E / AndroidRuntime(10025):在android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:101)   10-17 21:05:13.889:E / AndroidRuntime(10025):at com.myApp.DbAllHelper.getInstance(DbAllHelper.java:38)

2 个答案:

答案 0 :(得分:1)

您为什么使用context.getApplicationContext()?我非常确定只使用context就足够了。

答案 1 :(得分:0)

也许你是在OnClickListener中调用它,所以你必须使用这样的构造函数从DbAllHelper类创建新对象:

  

DbAllHelper db = DbAllHelper.getInstance(MainActivity.this);

另外,将此部分代码更改为:

    public static DbAllHelper getInstance(Context context)
    {
            if (sInstance == null)
            {
                    sInstance = new DbAllHelper(context);
            }
            return sInstance;
    }