row id from database - android

i am trying to do a query of my database for a string lets call it "Test" and then find out what row that particular string is in and save that number to use. I thought i had this figured out before but now it is not working for some reason and i get an error saying no such column "Test".
here is my code
public String getRow(String value){
ContactDB db = new ContactDB(this);
db.open();
Cursor curs = db.getId(value);
String test = curs.getString(curs.getColumnIndex(db.NAME));
curs.close();
Log.v("Contact", "Row ID: " + test);
db.close();
return test;
}
"Test" is sent into that as value
this is in my database
//---retrieve contact id---
public Cursor getId(String where){
Cursor c = db.query(DATABASE_TABLE, new String[] {ID},where,null,null,null,null);
if (c != null)
c.moveToFirst();
return c;
}
i dont remember changing anything from when i first tested it so i dont know why it wont work now

There are 2 errors that i could notice:
In the query
Cursor c = db.query(DATABASE_TABLE, new String[] {ID},where,null,null,null,null);
only the ID column is selected whereas you are trying to fetch details for column NAME
String test = curs.getString(curs.getColumnIndex(db.NAME));
include the name column as well in the select clause : something like
Cursor c = db.query(DATABASE_TABLE, new String[] {ID,NAME},where,null,null,null,null);
In the where clause you need to write the condition string excluding "where"
in your case String where contains value "Test". Hence the filter condition should be as
String whereClasue = NAME + " = '" + where + "'";
The query should be something like this:
public Cursor getId(String where){
Cursor c = db.query(DATABASE_TABLE, new String[] {ID,PHONE_NUMBER,NAME},NAME + " = '" + where + "'",null,null,null,null);
if (c != null)
c.moveToFirst();
return c;
}

Related

Android: get all contacts by IM

I want to query to Contacts content provider such that if a contact has IM whose type is equal to "XYZ".
I tried below way but I am not getting any result:
Uri uri1 = ContactsContract.Contacts.CONTENT_URI;
String[] projection1 = null;
String selection1 = null;
String[] selectionArgs1 = null;
String sortOrder1 = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor cursor1 = context.getContentResolver().query(uri1, projection1, selection1, selectionArgs1, sortOrder1);
if (cursor1 != null && cursor1.getCount() > 0) {
while (cursor1.moveToNext()) {
int contactId = Integer.parseInt(cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts._ID)));
Uri uri2 = ContactsContract.Data.CONTENT_URI;
String[] projection2 = null;
String selection2 = ContactsContract.CommonDataKinds.Im.PROTOCOL + " = ? AND " + ContactsContract.Contacts._ID + " = ? ";
String[] selectionArgs2 = new String[]{"XYZ", contactId + ""};
String sortOrder2 = null;
Cursor cursor2 = context.getContentResolver().query(uri2, projection2, selection2, selectionArgs2, sortOrder2);
if (cursor2 != null && cursor2.getCount() > 0) {
while (cursor2.moveToNext()) {
Log.i(TAG, "Name: " + cursor2.getString(cursor2.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)));
}
DatabaseUtils.dumpCursor(cursor2);
}
}
cursor1.close();
}
I am not getting any log with above code.
PS: I am not using built in protocols like AIM, Windows Live, Yahoo or skype. Its my custom Protocol, say it "XYZ".
For this, you need to query the ContactsContract.Data.CONTENT_URI and with the mime type as IM and then the label or type field (not sure) holds that which type of IM like you said 'XYZ' and in the value column you will get the value like a username.
There is a foreign key in this table which is linked to raw contact id of raw_contacts table.
UPDATE
Cursor cursor = getActivity().getApplicationContext().getContentResolver().query(
ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.MIMETYPE + "=?", new String[]{ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE}, null);
if(cursor!=null) {
cursor.moveToFirst();
do {
String value = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
//Types are defined in CommonDataKinds.Im.*
int imppType = cursor
.getInt(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
//Protocols are defined in CommonDataKinds.Im.*
int imppProtocol = cursor
.getInt(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL));
//and in this protocol you can check your custom value
}while (cursor.moveToNext());
cursor.close();
}
Thanks
I have stumbled upon the same problem. Turns out that the protocol should be an Int instead of a String. In case of being a custom one you should use ContactsContract.CommonDataKinds.Im.PROTOCOL_CUSTOM which is an alias for -1.

Getting the result of cursor and turning it into a string for TextView

