0

I am creating a note application where I add note title, details and time. I execute following query in my helper class oncreate method.

dbhelper class

String sql = "CREATE TABLE "+TABLE_NAME+"("+ Col1_ID + " INTEGER PRIMARY KEY AUTOINCREMENT" +","+
            Col2_TITLE+" TEXT" + ","+
            Col3_NOTE+ " TEXT" + ","+
            Col4_TIME+ " TEXT"+
            ")";
    sqLiteDatabase.execSQL(sql);

I am making getInfomration method in helper class to return cursor object which I can use in main activity to retrieve values and to save the note I addNote method.

  public Cursor getInformation(SQLiteDatabase sqLiteDatabase){
    String[] projections = {Col1_ID, Col2_TITLE, Col3_NOTE, Col4_TIME};
    cursor = sqLiteDatabase.query(TABLE_NAME, projections, null, null, null, null, null);
    return cursor;
}
public void addNote(String title, String note, String time, SQLiteDatabase sqLiteDatabase) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(Col2_TITLE, title);
    contentValues.put(Col3_NOTE, note);
    contentValues.put(Col4_TIME, time);
    sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
    sqLiteDatabase.close();
}

In my main activity I retrieve note title and time and display list in recycler view, also I want to know id of each item so I can update respective note item using the ID. But I always get 0 as my note ID for all the items.

sqLiteDatabase = noteDBHelper.getReadableDatabase();
    cursor = noteDBHelper.getInformation(sqLiteDatabase);

    noteLists = new ArrayList<>();

    if(cursor.moveToFirst()){
        do{
            noteObject = new NoteItem() ;
            log.d(tag, cursor.getInt(0)+"");//0 always for all the elements.
            //all elements below are well retrieved
            noteObject.setTitle(cursor.getString(1));
            noteObject.setTime(cursor.getString(3));
            noteObject.setDetails(cursor.getString(2));
            noteLists.add(noteObject);
        }while(cursor.moveToNext());
    }

    noteAdapter = new NoteAdapter(noteLists);
    recyclerView.setAdapter(noteAdapter);

Please give me Idea why I am not able to retrieve ID value from database? Isnt it created automatically with add note method?

Aalap Patel
  • 2,058
  • 2
  • 17
  • 31
  • Did you happen to add `PRIMARY KEY AUTOINCREMENT` after having run your app once? – Mike M. Dec 18 '16 at 02:51
  • can you be more speciffic did not understand your question., – Aalap Patel Dec 18 '16 at 03:04
  • Did you originally have `Col1_ID` as only `INTEGER`, and then later changed it to `INTEGER PRIMARY KEY AUTOINCREMENT`? Either way, try recreating your database - several options to do that: select "Clear data" in the system Settings for your app, uninstall/reinstall the app, increment the database version, whichever. – Mike M. Dec 18 '16 at 03:08
  • 1
    I uninstalled the app and then I see id numbers now. Thank you. – Aalap Patel Dec 18 '16 at 03:27

0 Answers0