1

Basically, I can insert into my database and view all the results using the below method and a SimpleCursorAdapter displaying to a ListView - works totally fine.

// Returns a Cursor containing all JSON strings
public Cursor getAllJSONstrings()
{       
    // Return all JSONstrings ordered by COLUMN_ID
    return ssDatabase.query(TABLE_ROUTINES, new String[] {COLUMN_ROWID, COLUMN_JSON}, null, null, null, null, COLUMN_ROWID);        
}

However, the following method gives nothing less than the NullPointerException every time I query.

The id LogCat tag shows the tag as being what it should be, 1 for the first item etc.

// Return one JSONstring in String form 
public String getJSONstring(long id)
{
    Log.i(TAG, "getJSONstringStart... id=" + id);

    Cursor cursor;

    Log.i(TAG, "Cursor defined");

    /****** NullPointerException LINE ******/
    cursor = ssDatabase.query(TABLE_ROUTINES, null, "_id=" + id, null, null, null, null);

    Log.i(TAG, "Exceed Cursor");

    int index = cursor.getColumnIndex(COLUMN_JSON);

    Log.i(TAG, "index=" + index);

    return cursor.getString(index);
}

For what it's worth, this method getJSONString(long id) is being executed in an AsyncTask. The id it refers to is the id in an OnItemClickListeners onItemClick method.

Any help would be very appreciated, my head has gone square!

Cheers!

mgibson
  • 6,103
  • 4
  • 34
  • 49

2 Answers2

4

You have to do moveToFirst(). Your method is assuming that the cursor's current row pointer is already set to the first row and that getString(index) will return the value of COLUMN_JSON for the first row.

This isn't true. You should never assume that your query returned something. If the selection clause didn't return any rows, then cursor.getCount() will return 0. In addition, the query may throw a SQLite exception. Any time you look at the results of a query, you should enclose your code in

try {

// query
if ((cursor != null) && (cursor.getCount() > 0)) {

    // some operation

}
...

} catch (Exception e) {

}

Joe Malin
  • 8,621
  • 1
  • 23
  • 18
1

Given that the only possible reference to be null is ssDatabase, since cursor is just being assigned and id is a plain long, and assuming that you are using the common SqlliteHelper pattern, my guess is that you may have forgotten to call open() before calling

getJSONstring

fedepaol
  • 6,834
  • 3
  • 27
  • 34
  • Cheers, turns out I did forget that :P I then had to change my cursor, thanks for the input though! – mgibson Dec 19 '12 at 21:58