I have a listview in my application that displays records according to the primary key _ID field with the lowest _ID number first. How can I change that so it is the highest _ID number first in the listview? i.e reverse the order.
The db query currently generating the listview is below. Thanks!
public Cursor fetch() {
String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SLOC, DatabaseHelper.FLOC, DatabaseHelper.DSNM, DatabaseHelper.SDATE, DatabaseHelper.STIME };
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToLast();
}
return cursor;
}
use this query:
Cursor c = mDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
You can use rawQuery method to hit any custom query like this and add ORDER BY ASC or DESC as you wish.
public Cursor fetch() {
String queryString = "SELECT * FROM tablename ORDER BY _id DESC"
Cursor cursor = sqLiteDatabase.rawQuery(queryString);
if (cursor != null) {
cursor.moveToLast();
}
return cursor;
}
Related
Here is the code, by this I can retrieve all the columns data from the database. But the problem is that now I want to retrieve only one column, that is my requirement.link1st link 2nd link3rd
word_list = new ArrayList<>();
SQLiteDatabase sd = mydb.getWritableDatabase();
Cursor cursor = sd.query("stickerstable",null, null, null, null, null, null);
if (cursor.moveToFirst()){
do{
word_list.add(new data_items(
cursor.getInt(cursor.getColumnIndex(ID)),
cursor.getString(cursor.getColumnIndex(STICKER_AUTHOR)),
cursor.getString(cursor.getColumnIndex(STICKER_NAME)
)));
}while (cursor.moveToNext());
cursor.close();
sd.close();
}
You can use rawQuery instead of query
Cursor cursor = sd.rawQuery("SELECT YOUR_COLUMN FROM stickerstable",null);
replace YOUR_COLUMN with the name of column you want to retrieve you can even use your Constants like this
Cursor cursor = sd.rawQuery("SELECT " + ID + " FROM stickerstable",null);
or a better way to use String.format
Cursor cursor = sd.rawQuery(String.format("SELECT %s FROM stickerstable", ID),null);
UPDATE
you can use query and specify the column in the second argument
Cursor cursor = sd.query("stickerstable",new String[]{ID}, null, null, null, null, null);
when you pass null means get all columns
I got this :
Cursor c = db.query("Org", null, null, null, null, null, null);
which means I choose a table "Org", but together with this I need to make this :
Cursor c = db.rawQuery(" SELECT "+ id + " AS _id")
because SimpleAdapter need to have an _id field necessarily for some reason or it will crash with an error. How do I combine this 2 into one query?
The second parameter of the query function is the list of columns.
If you want to rename a column, you cannot just blindy return all columns but have to list the desired columns:
String[] columns = new String[] { id+" AS _id", "Name", "Color", "whatever..." };
Cursor c = db.query("Org", columns, null, null, null, null, null);
For your statement : Cursor c = db.query("Org", null, null, null, null, null, null); the second parameter is wrong, you shoukd mention the column names in it.
public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Whereas for,
Cursor c = db.rawQuery(" SELECT "+ id + " AS _id from Org");
means that you Select id and create an alias of it using AS into _id, and you are selecting this id from Org table.
so now you will be able to access the result from this query from the column name _id, and in order to access the result use:
c.moveToFirst();
while (c.moveToNext())
{
System.out.println(c.getString(c.getColumnIndex("_id"));
}
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'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.