-3

Supposedly, I wanted to call a SQLStatement, which eventually will return a ID for a particular row.

public int FindInDatabase(String info){

        Cursor c = db.rawQuery("SELECT id FROM " + DatabaseName + " WHERE " + DataField + " = " + info,null);
        if (c != null){
            c.moveToFirst();
        }
        return c.getInt(1);
    }

Above code cannot be executed successfully, it contains error of Cursor: android.database.sqlite.SQLiteDatabase.rawQuery(java.lang.String, java.lang.String[]) on a null object reference . What is wrong overhere? Thanks.

Phantômaxx
  • 37,352
  • 21
  • 80
  • 110
JackPowell
  • 137
  • 3
  • 13

2 Answers2

0

Try this,

In class where you have extended SqliteOpenHelper. Intialize db object before using it.

public int FindInDatabase(String info){
    SQLiteDatabase db = this.getReadableDatabase();

        Cursor c = db.rawQuery("SELECT id FROM " + DatabaseName + " WHERE " + DataField + " = " + info,null);
        if (c != null){
            c.moveToFirst();
        }
        return c.getInt(1);
    }
Raghavendra
  • 2,250
  • 21
  • 29
  • Hi, thanks for the reply. I got an error of cannot resolve method 'getReadbleDatabse()' .. How to fix this?tq – JackPowell Dec 13 '16 at 12:26
  • @JackPowell okay. In which class you have this method FindInDatabase(). Is it in Activity? or class which extended SqliteOpenHelper.? – Raghavendra Dec 13 '16 at 12:27
  • This method "FindInDatabase()" was implemented in the activity class. The activity class is not extended with SqliteOpenHelper. tq – JackPowell Dec 13 '16 at 12:30
  • @JackPowell can u move this method to class which is extended by SqliteOpenHelper? – Raghavendra Dec 13 '16 at 12:31
0

Need to initialize DB before use of cursor;

SQLiteDatabase db = this.getReadableDatabase();
//cursor usage for db

So your code should be like this:

public int FindInDatabase(String info){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery("SELECT id FROM " + DatabaseName + " WHERE " + DataField + " = " + info,null);
        if (c != null){
            c.moveToFirst();
        }
        return c.getInt(1);
    }
Ready Android
  • 3,350
  • 1
  • 24
  • 39