尝试插入值时出现空点错误

时间:2019-06-05 23:30:51

标签: android sqlite android-sqlite

public boolean addInfo(String username, String DOB, String gender, String password) {

            SQLiteDatabase db = this.getWritableDatabase();

            ContentValues contentValues = new ContentValues();

            contentValues.put(UserProfile.Users.col_02, username);
            contentValues.put(UserProfile.Users.col_03, DOB);
            contentValues.put(UserProfile.Users.col_04, gender);
            contentValues.put(UserProfile.Users.col_05, password);

            long res = db.insert(UserProfile.Users.Table_Name, null, contentValues);

            if (res == -1) {
                return false;
            } else {
                return true;
            }

        }




public boolean updateInfo(String id, String username, String DOB, String gender, String password) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put(UserProfile.Users.col_01, id);
        contentValues.put(UserProfile.Users.col_02, username);
        contentValues.put(UserProfile.Users.col_03, DOB);
        contentValues.put(UserProfile.Users.col_04, gender);
        contentValues.put(UserProfile.Users.col_05, password);

db.update(UserProfile.Users.Table_Name, contentValues, "ID = ?", new String[]{id});

        return true;

    }

    public Cursor readAllInfo(String id) {

        SQLiteDatabase db = this.getReadableDatabase();

        String[] projection = {
                UserProfile.Users.col_01,
                UserProfile.Users.col_02,
                UserProfile.Users.col_03,
                UserProfile.Users.col_04,
                UserProfile.Users.col_05
        };

        String selection = UserProfile.Users.col_01 + "=?";

        Cursor cursor = db.query(UserProfile.Users.Table_Name,
                projection,
                selection,
                new String[]{id},
                null,
                null,
                null);

        return cursor;

    }
  public Integer deleteInfo(String id) {
        SQLiteDatabase db = this.getWritableDatabase();

  return db.delete(UserProfile.Users.Table_Name, "ID = ?", new String[]{id});

    }

这些是我的方法,我认为代码没有什么不妥,但是每次我在添加按钮中调用addInfo方法时,它都会说“尝试调用虚拟方法的空点异常” < / em>

2 个答案:

答案 0 :(得分:1)

可能的原因是您声明但未实例化Database Helper对象,即 this

方法可能是扩展SQliteOpenHelper的类的一部分,并且将具有构造函数,假设该类是DBHelper,则在调用这些方法的活动中

你会有类似的东西

DBHelper myDatabaseHelper;
  • 请注意,如果没有调用(调用)方法的代码,则实际名称可能是任何东西。堆栈跟踪(请参见Debug your app - View the system log)还提供了应复制到诸如异常发生位置之类的问题中的信息。

在调用方法之前,您需要实例化(构造)myDatabaseHelper,该方法类似于:-

    myDatabaseHelper = new DBhelper(this); //<<<<<<<<<< You are likely missing this and hence myDatabaseHelper is null.

