Never entering in cursor.moveToNext() in Android SQLite - java

I'm trying Official Documentation for Android this article. Creating Database, Table and inserting data is working fine. But I'm unable to get data from database. Here is the piece of code to retrieve data from table.
public Person searchDataInDB(String personCellString) {
SQLiteDatabase db = getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
PersonTable.COLUMN_NAME_ID,
PersonTable.COLUMN_NAME_NAME,
PersonTable.COLUMN_NAME_CELL_NO,
PersonTable.COLUMN_NAME_ADDRESS
};
// Filter results WHERE "cell#" = 'Person Cell #'
String selection = SQLiteDBHelper.PersonTable.COLUMN_NAME_CELL_NO + " = ?";
String[] selectionArgs = {"'" + personCellString + "'"};
// How you want the results sorted in the resulting Cursor
// String sortOrder = SQLiteDBHelper.PersonTable.COLUMN_NAME_ID + " DESC";
Cursor cursor = db.query(
SQLiteDBHelper.PersonTable.TABLE_NAME, // The table to query
null, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
String [] names = cursor.getColumnNames();
Log.e("SQLiteDB", "cursorCount = " + cursor.getCount() + ", cursorColumnCount = " + cursor.getColumnCount() + ", Column = " + names[0]);
Person person = null;
while (cursor.moveToNext()) {
int id = (int) cursor.getLong(
cursor.getColumnIndexOrThrow(PersonTable.COLUMN_NAME_ID));
Log.e("SQLiteDB", "moveToNext id = " + id);
String name = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_NAME));
Log.e("SQLiteDB", "moveToNext name = " + name);
String cellNo = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_CELL_NO));
Log.e("SQLiteDB", "moveToNext cell = " + cellNo);
String address = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_ADDRESS));
Log.e("SQLiteDB", "moveToNext address = " + address);
person = new Person(id, name, cellNo, address);
}
cursor.close();
return person;
}
It seems like my app does not enter in while loop i.e. while(cursor.moveToNext() So this method always returns initial value of person which is null. As a result, the first condition is always true from below code
Person person = dbHelper.searchDataInDB(personCellString);
if (person == null) {
Toast.makeText(mContext, "no such record exists in database!", Toast.LENGTH_LONG).show();
} else {
String personDetails = "Name = " + person.getName()
+ "Cell Number = " + person.getCellNumber()
+ "Address = " + person.getAddress();
personDetailsTV.setText(personDetails);
}
I'm using DB Browser for SQLite so I can see the records are successfully adding in the database.
What should I do with the above code to make it work?

What you are doing with this:
String[] selectionArgs = {"'" + personCellString + "'"};
is searching for the string value of personCellString enclosed inside single quotes and not for the actual value of the string personCellString.
Remove the single quotes:
String[] selectionArgs = {personCellString};
You don't have to worry about the string representation of personCellString in the final sql statement that will be constructed and executed which will contain them without explicitly setting them.

Related

Cannot get the max value in a SQLite database

I am trying to get the max id of a table in SQLite in Android. This is how I get it in the database helper:
public int getMaxIncrementation() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String result = "0";
try{
Cursor cursor = sqLiteDatabase.rawQuery("SELECT MAX(id) FROM " +TABLE_INCREMENTATION, new String[]{});
cursor.moveToFirst();
result = cursor.getString(cursor.getColumnIndex(INCREMENTATION_ID));
}catch (Exception ex) {
Log.e("ex", ex.getMessage());
}
return Integer.parseInt(result);
};
This is how I created the table:
private static final String CREATE_TABLE_INCREMENTATION = "CREATE TABLE IF NOT EXISTS " + TABLE_INCREMENTATION
+ "("
+ INCREMENTATION_DATEADDED + " TEXT,"
+ INCREMENTATION_DIRECTION + " INTEGER,"
+ INCREMENTATION_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ INCREMENTATION_USER + " TEXT"
+ ")";
This is the snapshot of my table with data in it:
On debugging, I always get this error:
Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor
is initialized correctly before accessing data from it.
First, since you don't have in the query any ? placeholders then you don't need to pass any parameters to the sql statement, so the 2nd argument of rawQuery() should be null.
Also you must give an alias to the column that your query returns and use it to get the returned value (you can't use INCREMENTATION_ID because it is not the name of the column returned):
Cursor cursor = sqLiteDatabase.rawQuery("SELECT MAX(id) AS maxid FROM " +TABLE_INCREMENTATION, null);
if (cursor.moveToFirst())
result = cursor.getString(cursor.getColumnIndex("maxid"));
Or if you don't use an alias then use 0 as there is only 1 column returned:
Cursor cursor = sqLiteDatabase.rawQuery("SELECT MAX(id) FROM " +TABLE_INCREMENTATION, null);
if (cursor.moveToFirst())
result = cursor.getString(0);

How to sort Uri Array by Date/Time?

Is it possible to sort an Array containing Uri's by date/time?
An Uri in my array looks like:
content://media/external/images/media/65
I have tried Collections.sort() but it wasn't possible with an Uri[]
Edit:
My Uri points to an image stored on the device. I want to sort the images by date and time and show it sorted in an GridView.
You can query the content resolver for modified time.
Uri uri = Uri.parse("content://media/external/images/media/65");
String projection [] = {
MediaStore.Images.Media.DATA
, MediaStore.Images.Media.DISPLAY_NAME
, MediaStore.Images.Media.SIZE
, MediaStore.Images.Media.MIME_TYPE
, MediaStore.Images.Media.DATE_MODIFIED
, DocumentsContract.Document.COLUMN_LAST_MODIFIED
};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if ( cursor==null)
{
return;
}
cursor.moveToFirst();
String data = cursor.getString(0);
String displayName = cursor.getString(1);
String size = cursor.getString(2);
String mimeType = cursor.getString(3);
String dateModified = cursor.getString(4); // null
String dateModified2 = cursor.getString(5);
Toast.makeText(context,
"DISPLAY_NAME: " + displayName
+ "\nDATA: " + data
+ "\nSIZE: " + size
+ "\nmimeType: " + mimeType
+ "\n" +MediaStore.Images.Media.DATE_MODIFIED + ": " + dateModified
+ "\n" +DocumentsContract.Document.COLUMN_LAST_MODIFIED + ": " + dateModified2
, Toast.LENGTH_LONG).show();
cursor.close();
Even uris from the media store deliver null for
MediaStore.Images.Media.DATE_MODIFIED ("date_modified")
hence DocumentsContract.Document.COLUMN_LAST_MODIFIED ("last_modified")
which is good for all.
Add a try and some catch blocks.

Get some contact info data from phone

I need to get list of id, first name, last name, number(or numbers), email, website of an android device contacts. I know by getting id I can query about phone numbers this is not a big deal. But I don't know how I should make query to get all these columns correctly.
I supposed for names I need ContactsContract.CommonDataKinds.StructuredName for email I need ContactsContract.CommonDataKinds.Email.ADDRESS ,for id Contacts and for website ContactsContract.CommonDataKinds.Website.URL.
My code returns strange values like a single digit number for GIVEN_NAME, null for FAMILY_NAME, one of contact numbers for Email.ADDRESS.
However I think the problem is query URI, which one should I use?
ContentResolver cr = getActivity().getContentResolver();
String[] projection = new String[] {
Contacts._ID,
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
ContactsContract.CommonDataKinds.Website.URL,
ContactsContract.CommonDataKinds.Email.ADDRESS};
Cursor nameCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
null,
null,
null);
while (nameCur.moveToNext()) {
String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String email = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
Integer id= nameCur.getInt(nameCur.getColumnIndex(Contacts._ID));
String website = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
//do some work with strings...
}
The problem is that all the sub-tables you're trying to access (Email, Phone, Website, etc.) are actually all stored in a single big table called Data.
All those sub-tables share the same fields Data1-Data15, so by querying on the Phone.CONTENT_URI table, you're only getting Phone info, that's why trying to access StructuredName.GIVEN_NAME on the result is wrong.
Instead you query over the Data.CONTENT_URI table that contains all info, and you differentiate between rows of different data type via the value at Data.MIMETYPE.
See docs here: https://developer.android.com/reference/android/provider/ContactsContract.Data
I'm not sure if you needed the contact's info for all contacts on the device, or for a specific one.
Here's the code to get info of a single contact (you need to assign value to the contactId variable there)
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3};
// query only emails/phones/events
String selection = Data.CONTACT_ID + "=" + contactId + " AND " +
Data.MIMETYPE + " IN ('" + StructuredName.CONTENT_ITEM_TYPE + "', '" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE"', '" + Website.CONTENT_ITEM_TYPE + "')";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);
while (cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1); // full name
String mime = cur.getString(2); // type of data (phone / birthday / email)
String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
String kind = "unknown";
switch (mime) {
case StructuredName.CONTENT_ITEM_TYPE:
String firstName = cur.getString(4);
String lastName = cur.getString(5);
Log.d(TAG, "got name: " + data + " - " + firstName + " " + lastName);
break;
case Phone.CONTENT_ITEM_TYPE:
Log.d(TAG, "got phone: " + data);
break;
case Email.CONTENT_ITEM_TYPE:
Log.d(TAG, "got email: " + data);
break;
case Website.CONTENT_ITEM_TYPE:
Log.d(TAG, "got website: " + data);
break;
}
}
cur.close();
To convert it to run over ALL contacts, simply remove the Data.CONTACT_ID + "=" + contactId part from the selection, and then you'll need to create some HashMap from contactId to an object containing the info about that contact (use the id variable for the key)
here is my solution:
first we need a query for getting all contact id in the table of "raw_contacts"
List<Integer> ret = new ArrayList<Integer>();
ContentResolver contentResolver = getActivity().getContentResolver();
// Row contacts content uri( access raw_contacts table. ).
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI;
// Return _id column in contacts raw_contacts table.
String queryColumnArr[] = {ContactsContract.RawContacts._ID};
// Query raw_contacts table and return raw_contacts table _id.
Cursor cursor = contentResolver.query(rawContactUri, queryColumnArr, null, null, null);
then we query table "data" for extra information for each contact id:
// Data content uri (access data table. )
Uri dataContentUri = ContactsContract.Data.CONTENT_URI;
// Build query columns name array.
List<String> queryColumnList = new ArrayList<String>();
// ContactsContract.Data.CONTACT_ID = "contact_id";
queryColumnList.add(ContactsContract.Data.CONTACT_ID);
// ContactsContract.Data.MIMETYPE = "mimetype";
queryColumnList.add(ContactsContract.Data.MIMETYPE);
queryColumnList.add(ContactsContract.Data.DATA1);
queryColumnList.add(ContactsContract.Data.DATA2);
queryColumnList.add(ContactsContract.Data.DATA3);
queryColumnList.add(ContactsContract.Data.DATA4);
queryColumnList.add(ContactsContract.Data.DATA5);
queryColumnList.add(ContactsContract.Data.DATA6);
queryColumnList.add(ContactsContract.Data.DATA7);
queryColumnList.add(ContactsContract.Data.DATA8);
queryColumnList.add(ContactsContract.Data.DATA9);
queryColumnList.add(ContactsContract.Data.DATA10);
queryColumnList.add(ContactsContract.Data.DATA11);
queryColumnList.add(ContactsContract.Data.DATA12);
queryColumnList.add(ContactsContract.Data.DATA13);
queryColumnList.add(ContactsContract.Data.DATA14);
queryColumnList.add(ContactsContract.Data.DATA15);
// Translate column name list to array.
String queryColumnArr[] = queryColumnList.toArray(new String[queryColumnList.size()]);
// Build query condition string. Query rows by contact id.
StringBuffer whereClauseBuf = new StringBuffer();
whereClauseBuf.append(ContactsContract.Data.RAW_CONTACT_ID);
whereClauseBuf.append("=");
whereClauseBuf.append(rawContactId);
// Query data table and return related contact data.
Cursor cursor = contentResolver.query(dataContentUri, queryColumnArr, whereClauseBuf.toString(), null, null);
last cursor contains all the data of any contact and for get that data we need switch case:
String mimeType =cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
switch (mimeType) {
// Get email data.
case ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE:
// Email.ADDRESS == data1
String emailAddress = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
int emailType = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
data.setDataType(emailType);
data.setDataValue(emailAddress);
ret1.add(data);
con.setEmailList(ret1);
break;
// Get organization data.
case ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE:
// Organization.COMPANY == data1
String company = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
con.setCompany(company);
break;
// Get phone number.
case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE:
// Phone.NUMBER == data1
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Phone.TYPE == data2
int phoneTypeInt = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
data.setDataType(phoneTypeInt);
data.setDataValue(phoneNumber);
ret1.add(data);
con.addPhoneList(ret1);
break;
// Get display name.
case ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE:
// StructuredName.DISPLAY_NAME == data1
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
// StructuredName.GIVEN_NAME == data2
String givenName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
// StructuredName.FAMILY_NAME == data3
String familyName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
ret.add("Display Name : " + displayName);
ret.add("Given Name : " + givenName);
ret.add("Family Name : " + familyName);
break;
// Get website.
case ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE:
// Website.URL == data1
String websiteUrl = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
// Website.TYPE == data2
int websiteTypeInt = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.TYPE));
String websiteTypeStr = getEmailTypeString(websiteTypeInt);
ret.add("Website Url : " + websiteUrl);
ret.add("Website Type Integer : " + websiteTypeInt);
ret.add("Website Type String : " + websiteTypeStr);
break;
}
this is not my compelete code just for getting idea. hope this will help someone!

