android sort integers from database from big to small - android

I made an quiz android app where the user get score every time he finish the quiz and after that the score will be saved in the database and after that the user can display the saved score. and my question is how I can display or sort these score on the page score from the biggest score to the smallest.
this is my code where I get the score and name of the user and set it on a textview:
TextView tv1 = (TextView) findViewById(R.id.TextView1);
DbHelper info = new DbHelper(this);
userInfo.open();
String data = userInfo.getData();
userInfo.close();
tv1.setText(data);
my getData method:
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ID2, KEY_NAME, KEY_SCORE};
Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, null);
String result ="";
int TheRow = c.getColumnIndex(KEY_ID);
int TheName = c.getColumnIndex(KEY_NAME);
int TheScore = c.getColumnIndex(KEY_SCORE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(TheRow ) + " " + c.getString(TheName ) + " " + c.getString(TheScore ) + "\n";
}
return result;
}

You can set ascending or descending in the last argument of your query. In your case, your getData() method can return your string with the KEY_SCORE column in descending order by changing the query line to this:
Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, KEY_SCORE + " DESC");
Good Luck!

Related

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 sqlite return number of rows from query

I am trying to build a method to determine if a user exists in an Android sqlite database before inserting, I have tried to build this method to return the number of rows, however If I try a search for like matches like this
String[] columns = new String[] { SCREEN_NAME, NAME, PROFILE_IMAGE_URL,
USER_ID };
Cursor c = friendsDatabase.query(DATABASE_TABLE, columns, SCREEN_NAME
+ " LIKE '" + screenName + "%'", null, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();
return count;
I get the number of rows returned no problem however the minute I look for an exact match like this
String[] columns = new String[] { SCREEN_NAME, NAME, PROFILE_IMAGE_URL,
USER_ID };
Cursor c = friendsDatabase.query(DATABASE_TABLE, columns, SCREEN_NAME
+ " = '" + screenName + "'", null, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();
return count;
I get 0 rows every time no matter if it matches or not, Im not sure if theres something wrong with my SQL or maybe im using the wrong arguments to make the statement, any help would go a long way thanks
Try this code it might work
Using Raw Query
Cursor mCount= db.rawQuery("select count(*) from "+ DATABASE_TABLE +" where "+SCREEN_NAME+"='" + SCREEN_NAME + "'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
Or using the same code but differently
db.query(DATABASE_TABLE , columns, SCREEN_NAME=?, new String[] { SCREEN_NAME}, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();

How to use SQL to search for a value?

I'm trying to learn how to use database in Android and so far I have learned how to fetch all rows of data in the table, but I'm not sure how I'm going to use a SQL query to search for a value that is equal to the string value I pass to the method below?
I wonder if someone could add some simple code how to query the database with SQL in my code? Preciate the help! Thanks!
Something like this: String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH = filePath";
// Read from database
public String readContacts(String filePath){
String[] columns = new String[]{TABLE_ID, TABLE_IMAGE_PATH, TABLE_CONTACT_NAME, TABLE_CONTACT_NUMBER, TABLE_CONTACT_ADDRESS};
Cursor c = db.query(DB_TABLE, columns, null, null, null, null, null);
int id = c.getColumnIndex(TABLE_ID);
int imagePath = c.getColumnIndex(TABLE_IMAGE_PATH);
int name = c.getColumnIndex(TABLE_CONTACT_NAME);
int number = c.getColumnIndex(TABLE_CONTACT_NUMBER);
int address = c.getColumnIndex(TABLE_CONTACT_ADDRESS);
String result = "";
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(id) + " " + c.getString(imagePath) + " " + c.getString(name) + " " + c.getString(number) + " " + c.getString(address);
}
return result;
}
You can search Query
its for exact string
String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH like '"+filePath+"';
if value contains your string
String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH like '%"+filePath+"%';
if value needs from last
String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH like '%"+filePath+"';
if value needs from first
String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH like '"+filePath+"%';
put these
SQLiteDatabase dbR = this.getReadableDatabase();
Cursor cur = dbR.rawQuery("query", null);
return cur
using this cursor you can get value.
you can do that easily by modifying your query code to:
String[] columns = new String[]{TABLE_ID, TABLE_IMAGE_PATH, TABLE_CONTACT_NAME, TABLE_CONTACT_NUMBER, TABLE_CONTACT_ADDRESS};
Cursor cursor = db.query(ANSWERS_TABLE,
columns,
columns[1] + " = ?", new String[]{filePath}, null, null, null);
Take a look here : SQLiteDataBase Query

How do I properly display SQLite query results

I'm a noob to android and i am using a method to display a SQLite query. I want the row entry to display as row#, entryname, qty, amount (1. ferrari 2 $250,000), but instead it displays as (1. ferrari 2 null$250,000). I'm at my wits end because i can't figure out why i'm getting this pesky null. Nothing obvious jumps out at me in either my create entry or get data methods. Any help is greatly appreciated. Here is my code.
My create entry method:
public long createEntry(String coin, String quantity, String value) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, coin);
cv.put(KEY_QUANTITY, quantity);
cv.put(KEY_VALUE, value);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
My getdata method (for displaying in view):
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_VALUE };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iQuantity = c.getColumnIndex(KEY_QUANTITY);
int iValue = c.getColumnIndex(KEY_VALUE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iQuantity) + " " + c.getString(iValue) + "\n";
}
return result;
}
Nothing obvious jumps out at me in either my create entry or get data methods.
Well from your question, if what you are expecting is 4 results separated by spaces then in the following...
ferrari 2 null$250,000
...you clearly have exactly that. If your create / get methods are OK then I'd start by suspecting your data source for the 'value'.
The 'null' is pre-pended to the value, in other words, it appears after the third space. Take a close look at the encoding of your data source and make sure you are handling it correctly.

row id from database

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;
}

Categories

Resources