0

I am fetching data from a database using this code :

Cursor cursor = db.query(News_Table, null, null, null, null, null, null);

if (cursor != null) 
{
    cursor.moveToFirst();
}
allNews = new News[cursor.getCount()];
int i = 0;

while (!(cursor.isLast())) 
{
    allNews[i] = new News(cursor.getInt(0), cursor.getString(2),
            cursor.getString(1));
    cursor.moveToNext();
    i++;
}    

This is how my table looks : enter image description here

But everytime my last row is not being fetched and i get a null pointer exception. Here is the log cat screen : enter image description here

Why is my code running only for n-1 rows correctly and giving a problem on the (n)th row, where n is the total number of rows in my news table.

1
  • You check cursor != null and then three lines later use it as if it couldn't be null with cursor.getCount() either the null check isn't required, or your code cannot handle null values. Commented Jan 16, 2013 at 21:36

2 Answers 2

4

cursor.isLast() will return true when the cursor is on the last row, and so your while loop will stop at that point having not read & processed the last row. typically the pattern for iterating a cursor would be (note this doesn't call moveToFirst() either)

Cursor cursor = getACursor();
int i = 0;
while (cursor.moveToNext()) {
   /// do something with this row
   allNews[i] = new News(cursor.getInt(0), cursor.getString(2),cursor.getString(1));
   i++;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I agree. The NPE is thrown later, probably when the author tries to loop through allNews but the last item is still null.
Yes this code works, but i still didn't understand the flaw in my code, because the same code that i use works somewhere else perfectly in my app. then why not here?
if you have the same while(!last) construct, then its wrong elsewhere as well, perhaps that case doesn't hit the later NPE and so you haven't noticed.
1
while (!(cursor.isLast())) 

I think issue while not of isLast(). You are explicitly saying if not last row.

Change while loop to:

 while (cursor.moveToNext()) {
   //Your code.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.