This is my query :
Cursor nextdate(String Date) {
SQLiteDatabase db = this.getReadableDatabase();
String[] params = new String[]{String.valueOf(Date)};
Cursor cur = db.rawQuery(" SELECT MIN (" + colDateDue + ") FROM " + PAYMENTS + " WHERE " + colDateDue + ">=?", params);
cur.moveToFirst();
return cur;
}
I want to display the result of that query in a TextView but I don't know how to, so naturally I look for an answer. I find a few answers around and come up with this :
DatabaseHelper db = new DatabaseHelper(this);
String str = "";
if (c!= null) {
if (c.moveToFirst()) {
str = c.getString(c.getColumnIndex(db.colDateDue);
}
}
TextView.setText(str);
But I get the error
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Which got me a bit confused since the usual fix for that error is using cur.moveToFirst(); which is used in both instances... what am I doing wrong exactly?
try like this:
keep the column index as 0 because that cursor will have only one column.
DatabaseHelper db = new DatabaseHelper(this);
String str = "";
if (c!= null) {
if (c.moveToFirst()) {
str = c.getString(0);
}
}
TextView.setText(str);
You are attempting to use the index of db.colDateDue. However, that does not correlate with your actual query. You can happily pull the first result with:
str = c.getString(0);

Android database query with multiple selection

I know how to query for a single selection with the following:
Cursor cursor = database.query(true, TABLE, COLUMNS, "name = ?", new String[]{"Bob"},null,null,null,null);
But suppose I want to make a function as follows:
public Cursor queryNames(String[] names)
where the function returns a cursor where the name = names[0] OR name = names[1] ... etc. So for example, if I called the function queryNames(new String[] {"Alice","Bob","Charlie"}), the function should return a cursor where the name is any of the three (Alice, Bob, or Charlie). How would I write this? Thanks!
Your method might want to look like this:
public Cursor queryNames(String[] names) {
SQLiteDatabase mDb = this.getReadableDatabase();
String whereStatement = "";
for(int i = 0; i < names.length; i++) {
if (i != (names.length - 1))
whereStatement = whereStatement + "name = ? OR "
else
whereStatement = whereStatement + "name = ?"
Cursor cursor = mDb.query(true, TABLE, COLUMNS, whereStatement, names, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
mDb.close();
return cursor;
}
Hope this helps!
try:
Cursor cursor = db.query(true, TABLE, COLUMNS, "name IN (?)", new String[]{" 'moe', 'larry', 'curly'"}, null, null, null, null);
It would probably be best to build the String[] separately than to guess at the number of names.
Enclose the whole thing in double quotes, the individual names in single quotes, comma-separated.

Skip deleted/empty rows sqlite

I am populating AChartEngine from sqlite database and I need all of the data to be displayed. The problem I'm having is when I delete a record the graph series stops populating at the deleted record. I need to find a way to skip over deleted/empty records and continue populating my graph. I need it to do it the same way listview skips over deleted records and keeps on displaying all rows. I am very new to a lot of this and am having a very difficult time with this. I have tried to write if statements in order to skip deleted/empty rows but nothing seems to work. Thank you for helping!
in my graphing activity:
for (int i = 1; !c.isAfterLast(); i++) {
String value1 = db.getValue1(i);
String value2 = db.getValue2(i);
c.moveToNext();
double x7 = Double.parseDouble(value1);
double y7 = Double.parseDouble(value2);
myseries.add(x7, y7);
}
I am getting error: CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
If I surround with try and catch it will populate rows up until the deleted record.
"EDIT"
in my sqlite database:
public String getValue1(long l) {
String[] columns = new String[]{ EMP_DEPT };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value1 = c.getString(0);
return value1;
}
return null;
}
public String getValue2(long l) {
String[] columns = new String[]{ EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value2 = c.getString(0);
return value2;
}
return null;
}
Your issue is that your safety net for commands on rows that don't exist is to use if (c != null){ and then perform your commands inside that block, but a Cursor request from a query will never come up null, it will instead result in a cursor object with no rows.
A more appropriate solution to use this as your safety net instead if (c.moveToFirst()){ Because the method itself returns a boolean for if the method actually carried itself out in the first place - true if it moved and false if not (which occurs when there's no rows to move into). another check, if you wish, would be to see how many rows the cursor has with c.getCount().
Additionally, you should combine your methods so that you don't make redundant queries to the database:
public String[] getValues(long l) {
String[] results = new String[2];
String[] columns = new String[]{ EMP_DEPT, EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c.moveToFirst()) {
results[0] = c.getString(0);
results[1] = c.getString(1);
} else {
Log.d("GET_VALUES", "No results formed from this query!");
}
return results;
}
You should use a single query to get all values at once:
SELECT Date1 FROM MyTable WHERE id BETWEEN 1 AND 12345
or:
db.query(EMP_TABLE, columns, EMP_ID + " BETWEEN 1 AND " + ..., ...);
Then missing values will just not show up when you iterate over the cursor.

Android- Getting a single value from a database table using cursor

I'm using cursors to retrieve data from a database. I know how to retrieve entire columns to use on listviews and such, but I'm struggling to find a way to retrieve a single value.
Let's say I have a table with two columns ("_id" and "Name") and I have ten records (rows) in that table. How would I get, for example, the Name in the third row? Considering I defined a cursor that reads that table:
public Cursor getMyNameInfo() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String sqlTables = "MyNames";
qb.setTables(sqlTables);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToFirst();
return c;
}
Instead of c.moveToFirst() use c.moveToPosition(2) (Cursor indexes are zero-based hence '2' is the third record).
Remember to check that the Cursor has valid data first though.
EDIT:
Once you've moved the cursor to the 3rd record as I explain above, use the following to just get the value of the "Name" column.
String theName = c.getString(getColumnIndex("Name"));
Cursor cursor = dbHelper.getdata();
System.out.println("colo" + cursor.getColumnCount() + ""
+ cursor.getCount());
cursor.moveToFirst();
if (cursor != null) {
while (cursor.isAfterLast() == false) {
String chktitle = title.trim().toString();
String str = cursor.getString(cursor.getColumnIndex("title"));
System.out.println("title :: "
+ cursor.getString(cursor.getColumnIndex("title")));
System.out.println("date :: "
+ cursor.getString(cursor.getColumnIndex("date")));
System.out.println("desc :: "
+ cursor.getString(cursor.getColumnIndex("desc")));
if (chktitle.equals(str) == true) {
tvAddfavorite.setText("Remove Favorite");
break;
}
cursor.moveToNext();
}
}
cursor.close();
Add a WHERE clause:
qb.appendWhere("_id = 2");
Thanks to the answers above I created the following method to give the value of an item from another column but in the same row.
public String getValueFromColumn(int position, String tableName, String columnToGetValueFrom) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tableName);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToPosition(position);
String neededValue = c.getString(c.getColumnIndex(columnToGetValueFrom));
return neededValue;
}
Hope it helps anyone.

Categories

Resources