Android SQLite SELECT Query

I have taken String value from a EditText and set it inside SELECT QUERY after WHERE condition
As
TextView tv = (TextView) findViewById(R.id.textView3);
EditTextet2 et = (EditText) findViewById(R.id.editText1);
String name = et.getText().toString();
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE name = '"+name+"'", null);
c.moveToNext();
tv.setText(c.getString(c.getColumnIndex("email")));
But it doesn't work. Any suggestions?
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst() like #thinksteep mentioned.
This is a complete code for select statements.
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values
String column1 = c.getString(0);
String column2 = c.getString(1);
String column3 = c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
Try using the following statement:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE name = ?", new String[] {name});
Android requires that WHERE clauses compare to a ?, and you then specify an equal number of ? in the second parameter of the query (where you currently have null).
And as Nambari mentioned, you should use c.moveToFirst() rather than c.moveToNext()
Also, could there be quotations in name? That could screw things up as well.
Here is the below code.
String areaTyp = "SELECT " +AREA_TYPE + " FROM "
+ AREA_TYPE_TABLE + " where `" + TYPE + "`="
+ id;
where id is the condition on which result will be displayed.
public User searchUser(String name) {
User u = new User();
SQLiteDatabase db = this.getWritableDatabase(); //get the database that was created in this instance
Cursor c = db.rawQuery("select * from " + TABLE_NAME_User+" where username =?", new String[]{name});
if (c.moveToLast()) {
u.setUsername(c.getString(1));
u.setEmail(c.getString(1));
u.setImgUrl(c.getString(2));
u.setScoreEng(c.getString(3));
u.setScoreFr(c.getString(4));
u.setScoreSpan(c.getString(5));
u.setScoreGer(c.getString(6));
u.setLevelFr(c.getString(7));
u.setLevelEng(c.getString(8));
u.setLevelSpan(c.getString(9));
u.setLevelGer(c.getString(10));
return u;
}else {
Log.e("error not found", "user can't be found or database empty");
return u;
}
}
this is my code to select one user and one only
so you initiate an empty object of your class then
you call your writable Database
use a cursor in case there many and you need one
here you have a choice Use : 1-
if (c.moveToLast()) { } //it return the last element in that cursor
or Use : 2-
if(c.moveToFirst()) { } //return the first object in the cursor
and don't forget in case the database is empty you'll have to deal with that in my case i just return an empty object
Good Luck
Detailed answer:
String[] selectionArgs = new String[]{name};
Cursor c = db.rawQuery(
"SELECT * FROM " + tabl1 +
" WHERE " + name + " = ? ", selectionArgs
);
selectionArgs : this takes the 'name' you desire to compare with, as argrument.
Here note "A Cursor object, which is positioned before the first entry of the table you refer to".
So,to move to first entry :
c.moveToFirst();
getColumnIndex(String ColumnName) : this returns the zero-based column index for the given column name.
tv.setText(c.getString(c.getColumnIndex("email")));
In case, you want to go searching through multiple rows for a given name under 'name' column then use loop as below:
if (cursor.moveToFirst()){
do{
////go traversing through loops
}while(cursor.moveToNext());
}
This should solve the problem.

