0

I am developing simple app to retrieve a string from SQLite database and display it in TextView of my main activity. For that, I created method inside class which handles SQLite database, then inside main activity I called the method, but what it does is only to give NullPointerException.

Method inside my SQLite database handler class.

 @Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "CREATE TABLE " + PERSON_TABLE_NAME +
                    "(" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    PERSON_COLUMN_NAME + " TEXT, " +
                    PERSON_COLUMN_GENDER + " TEXT, " +
                    PERSON_COLUMN_AGE + " INTEGER)"
    );

}......////////////   Some  Code...........






public String getAddress(int id) {
    // TODO Auto-generated method stub
    SQLiteDatabase db = this.getReadableDatabase();


    try {
        Cursor cursor =  db.rawQuery("SELECT * FROM " + PERSON_TABLE_NAME + " WHERE " +
                PERSON_COLUMN_ID + "=?", new String[]{Integer.toString(id)});

        if (cursor != null) {
            cursor.moveToFirst();
            return cursor.getString (cursor.getColumnIndex (PERSON_COLUMN_NAME));
        }
    }
    catch (Exception e) {

        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "";
}

My main activity Where I call the method.

button = (Button) findViewById(R.id.addNew);
    button.setText(dbHelper.getAddress(8));
Cœur
  • 32,421
  • 21
  • 173
  • 232
Farid
  • 2,132
  • 1
  • 13
  • 31

1 Answers1

-1

May be your first row does contain a null string at PERSON_COLUMN_NAME(column). Try to increase database version and add rows again.

OR try this:

    String[] columns = {PERSON_COLUMN_ID, PERSON_COLUMN_NAME};
    Cursor res = db.query(PERSON_TABLE_NAME, columns, null, null, null,null, null);
    res.moveToFirst();
    do{
        res.moveToNext();}
    while(res.getString(0) != id)
    return res.getString(1);

P.S. This could have been written in comments but since my reputation is less then 50, i have to write it as answer.

Abhinav Gupta
  • 355
  • 1
  • 3
  • 12