I coudn't imagine why my score is not descending. It was the first digit only to sort. help me guys to analyze this code and tell me whats wrong also the answer.
public String getData() {
Cursor c= ourDatabase.query(DATABASE_TABLE, new String[] {KEY_NAME, KEY_SCORE},
null, null, null, null, KEY_SCORE +" DESC");
String result = "";
int iname = c.getColumnIndex(KEY_NAME);
int iscore = c.getColumnIndex(KEY_SCORE);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iname) + " "+ c.getInt(iscore)+ "\n";
}
return result;
}
The problem is probably that KEY_SCORE is being stored as a string and not as a number.
There is more than one way to fix this. Cast the score to an integer or float:
cast(Key_Score as float) desc
Or, if it is an integer with no leading 0s, the following trick works:
len(Key_Score) desc, key_score desc
However, in some databases the len() function might be spelled length() or something else.
Related
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!
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();
I try to get all unique values from database coulmn using SELECT DISTINCT sql command.
But i get exception when my activity is loading, i have this error code in logcat:
05-05 09:08:32.637: E/AndroidRuntime(1314): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workoutlog/com.example.workoutlog.AddWorkOutPage}: android.database.sqlite.SQLiteException: near "SELECT": syntax error (code 1): , while compiling: SELECT * FROM exerciseTable WHERE SELECT DISTINCTexercise_typefromexerciseTable
I think that i have not wrote the command correctly, here is my code:
public String[] getAllExercies() {
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
Cursor c = ourDatabase.query(TABLE_NAME, null, selecet, null, null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
String[] list = new String[c.getCount()-1];
int j = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
list[j] = c.getString(dayExercise);
j++;
}
return list;
}
I think you should first checkout these answers here and here in order to see the working of .query() function.
Please note that while using ourDatabase.query() function, the parameters are as follows:
String Table Name: The name of the table to run the query against
String [ ] columns: The projection of the query, i.e., the columns to retrieve
String WHERE clause: where clause, if none then pass null
String [ ] selection args: The parameters of the WHERE clause
String Group by: A string specifying group by clause
String Having: A string specifying HAVING clause
String Order By by: A string Order By by clause
So your third variable should be a WHERE clause, something like:
String[] args = { "first string" };
Cursor c = ourDatabase.query("TABLE_NAME", null, "exercise_type=?", args, null, null, null);
Since you don't need a WHERE clause, for your purposes you might want to use rawQuery() method instead.
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;
ourDatabase.rawQuery(selecet, null);
Update
Try the answer from here. Do something like this:
Cursor c = ourDatabase.query(true, "exerciseTable", new String[] {"exercise_type"}, null, null, "exercise_type", null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
//... continue with your further code
Hope this helps else please comment.
Issue:
you have not maintained the space between the words.
Explaination:
suppose, String COLUMN_EXERCISE = "exercise";
and String TABLE_NAME = "tbl_workout";
then
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
simply means,SELECT DISTINCTexercisefromtbl_workout
Solution:
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " from " + TABLE_NAME;
Edit:
Kindly use following syntax to fire rawQuery
Cursor c = ourDatabase.rawQuery(selecet,null);
I hope it will be helpful !
You miss all the spaces in your query, you should replace with this:
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;
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.
I'm trying to create a simple Login form, where I compare the login id and password entered at the login screen with that stored in the database.
I'm using the following query:
final String DATABASE_COMPARE =
"select count(*) from users where uname=" + loginname + "and pwd=" + loginpass + ");" ;
The issue is, I don't know, how can I execute the above query and store the count returned.
Here's how the database table looks like ( I've manged to create the database successfully using the execSQl method)
private static final String
DATABASE_CREATE =
"create table users (_id integer autoincrement, "
+ "name text not null, uname primary key text not null, "
+ "pwd text not null);";//+"phoneno text not null);";
Can someone kindly guide me as to how I can achieve this? If possible please provide a sample snippet to do the above task.
DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).
SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
"uname=? AND pwd=?", new String[] {loginname,loginpass});
#scottyab the parametrized DatabaseUtils.queryNumEntries(db, table, whereparams) exists at API 11 +, the one without the whereparams exists since API 1. The answer would have to be creating a Cursor with a db.rawQuery:
Cursor mCount= db.rawQuery("select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass +"'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
I also like #Dre's answer, with the parameterized query.
Use an SQLiteStatement.
e.g.
SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );
long count = s.simpleQueryForLong();
See rawQuery(String, String[]) and the documentation for Cursor
Your DADABASE_COMPARE SQL statement is currently invalid, loginname and loginpass won't be escaped, there is no space between loginname and the and, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as
select count(*) from users where uname=boband pwd=password);
Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.
To use selectionArgs you would do something like
final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";
private void someMethod() {
Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
...
}
Assuming you already have a Database (db) connection established, I think the most elegant way is to stick to the Cursor class, and do something like:
String selection = "uname = ? AND pwd = ?";
String[] selectionArgs = {loginname, loginpass};
String tableName = "YourTable";
Cursor c = db.query(tableName, null, selection, selectionArgs, null, null, null);
int result = c.getCount();
c.close();
return result;
how to get count column
final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;
int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);
This is the most concise and precise alternative. No need to handle cursors and their closing.
If you are using ContentProvider then you can use:
Cursor cursor = getContentResolver().query(CONTENT_URI, new String[] {"count(*)"},
uname=" + loginname + " and pwd=" + loginpass, null, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
If you want to get the count of records then you have to apply the group by on some field or apply the below query.
Like
db.rawQuery("select count(field) as count_record from tablename where field =" + condition, null);
Another way would be using:
myCursor.getCount();
on a Cursor like:
Cursor myCursor = db.query(table_Name, new String[] { row_Username },
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password },
null, null, null);
If you can think of getting away from the raw query.
int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();