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.
Related
I have problem with receiving last data from table in Android SQLite.
Adding values works great but I struggle with receiving last date from table, here is code:
int getKoniec() {
SQLiteDatabase db = this.getReadableDatabase();
String sortOrder = TABELA_koniec + " DESC LIMIT 1";
Cursor cursor = db.query(
TABELA,
new String[] { "koniec" },
null,
null,
null,
null,
sortOrder
);
if(cursor != null) {
cursor.moveToFirst();
}
int koniecINT = cursor.getInt(0);
Log.v("VALUE: ","" + koniecINT);
cursor.close();
return koniecINT;
}
While adding values 10,9,8,7.. output (return koniecINT) is always 10.
Can you help me to solve this problem? Thanks
Try this query
select * from table_name order by row_id desc limit 1
or
mCursor.moveToLast();
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.
Am having a table card with colums id,name, content,status, date.
i want to take id,name,content condition is status <= cards.STATUS also have to sort it by date
How i have to do this.
am doing like,
private Cursor c;
String[] cols = { id,name, content };
c = cardsDB.query(CARDS_TABLE_NAME, cols, "status <=" + Card.STATUS, null, null, null, "date desc");
if (c.moveToFirst()) {
do {
CardArray.add(new Card(c.getInt(0), c.getInt(1), c.getString(2)));
} while (c.moveToNext());
}
c.close();
When you have the complicated query , its better to use raw query not query method.
This is an example of how to implement a raw query:
String query= "Select id,name ,content from CARDS_TABLE_NAME Where status <= ? date desc";
Cursor c= database.rawQuery(query, new String[]{Card.STATUS});
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;
}
I am trying to use this query upon my Android database, but it does not return any data. Am I missing something?
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String select = "Select _id, title, title_raw from search Where(title_raw like " + "'%Smith%'" +
")";
Cursor cursor = db.query(TABLE_NAME, FROM,
select, null, null, null, null);
startManagingCursor(cursor);
return cursor;
This will return you the required cursor
Cursor cursor = db.query(TABLE_NAME, new String[] {"_id", "title", "title_raw"},
"title_raw like " + "'%Smith%'", null, null, null, null);
Alternatively, db.rawQuery(sql, selectionArgs) exists.
Cursor c = db.rawQuery(select, null);
This will also work if the pattern you want to match is a variable.
dbh = new DbHelper(this);
SQLiteDatabase db = dbh.getWritableDatabase();
Cursor c = db.query(
"TableName",
new String[]{"ColumnName"},
"ColumnName LIKE ?",
new String[]{_data+"%"},
null,
null,
null
);
while(c.moveToNext()){
// your calculation goes here
}
I came here for a reminder of how to set up the query but the existing examples were hard to follow. Here is an example with more explanation.
SQLiteDatabase db = helper.getReadableDatabase();
String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";
Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
Parameters
table: the name of the table you want to query
columns: the column names that you want returned. Don't return data that you don't need.
selection: the row data that you want returned from the columns (This is the WHERE clause.)
selectionArgs: This is substituted for the ? in the selection String above.
groupBy and having: This groups duplicate data in a column with data having certain conditions. Any unneeded parameters can be set to null.
orderBy: sort the data
limit: limit the number of results to return
Try this, this works for my code
name is a String:
cursor = rdb.query(true, TABLE_PROFILE, new String[] { ID,
REMOTEID, FIRSTNAME, LASTNAME, EMAIL, GENDER, AGE, DOB,
ROLEID, NATIONALID, URL, IMAGEURL },
LASTNAME + " like ?", new String[]{ name+"%" }, null, null, null, null);