How can I get every row from a Content Provider? - android

How can I get every row from a content provider ? I tried to do this using Cursor c = getContentResolver().query(uri, null, null, null, null)
and then
String s;
if (c != null && c.moveToFirst())
while (c.moveToNext())
s = c.getString(c.getColumnIndexOrThrow("string"));
c.close();
but it didn't work.Instead of taking all the rows, it was taking only the last one, repeatedly, as many times as the rows-1 of my db.

You are getting "rows-1" because your use of moveToFirst() followed by moveToNext() as the loop control causes you to skip the first row.
If you are seeing all rows of the DB with the same value for column "string", there is either a problem with the code that shows you "s" (which you didn't post) or your DB contains the same value for every row, or you have not implemented query() correctly in your ContentProvider.
You can also use Cursor.getCount() to get the number of rows in the cursor.
This code works for me when run against a content provider backed by a DB:
Cursor c = getContentResolver().query(uri, null, null, null, null);
if (c != null) {
while (c.moveToNext()) {
String s = c.getString(c.getColumnIndexOrThrow("name"));
Log.i("Demo", s);
}
c.close();
}

Related

Android Studio - How can I retrieve data from my database with a WHERE clause? [duplicate]

I am using custom adapter extending cursor adapter for displaying data in listview, to display particular phone number i have passed the id to a method in database class but it is showing
errorandroid.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
while placing debugger in the the method it is not going after the line
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
Can any one help me to solve it.
This is the code:
public String getNumberFromId(int id)
{
String num;
db= this.getReadableDatabase();
Cursor cursor = db.query(scheduletable, new String[] { "ContactNumber" },"_id="+id, null, null, null, null);
cursor.moveToFirst();
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
db.close();
return num;
}
Whenever you are dealing with Cursors, ALWAYS check for null and check for moveToFirst() without fail.
if( cursor != null && cursor.moveToFirst() ){
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
}
Place logs appropriately to see whether it is returning null or an empty cursor. According to that check your query.
Update Put both the checks in a single statement as mentioned by Jon in the comment below.
Update 2 Put the close() call within the valid cursor scope.
try this.. this will avoid an Exception being thrown when the cursor is empty..
if(cursor != null && cursor.moveToFirst()){
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
}
First check this Condition before fetching data
if(cursor!=null && cursor.getCount()>0){
cursor.moveToFirst();
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
}
Check the return value from moveToFirst(), before you try to read anything from the cursor. It looks as if no results are being returned.
a save schema to query Cursors is
// just one
Cursor cursor = db.query(...);
if (cursor != null) {
if (cursor.moveToFirst()) {
value = cursor.getSomething();
}
cursor.close();
}
// multiple columns
Cursor cursor = db.query(...);
if (cursor != null) {
while (cursor.moveToNext()) {
values.add(cursor.getSomething());
}
cursor.close();
}
In case people are still looking:
Instead of searching for "ContactNumber" try searching for Phone.NUMBER. The tutorial has the code with more details: http://developer.android.com/training/basics/intents/result.html
try to uninstall the app and then again test it... actually the sqlite db is created only once when the app is first install... so if you think your logic is current then reinstalling the app will do the trick for you. !!!!

Android: SQLite, cursor.moveToNext() always returns false

The following statement cursor.moveToNext() is always false. I expect the loop to execute once. I've tested that the query actually returns data.
Does anyone know what is the matter?
String query ="SELECT(SELECT COUNT(*) FROM Table1) as count1, (SELECT COUNT(*) FROM Table2) as count2;";
Cursor mCursor = mDb.rawQuery(query, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
while (cursor.moveToNext()) { //<---------------return false here???
String result_0=cursor.getString(0);
}
I know you've solved your problem, but here is a walkthrough of what happened:
Cursor mCursor = mDb.rawQuery(query, null);
// At this point mCursor is positioned at just before the first record.
if (mCursor != null) {
mCursor.moveToFirst();
// mCursor is now pointing at the first (and only) record
}
while (mCursor.moveToNext()) {
String result_0=cursor.getString(0);
}
// The loop above was skipped because `.moveToNext()` caused mCursor
// to move past the last record.
So, in your case of only needing a single record, you only need either mCursor.moveToFirst() OR your mCursor.moveToNext().
you can iterate cursor this way.
if(moveCursor.moveToFirst()){
do{
//your code
}while(moveCursor.moveToNext());
}

How to check if a cursor is empty? [duplicate]

This question already has answers here:
How To Test If Cursor Is Empty in a SQLiteDatabase Query
(6 answers)
Closed 2 years ago.
When I'm trying to get the phone numbers from the contact list of the phone. The problem is, when I'm running the app while the contact list in the phone is empty, the app is stopped. I checked it and this is because the cursor is empty.
How can I check if the cursor is empty or if there are any contacts in the contact list of the phone?
ArrayList<String> lstPhoneNumber = new ArrayList<String>();
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
lstPhoneNumber = new ArrayList<String>();
phones.moveToFirst();
// The problematic Line:
lstPhoneNumber.add(phones.getString(phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER)));
while (phones.moveToNext()) {
lstPhoneNumber.add(phones.getString(phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phones.close();
The general pattern to test for a "valid" cursor is
((cursor != null) && (cursor.getCount() > 0))
The Contacts Provider doesn't return null, but other content providers might do so if they encounter some sort of data error. A content provider should handle Exceptions, set the cursor to zero, and log the Exception, but there's no guarantee.
Use cursor.getCount() == 0. If true, the cursor is empty
I added in a projection so you are only getting the column you need.
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
ArrayList<String> lstPhoneNumber = new ArrayList<String>();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, null, null, null);
if (phones == null)
return; // can't do anything with a null cursor.
try {
while (phones.moveToNext()) {
lstPhoneNumber.add(phones.getString(0));
}
} finally {
phones.close();
}
public boolean isCursorEmpty(Cursor cursor){
return !cursor.moveToFirst() || cursor.getCount() == 0;
}
Try this one. The problem of your code is that it will execute add regardless of the length of the cursor. I enclose the phones.moveToFirst() in if statement since it will return false if cursor is empty or has no record set.
if(phones.moveToFirst()){
do{
lstPhoneNumber.add(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}while(phones.moveToNext())
} else {
//do something else
}
System.out.println("count "+ cursor.getCount());
This will show value of cursor in logcat
cursor.moveToFirst();
if (cursor.isBeforeFirst()) //means empty result set
; //do your stuff when cursor is empty
isBeforeFirst() after a moveToFirst() works well also.
According to the Cursor documentation:
isBeforeFirst():
Returns whether the cursor is pointing to the position before the first row.

What is The use of moveToFirst () in SQLite Cursors

I am a programming newbie
and I found this piece of code in the internet and it works fine
Cursor c=db.query(DataBase.TB_NAME, new String[] {DataBase.KEY_ROWID,DataBase.KEY_RATE}, DataBase.KEY_ROWID+"= 1", null, null, null, null);
if(c!=null)
{
c.moveToFirst();
}
but I am not able to understand the use of the
if(c!=null)
{
c.moveToFirst();
}
part. What does it do exactly , and if I remove the
if(c!=null) { c.moveToFirst(); }
part, the code doesn't work.
The docs for SQLiteDatabase.query() say that the query methods return:
"A Cursor object, which is positioned before the first entry."
Calling moveToFirst() does two things: it allows you to test whether the query returned an empty set (by testing the return value) and it moves the cursor to the first result (when the set is not empty). Note that to guard against an empty return set, the code you posted should be testing the return value (which it is not doing).
Unlike the call to moveToFirst(), the test for if(c!=null) is useless; query() will either return a Cursor object or it will throw an exception. It will never return null.
if (c.moveToFirst()) {
while(!c.isAfterLast()) { // If you use c.moveToNext() here, you will bypass the first row, which is WRONG
...
c.moveToNext();
}
}
Cursor is not a Row of the result of query. Cursor is an object that can iterate on the result rows of your query. Cursor can moves to each row. .moveToFirst() method move it to the first row of result table.
moveToFirst() method moves the cursor to the first row. It allows to perform a test whether the query returned an empty set or not. Here is a sample of its implementation,
if (cursor.getCount() == 0 || !cursor.moveToFirst()) {
return cursor.getLong(cursor.getColumnIndexOrThrow(ID_COLUMN));
cursor.close();
what macio.Jun says is right!
we have code like below:
String sql = "select id,title,url,singer,view,info from cache where id=" + id;
SQLiteDatabase db = getMaintainer().getReadableDatabase();
Cursor query = db.rawQuery(sql, null);
query.moveToFirst();
while(query.moveToNext()){
DBMusicData entity = new DBMusicData();
entity.setId(query.getString(query.getColumnIndex(FIELD_ID)));
entity.setTitle(query.getString(query.getColumnIndex(FIELD_TITLE)));
entity.setSinger(query.getString(query.getColumnIndex(FIELD_SINGER)));
entity.setTitlepic(query.getString(query.getColumnIndex(FIELD_PICURL)));
entity.setInfoUrl(query.getString(query.getColumnIndex(FIELD_INFO)));
entity.setViews(query.getString(query.getColumnIndex(FIELD_VIEW)));
Log.w(tag, "cache:"+ entity.toString());
}
query.close();
query=null;
db.close();
db=null;
If we have only one record in the cache table, query.moveToFirst(); will cause that no record returns.

Android Cursor wont Loop, Application Freezes

So here it goes, i have this application retrieves records from database, i have 5 entries from my database, and retrieved its using this code;
Cursor c = dbconnection.rawQuery("SELECT * from Patients", null);
after that i looped it to retrieve the data pero row in my Database as such;
c.moveToFirst();
while(!c.isAfterLast())
{
//Some code to put records per column in to a Patient Object
c.moveToNext();
}
So my problem is that as it enters the loop my Emulator freezes and as i tried to display per record into a Log, i won't cuz the emulator it self already frozed.
Can somebody enlighten me into this matter, This issue is really really new to me
EDIT
yes already tried what baya and ofir suggested.. they worked out but i have this null error during iteration with this loop code
Cursor c = dbHelper.retrieveAllData();
c.moveToFirst();
while(c.moveToNext())
{
Log.d("dbcheck",Integer.toString(c.getPosition()));
//Log.d("dbcheck",c.getString(c.getColumnIndex("firstname")));
//Log.d("dbcheck",c.getString(c.getColumnIndex("lastname")));
**p.setFname(c.getString(c.getColumnIndex("firstname")));**
p.setMi(c.getString(c.getColumnIndex("middleinitial")));
p.setLname(c.getString(c.getColumnIndex("lastname")));
p.setAddr(c.getString(c.getColumnIndex("address")));
p.setAge(c.getInt(c.getColumnIndex("age")));
p.setMed_history(c.getString(c.getColumnIndex("med_history")));
p.setPat_status(c.getString(c.getColumnIndex("status")));
patientList.add(p);
}
i have a null exception error on the p.setFname() line.. i don't know how it became null where in fact i already displayed it with Log using that code that is commented out..
Just try,
Cursor c = dbconnection.rawQuery("SELECT * from Patients", null);
if (c.getCount() > 0) {
Patient p;
while(c.moveToNext) {
//initialize ur object to store new patient info.
p = new Patient();
p.setFname(c.getString(c.getColumnIndex("firstname")));
//add newly created patient to ur list
patientList.add(p);
}
}
c.close();
Try do it like this:
// return all columns
Cursor cursor = mDb.query(Patients, null, null, null, null, null, null);
if ((cursor != null) && (cursor.getCount() > 0)) {
while(cursor.moveToNext()){
//Some code to put records per column in to a Patient Object
}
cursor.close();
}

Categories

Resources