0

My app crashes when I try to write to the database.

Here is my database helper:

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "alarms.db";
    private static final String TABLE_NAME = "alarm_table";
    private static final String COL_1 = "ID";
    private static final String COL_2 = "NAME";
    //private static final String COL_3 = "DAYS";
    private static final String COL_4 = "RINGTONE";
    private static final String COL_5 = "HOUR";
    private static final String COL_6 = "MINUTE";

    private static final String TABLE_NAME_DAYS = "days_table";
    private static final String DAYS_COL_1 = "MONDAY";
    private static final String DAYS_COL_2 = "TUESDAY";
    private static final String DAYS_COL_3 = "WEDNESDAY";
    private static final String DAYS_COL_4 = "THURSDAY";
    private static final String DAYS_COL_5 = "FRIDAY";
    private static final String DAYS_COL_6 = "SATURDAY";
    private static final String DAYS_COL_7 = "SUNDAY";

    private SQLiteDatabase db;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db = getWritableDatabase();

        db.execSQL("CREATE TABLE "  + TABLE_NAME + " ("
                + COL_1 + " TEXT PRIMARY KEY NOT NULL, "
                + COL_2 + " TEXT NOT NULL, "
                + COL_4 + " TEXT NOT NULL, "
                + COL_5 + " INTEGER NOT NULL, "
                + COL_6 + " INTEGER NOT NULL" +
        ");");

        db.execSQL("CREATE TABLE "  + TABLE_NAME_DAYS + " ("
                + COL_1 + " TEXT PRIMARY KEY NOT NULL, "
                + DAYS_COL_1 + " TEXT, "
                + DAYS_COL_2 + " TEXT, "
                + DAYS_COL_3 + " TEXT, "
                + DAYS_COL_4 + " TEXT, "
                + DAYS_COL_5 + " TEXT, "
                + DAYS_COL_6 + " TEXT, "
                + DAYS_COL_7 + " TEXT"
                +
        ");");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    }

    public boolean addObjectToDB(Alarm inData){
        boolean rValue = true;
        long result;

        Log.i("This is my super tag!!!", "running from addObjectToDB method!!");
        Log.i("This is my super tag!!!", inData.getName());
        Log.i("This is my super tag!!!", inData.getId());

        // ============== CV : start ==============

        ContentValues cv = new ContentValues();

        cv.put(COL_1, inData.getId());
        cv.put(COL_2, inData.getName());
        //     COL_3 - DAYS
        cv.put(COL_4, inData.getRingtone().toString());
        cv.put(COL_5, inData.getHour());
        cv.put(COL_6, inData.getMinute());

        result = db.insert(TABLE_NAME, null, cv);  //I did some extensive testing and this is the point when the app first crashes

        if(result == -1){
            rValue = false;
        }
        else{
            // ============== CV2 : start ==============

            ContentValues cv2 = new ContentValues();
            List<String> days = inData.getDays();

            cv2.put(COL_1, inData.getId());
            cv2.put(DAYS_COL_1, days.get(0));
            cv2.put(DAYS_COL_2, days.get(1));
            cv2.put(DAYS_COL_3, days.get(2));
            cv2.put(DAYS_COL_4, days.get(3));
            cv2.put(DAYS_COL_5, days.get(4));
            cv2.put(DAYS_COL_6, days.get(5));
            cv2.put(DAYS_COL_7, days.get(6));

            result = db.insert(TABLE_NAME_DAYS, null, cv2);

            rValue = result != -1;
        }

        return rValue;
    }
}

These three methods come from MainActivity:

@override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myDB = new DatabaseHelper(this);

    ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager);

    TabLayout tabLayout = (TabLayout)findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
}


@Override
@SuppressWarnings("unchecked")
public void onResume(){
    super.onResume();

    Intent intent = getIntent();
    if(intent.hasExtra("AlarmList")){
        AlarmList = (List<Alarm>) intent.getSerializableExtra("AlarmList");
        Toast.makeText(MainActivity.this, "on resume..!", Toast.LENGTH_SHORT).show();
        testDB();
    }
    else{
        AlarmList = new ArrayList();
    }
}

private void testDB(){
    boolean check = myDB.addObjectToDB(AlarmList.get(0));

    if(check){
        Toast.makeText(MainActivity.this, "Success!", Toast.LENGTH_SHORT).show();
    }
    else{
        Toast.makeText(MainActivity.this, "Failure.. =(", Toast.LENGTH_LONG).show();
    }
}

