Sort SQLite database by a parameter - android

I have a database with tow parameters one is a string called app_name the other one is an integer of how many times the app was opened.
After running the code
String[] columns = new String[]{KEY_ROWID,KEY_NAME,KEY_OPENED};
Cursor c = database.query(DATABASE_TABLE,columns,null,null,null,null,null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iAppName = c.getColumnIndex(KEY_NAME);
int iTimesOpened = c.getColumnIndex(KEY_OPENED);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result = result+c.getString(iRow)+" "+c.getString(iAppName)+" //"+c.getString(iTimesOpened)+"\n";
}
return result;
result equals:
1 dialer 1
2 whatsapp 7
3 facebook 20
4 google play store 10
I want the result to be sorted by the times opened so it will look like this
1 facebook 20
2 google play store 10
3 whatsapp 7
4 dialer 1
How can i change that order?

Cursor c = database.query(DATABASE_TABLE,columns,null,null,null,null, KEY_OPENED);
The last parameter to query is ORDER BY.
If you want to order by the integer value of the KEY_OPENED column, you can use CAST operator to cast the value of the field into an integer.
Cursor c = database.query(DATABASE_TABLE,columns,null,null,null,null, "CAST( " + KEY_OPENED + " AS INTEGER)");

use this
Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
Refer this documentation to understand more about query method.

Related

SQLite having clause requires group by, but I don't need a group by [duplicate]

