Pramod Yadav Pramod Yadav - 1 month ago 8
Android Question

problems with cursor and getting data?

i have created a table and trying to fetch data from it using a cursor as follow:

public Cursor getcontent()
{
Cursor d= database.query(DatabaseHandler.Table_Name2,allColumns,selection, null, null,null,null);
return d;
}
Cursor r=X.getcontent();
if (r.getCount() > 0) {
r.moveToFirst();
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext()==true);
r.close();
} else {
Log.i("TAG"," No value found");
}


I am showing the result in the
textview
to see what data it is fetched. My problem is when i run this code sometimes it shows the data in the
textview
, whatever it has fetched and sometimes it doesn't. Its a 50:50 ratio ,according to me it should show fetched values everytime as data is fetched everytime i don't know what is wrong here ,can someone tell me what's the issue here.

Answer

Check Whether Cursor you are getting is Null or not . and if yes then What is the Count of Cursor. you can Do it by Below Way.

Cursor r = X.getcontent();
if ((r != null) && (r.getCount() > 0)) {
    r.moveToFirst();
    do {
        String id = r.getString(r.getColumnIndex("content_id"));
        al.add(id);
        MainActivity.tt1.append("\n");  
        MainActivity.tt1.append(id);   
    } while (r.moveToNext());
    r.close();
} else {
    Log.i("TAG"," No value found inside Cursor");
}