I tried checking the crash log for what the issue might be, but it displays the cause of the crash, then it switches real quickly. I did manage to get a half-decent screenshot of the crash log and it's saying:

Unable to resume activity : java.lang.NullPointerException Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabse.insert(java.lang.String, java.lang.String android.c ... the rest if cut off..

What am I doing wrong?

  • 2
    Can u show where and how did u initialize **myDB** ? – Raghavendra Sep 27 '17 at 07:12
  • share your complete code – sumit Sep 27 '17 at 07:14
  • 1
    Possible duplicate of [NullPointerException when trying to insert into SQLite - Android](https://stackoverflow.com/questions/14143886/nullpointerexception-when-trying-to-insert-into-sqlite-android) – Vishal Yadav Sep 27 '17 at 07:20
  • Why are you calling db = getWritableDatabase(); in onCreate this is shadowing problem. use this.db = getWritableDatabase(); but recommended one is call db = getWritableDatabase(); in addObjectToDB method before calling insert and close it using db.close() after success of insert. – Abhishek Sep 27 '17 at 07:20
  • @Raghavendra I edited the original post and added in MainActivity's onCreate, which is where I initialize myDB. –  Sep 27 '17 at 07:50

1 Answers1

0

Missed to initialise db

public boolean addObjectToDB(Alarm inData){

    //You missed this line
    db = getWritableDatabase();

    boolean rValue = true;
    long result;

    Log.i("This is my super tag!!!", "running from addObjectToDB method!!");
    Log.i("This is my super tag!!!", inData.getName());
    Log.i("This is my super tag!!!", inData.getId());

    // ============== CV : start ==============

    ContentValues cv = new ContentValues();

    cv.put(COL_1, inData.getId());
    cv.put(COL_2, inData.getName());
    //     COL_3 - DAYS
    cv.put(COL_4, inData.getRingtone().toString());
    cv.put(COL_5, inData.getHour());
    cv.put(COL_6, inData.getMinute());

    result = db.insert(TABLE_NAME, null, cv);  //I did some extensive testing and this is the point when the app first crashes

    if(result == -1){
        rValue = false;
    }
    else{
        // ============== CV2 : start ==============

        ContentValues cv2 = new ContentValues();
        List<String> days = inData.getDays();

        cv2.put(COL_1, inData.getId());
        cv2.put(DAYS_COL_1, days.get(0));
        cv2.put(DAYS_COL_2, days.get(1));
        cv2.put(DAYS_COL_3, days.get(2));
        cv2.put(DAYS_COL_4, days.get(3));
        cv2.put(DAYS_COL_5, days.get(4));
        cv2.put(DAYS_COL_6, days.get(5));
        cv2.put(DAYS_COL_7, days.get(6));

        result = db.insert(TABLE_NAME_DAYS, null, cv2);

        rValue = result != -1;
    }

    return rValue;
}
Abhishek
  • 3,348
  • 3
  • 15
  • 34
  • I had db = getWritableDatabase(); in that method to begin with. When it didn't work I tried moving it to the onCreate method, which also didn't work. I changed it back and it still doesn't work. –  Sep 27 '17 at 07:48
  • I can't catch the error, because it blinks and disappears too quickly. However, I tried changing phones from Huawei to a Samsung - and it works just fine on the Samsung.. The Huawei says "E/ZipFileCache: init failed when open zip file." and "E/HAL: hw_get_module_by_class: lib loaded: /system/lib/hw/gralloc.msm8916.so" and " E/HAL: hw_get_module_by_class: lib loaded: /system/lib/hw/gralloc.msm8916.so". The Samsung doesn't. I'm guessing this might have to do with the problem? Possibly some sort of permissions issue? –  Sep 27 '17 at 12:48
  • Please check https://stackoverflow.com/questions/33669464/android-logcat-error-zipfilecache-init-failed-when-open-zip-file-device-spec this link also talk abou huwai. – Abhishek Sep 27 '17 at 12:53
  • I already checked out that thread. It doesn't seem to have any solution to the problem, just people saying "That happened on my Huawei too"... So Huawei phones can't use SQLite? –  Sep 27 '17 at 12:55
  • As per comment it say it is relate with huwai devices not a development problem. – Abhishek Sep 27 '17 at 12:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/155423/discussion-between-abhishek-and-phrosen). – Abhishek Sep 27 '17 at 12:55