0

下面是我的数据库助手类:

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);从我的活动中打电话时。我得到以下空指针。

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): 在 com.myApp.DbAllHelper.getInstance(DbAllHelper.java:38)

4

2 回答 2

1

你为什么用context.getApplicationContext()?我很确定只要使用context就足够了。

于 2013-10-17T18:14:26.140 回答
0

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

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

另外将这部分代码更改为:

    public static DbAllHelper getInstance(Context context)
    {
            if (sInstance == null)
            {
                    sInstance = new DbAllHelper(context);
            }
            return sInstance;
    }
于 2013-10-17T18:17:57.927 回答