如何在返回插入的行ID的同时修复NullPointerException

时间:2018-12-24 05:06:40

标签: android sqlite

在我的android应用中,数据库中有一个名为“ NOTIFICATIONS”的表。当我尝试向该表中插入一行并返回插入的行ID时,它向我显示了空指针异常。下面,我添加了插入方法和异常堆栈跟踪。我的代码有什么问题吗?

我的插入方法:

public long insertDataNotification(Integer id,Integer read,String title,String text,Integer notificationgroup,String date) {
                  opendb();
                  ContentValues contentValues = new ContentValues();
                  contentValues.put("ID",id);
                  contentValues.put("READ",read);
                  contentValues.put("TITLE",title);
                  contentValues.put("TEXT",text);
                  contentValues.put("NOTIFICATIONGROUP",notificationgroup);
                  contentValues.put("DATE",date);
   line 278->     long result = db.insert("NOTIFICATIONS",null ,contentValues);
                  if(result == -1){
                      closedb();
                      return -1;
                  }
                  else {
                      closedb();
                      return result;
                  }
              }

异常堆栈跟踪:

    java.lang.NullPointerException: 

  at com.calendar.shannirmala.calendar.DatabaseHelper.insertDataNotification (DatabaseHelper.java:278)

  at com.calendar.shannirmala.calendar.MyFirebaseMessangingService.onMessageReceived (MyFirebaseMessangingService.java:88)

  at com.google.firebase.messaging.FirebaseMessagingService.zzd (FirebaseMessagingService.java:60)

  at com.google.firebase.iid.zzg.run (zzg.java:4)

  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1162)

  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:636)

  at com.google.android.gms.common.util.concurrent.zza.run (zza.java:6)

  at java.lang.Thread.run (Thread.java:784)

1 个答案:

答案 0 :(得分:0)

我希望这对您有用。

我认为访问您的数据库对象存在问题。

type Model<T> = T extends { id: string } ? never: T;
type Item<T extends Model<T>> = T & { id: string }

像这样初始化您的数据库:

 private static SQLiteDatabase db;

这里Sqliteopenhelper是SQLiteOpenHelper的子类,在该类中添加如下构造函数:

 db = new Sqliteopenhelper(context, "YourDbName.db", null, version).getWritableDatabase();

添加此行而不是opendb()并检查。如果可行,则进行全局初始化。

在DatabaseHelper类中编写这样的函数

 public Sqliteopenhelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

您的方法如下:

public boolean InsertDataIntoTable(String table, ContentValues contentValues) {
        long count = db.insert(table, null, contentValues);

        if (count > 0) {
            Log.e("Class DbUtil", "Data Saved");
            return true;
        } else {
            Log.e("Class DbUtil", "Data not Saved");
            return false;
        }
    }