This question already has an answer here:
How to get the row# nearest to current time in SQLite for Android rawQuery
(1 answer)
Closed 6 years ago.
Experts,
Here is my goal:
get the value of A from a query, where B=max(B), if the query return 0 row, then set 999999.
If use Method 1, syntax error because no group by clause, but I don't need a group.
If use Method 2, when CONDITIONS are false, namely 0 row, the cursor.getCount() ==1 >0, cannot get 999999.
One way I can think of is add a column C set value 'constant' in tb, then add group by C in Method 1.
But it is totally not grace.
What should I do? Thanks.
Method 1:
Cursor cursor = db.rawQuery("select A, B " +
"from tb " +
"where "CONDITIONS" +
"having B=max(B)", null);
cursor.moveToFirst();
valueA = cursor.getDouble(0);
if (cursor.getCount()==0) valueA = 999999;
cursor.close();
Method 2:
Cursor cursor = db.rawQuery("select A, max(B) " +
"from tb " +
"where "CONDITIONS", null);
cursor.moveToFirst();
valueA = cursor.getDouble(0);
if (cursor.getCount() == 0) valueA = 999999;
cursor.close();
You should place the 'max(b)' function in the select clause, because this is the best way to find the aggregate.
You will get at least one row in the resulting cursor even if the values are NULL. So, you should read the value of 'max(b)' from the cursor and then add the logic.
In your first method, you are using the keyword having which is used with the GROUP BY keyword. So the code is giving you the error.
Having keyword example:
SELECT * FROM Students GROUP BY name HAVING count(name) < 2;
You can use following command:
SELECT column_name FROM table_name where MAX(column_name);
and:
cursor.moveToFirst();
if (cursor.getCount()<1){
valueA= 999999;
}else{
valueA= cursor.getDouble(0);
}
cursor.close();
If use group function you must use group by .
You can use sub query like this ..
Cursor cursor = db.rawQuery("select A , B " +
"from tb " +
"where "CONDITIONS" +
" AND B = (select max(B) from tb)", null);

SQLiteDatabase, Updated Values not matching in select query

I got stuck in a very strange issue. Where i am able to update the db Values when when trying to fetching the rows corresponding to that values i am not getting anything.
In this database, i inserted these rows, the date were 29, june for the last two rows, but when i updated these dates to 15, and tried to fetch the rows corresponding to that date
String where = COL_DATE + " = ?";
String[] args = {"15"};
Cursor cursor = db.query(TABLE_DAILY_EXPENSE, null, where, args, null, null, null);
Then Log.d(TAG, "Cursor count= " + cursor.getCount());gives 0`
Where as by fetching through month, it gives count = 2.
So i concluded, that somewhere after updating the fields, its not matching that updated field for fetching that corresponding row. But why this is happening?? No Idea.
`
The value in the database is a number.
The value you are searching for is a string, which is different.
The Android database API allows only strings as parameters in most places, so you have to insert the number directly into the SQL command:
String where = COL_DATE + " = " + 15;
String[] args = null;

Android SQLite Incrementing Integer Field Read from Query

Disclosure up front, this is a school project.
I have a method in a class that manages the database for a "quzzer" feature in my app, it is intended to increment (or decrement in one case) three integer fields in an SQLite database. It needs to do this independently from the "quizzing functions", so I need to pull the data first, change it, then update it into the database.
The fields are as follows in the database:
"prof_level" - Only acceptable values are 1 to 4 inclusive.
"times_correct" - Only positive numbers.
"times_incorrect" - Only positive numbers.
I can pull the numbers fine from the db then increment them by 1, but when I update, they increment the values in the db by 2 instead, and I've no idea why. Here is the full code of the method:
public void updateCharacterProf(String table, String charToUpdate, boolean isIncreased){
//get character from table
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(table);
String[] projection = {"prof_level", "times_correct", "times_incorrect"};
Cursor c = qb.query(db, projection, "character=='" + charToUpdate + "'", null, null, null,
null, null);
c.moveToFirst();
//check to see if the prof level is at max/min
int profLevel = c.getInt(0);
int correctTimes = c.getInt(1);
int incorrectTimes = c.getInt(2);
//mod prof levels
if (isIncreased){
profLevel++;
correctTimes++;
}
else{
profLevel--;
incorrectTimes++;
}
if (profLevel == 4 && isIncreased){
profLevel = 4;
}
else if (profLevel == 1 && !isIncreased){
profLevel = 1;
}
c.close();
ContentValues values = new ContentValues();
values.put("prof_level", profLevel);
values.put("times_correct", correctTimes);
values.put("times_incorrect", incorrectTimes);
//update db
db.update(table, values, "character=='" + charToUpdate + "'", null);
db.close();
}
I'm hoping that it's just something I don't get about how updating SQLite dbs, but I'm lost at the "var++ == +=2" thing that I'm getting now.
I discovered that the issue was o e of my own creation, I fired the callback that calls this database update twice accidently in the dialog fragment that calls it (once in an onClick method and once in a life cycle onDismiss override.).
Fixing this bug, which happened during another different dateabase related thing, fixed the problem for me.

Selecting Random rows with limit in SQLite

I have went through many related threads and i was not successful yet .
I dont know where i am going wrong , i have the following method to get the rows .
public Cursor getallrows (String fid , String sid , String bid , String pid , String limit)
{
return db.query(DATABASE_ALLPENLIST, new String[] {"rowpos","Peninnerid","issampled","onesymbol","twosymbol","threesymbol","foursymbol","fivesymbol","buildingid","farmid","sampleid","penid"}, "farmid = "+fid+" and sampleid = "+sid+" and buildingid = "+bid+" and penid = "+pid , null, null, null,"RANDOM()",limit);
}
but the above method returns me the correct number of rows mentioned in the limit but not in the Random order , it is returning the first n rows mentioned in the limit variable .
Is this RANDOM() case-sensitive ? But i have also tried with Random() and "RANDOM() LIMIT "+limit in the place of 7th parameter .
Thanks in Advance .
This query should work with return random rows based off if the limit variable is of string type or you can be explicit with it like this:
db.query(DATABASE_ALLPENLIST,
new String[] {"rowpos","Peninnerid","issampled","onesymbol","twosymbol","threesymbol","foursymbol","fivesymbol","buildingid","farmid","sampleid","penid"},
"farmid = "+fid+" and sampleid = "+sid+" and buildingid = "+bid+" and penid = "+pid ,
null,
null,
null,
"RANDOM()",
"1");
or try raw query:
db.rawQuery("Select rowpos, Peninnerid , issampled, onesymbol, twosymbol, threesymbol, foursymbol, fivesymbol, buildingid, farmid, sampleid, penid From " + DATABASE_ALLPENLIST + " Order By RANDOM() LIMIT ?", new String[] {limit});
Doumentation to this API: Link

How to get the sum/total of all records? ANDROID Sqlite

I'd like to get the total of all records. I'd be getting the records from my meal_serving. I'd like to add up all the values. For example, please check this:
Meal Serving
1st row - 8
2nd row - 2
3rd row - 3
Total is: 13
This is what I've got:
public String getTotal() {
String[] column =
new String[]{ KEY_SERVING, "sum(meal_serving)" };
Cursor c =
ourDatabase.query( DATABASE_TABLE, column, null, null, null, null, null );
String result = "";
int iSERVING = c.getColumnIndex( KEY_SERVING );
for ( c.moveToFirst(); ! c.isAfterLast(); c.moveToNext() ){
result = result + c.getString( iSERVING );
}
return result;
}
But only the last record is showing. What's wrong?
You'll need to do
String[]{ "sum(meal_serving) as " + KEY_SERVING };
Instead of your current column string array. That will generate the sum and name it so you can retrieve it.
You might need to make up a unique name if KEY_SERVING is one of your other columns too.

Categories

Resources