然后您可以使用

     if (myDatabaseHelper.addInfo("TheUserName","2000-01-01","Female","thepassword"))
         ...... code to run if the info was added 
     { else {
         ... code to run if the user was not added
     }

由于myDatabaseHelper为null,因此尝试访问它时会引发异常(addInfo,如果已实例化/构造,将成为myDatabaseHelper的一部分)

考虑以下示例:-

您的DatabaseHelper(在两个示例运行中将保持不变):-

public class DBHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb";
    public static final int DBVERSION = 1;

    public DBHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE If NOT EXISTS " + UserProfile.Users.Table_Name +
                "(" +
                        UserProfile.Users.col_01 + " INTEGER PRIMARY KEY," +
                        UserProfile.Users.col_02 + " TEXT, " +
                        UserProfile.Users.col_03 + " TEXT," +
                        UserProfile.Users.col_04 + " TEXT," +
                        UserProfile.Users.col_05 + " TEXT" +
                ")"
        ); 
    }

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

    }

    public boolean addInfo(String username, String DOB, String gender, String password) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(UserProfile.Users.col_02, username);
        contentValues.put(UserProfile.Users.col_03, DOB);
        contentValues.put(UserProfile.Users.col_04, gender);
        contentValues.put(UserProfile.Users.col_05, password);
        long res = db.insert(UserProfile.Users.Table_Name, null, contentValues);
        if (res == -1) {
            return false;
        } else {
            return true;
        }
    }

    public boolean updateInfo(String id, String username, String DOB, String gender, String password) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(UserProfile.Users.col_01, id);
        contentValues.put(UserProfile.Users.col_02, username);
        contentValues.put(UserProfile.Users.col_03, DOB);
        contentValues.put(UserProfile.Users.col_04, gender);
        contentValues.put(UserProfile.Users.col_05, password);
        db.update(UserProfile.Users.Table_Name, contentValues, "ID = ?", new String[]{id});
        return true;
    }

    public Cursor readAllInfo(String id) {

        SQLiteDatabase db = this.getReadableDatabase();
        String[] projection = {
                UserProfile.Users.col_01,
                UserProfile.Users.col_02,
                UserProfile.Users.col_03,
                UserProfile.Users.col_04,
                UserProfile.Users.col_05
        };

        String selection = UserProfile.Users.col_01 + "=?";

        Cursor cursor = db.query(UserProfile.Users.Table_Name,
                projection,
                selection,
                new String[]{id},
                null,
                null,
                null);
        return cursor;

    }
    public Integer deleteInfo(String id) {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(UserProfile.Users.Table_Name, "ID = ?", new String[]{id});
    }
}
  • 请注意,您的代码已按上述内容嵌入。

并考虑调用活动(无需实例化myDatabasehelper):-

public class MainActivity extends AppCompatActivity {

    DBHelper myDatabaseHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //myDatabaseHelper = new DBHelper(this); //<<<<<<<<<< 
        myDatabaseHelper.addInfo("UserX","2000-01-01","Unknown","password");
        Cursor csr = myDatabaseHelper.readAllInfo("1");
        DatabaseUtils.dumpCursor(csr);
    }
}

您将获得Null指针异常(NPE),具体如下:-

2019-06-06 15:34:46.235 5658-5658/aso.so5647108356471083 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: aso.so5647108356471083, PID: 5658
    java.lang.RuntimeException: Unable to start activity ComponentInfo{aso.so5647108356471083/aso.so5647108356471083.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean aso.so5647108356471083.DBHelper.addInfo(java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean aso.so5647108356471083.DBHelper.addInfo(java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
        at aso.so5647108356471083.MainActivity.onCreate(MainActivity.java:16)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6669) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

以下行是相关行,它说明已声明为DBhelper的变量为空。

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean aso.so5647108356471083.DBHelper.addInfo(java.lang.String,java.lang.String, java.lang.String, java.lang.String)' on a null object reference

一个简单的更改(取消注释行myDatabaseHelper = new DBHelper(this);并使用:-

public class MainActivity extends AppCompatActivity {

    DBHelper myDatabaseHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myDatabaseHelper = new DBHelper(this); //<<<<<<<<<<
        myDatabaseHelper.addInfo("UserX","2000-01-01","Unknown","password");
        Cursor csr = myDatabaseHelper.readAllInfo("1");
        DatabaseUtils.dumpCursor(csr);
    }
}

可以正常工作,提取添加的数据并将其写入日志,具体方法如下:-

2019-06-06 15:47:22.579 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@791f7af
2019-06-06 15:47:22.580 I/System.out: 0 {
2019-06-06 15:47:22.580 I/System.out:    _id=1
2019-06-06 15:47:22.580 I/System.out:    col02=UserX
2019-06-06 15:47:22.580 I/System.out:    col03=2000-01-01
2019-06-06 15:47:22.580 I/System.out:    col04=Unknown
2019-06-06 15:47:22.580 I/System.out:    col05=password
2019-06-06 15:47:22.580 I/System.out: }
2019-06-06 15:47:22.580 I/System.out: <<<<<

答案 1 :(得分:0)

尝试下面的代码,这里myDatabaseHelper是创建表的那个类的对象。

l1.zip(l2).map { |a,b| a.merge(b) }