Can get ID from received phone number, but not group

I have succeded in getting the ID and name from a phone number that is calling in. What I would like to to is to see which groups this ID belongs to. I have tried the following:
//Search for the information about the phone number, save the goupID(s)
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(aNumber));
ContentResolver cr = mService.getContentResolver();
Cursor myCursor = cr.query(uri, new String[]{PhoneLookup._ID, PhoneLookup.DISPLAY_NAME},null, null, null);
myCursor.moveToFirst();
//String contactID = myCursor.getString(myCursor.getColumnIndex(PhoneLookup._ID));
String contactID = myCursor.getString(myCursor.getColumnIndex(ContactsContract.Contacts._ID));
myCursor.close();
//Use the cursor to query for group with help of ID from the Phone look up
myCursor = cr.query(ContactsContract.Groups.CONTENT_URI,
new String[]{ContactsContract.Groups._ID},
ContactsContract.Groups._ID + " = ?",
new String[]{contactID},
null);
//Contact may be in more than one group
nbrOfGroups = myCursor.getCount();
groupName = new String [nbrOfGroups];
The problem is tha second query, where I would like to use the contactID that i found in the phone lookup, to see which groups that contacID belongs to. The result is no group, although the contact is added to a group in my contacs.
Any ideas? :)
Groups._ID is not same as Contact ID, instead it is the index for the table storing all the group information. After you get the contact ID you should get all the group membership for that contact from the data table by using the Group membership mimetype.
After getting the group ids you can query the Groups table to get the TITLE for all the groups
try with this code
//Search for the information about the phone number, save the goupID(s)
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode("123123"));
ContentResolver cr = this.getContentResolver();
Cursor myCursor = cr.query(uri, new String[]{PhoneLookup._ID, PhoneLookup.DISPLAY_NAME},null, null, null);
myCursor.moveToFirst();
//String contactID = myCursor.getString(myCursor.getColumnIndex(PhoneLookup._ID));
String contactID = myCursor.getString(myCursor.getColumnIndex(ContactsContract.Contacts._ID));
myCursor.close();
//Use the cursor to query for group with help of contact ID from the Phone look up
myCursor = cr.query(ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data.CONTACT_ID,
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID},
ContactsContract.Data.CONTACT_ID + " = ? " +
Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'",
new String[]{contactID},
null);
//Contact may be in more than one group
int nbrOfGroups = myCursor.getCount();
int[] groupIds = new int[nbrOfGroups];
int index = 0;
// unfortunately group names are stored in Groups table
// so we need to query again
if (myCursor.moveToFirst()) {
do {
groupIds[index] = myCursor.getInt(1); // Group_row_id column
} while (myCursor.moveToNext());
}
myCursor.close();
// construct the selection
StringBuffer sb = new StringBuffer();
for (int i = 0; i < nbrOfGroups; i++) {
if (i != 0) {
sb.append(",");
}
sb.append(groupIds[i]);
}
String[] groupName = new String [nbrOfGroups];
myCursor = cr.query(ContactsContract.Groups.CONTENT_URI,
new String[]{ContactsContract.Groups.TITLE},
ContactsContract.Groups._ID + " IN (" + sb.toString() + ")",
null, null);
// finally got the names
if (myCursor.moveToFirst()) {
do {
groupName[index] = myCursor.getString(0); // Group_row_id column
} while (myCursor.moveToNext());
}
myCursor.close();

Categories

Resources