I wrote a method in my database manager that is suppose to return the total amount of rows in a table called homeIcons; but i noticed that it returns 0 when there are 0, 1 there is 1, and then 10 when there are 3? so something is wrong with my method.. please see below:
public int getHomeScreenTotal (){
SQLiteDatabase db=this.getReadableDatabase();
Cursor c = db.rawQuery("select count(*) as count from "+ homeIcons,null);
c.moveToFirst();
int total = c.getInt(0);
return total;
}
EDIT
so i edited my code.. and i have rewritten this method in just about every way possible.. The problem is not that it isn't returning the right amount of rows, because it is.. it is just that it is returning the number in binary.. instead of 3, it returns 11 instead of 5 it returns 101 .. UHG!!!! i just want an int! I can't tell if this is a bug in the adroid/java method for accessing a SQLite DB or if i am missing something.. I have even tried duck punching it to an int, but to no avail.. :(
EDIT
ok i just tried to force the binary to an int using the following method:
public int getHomeScreenTotal (){
SQLiteDatabase db=this.getReadableDatabase();
int rows;
String bin = ""+ db.compileStatement("SELECT COUNT(*) FROM " + homeIcons).simpleQueryForLong();
rows = Integer.parseInt(bin, 2);
return rows;
}
this throws an Error of
java.lang.NumberFormatException: Invalid int: "7"
where the "7" is, is actually the number it is suppose to return.. if i have 5 rows i get an error of Invalid int "5"; ect..
You'll be much happier making the database do the lifting for you.
String query = "select count(*) from " + homeIcons;
you can get the number of rows from SQLite by executing the following query:
SELECT count(*) as count FROM homeIcons;
it will return a table containing one row, which contains only the number of rows in your homeIcons table:
+---------+
| count |
+---------+
| ### |
+---------+
To use this code in your application, execute:
Cursor c = db.rawQuery("SELECT count(*) AS count FROM "+ homeIcons,null);
c.moveToFirst();
int total = c.getInt(0);
EDIT
to get the decimal number out of the binary that is returned, use:
String bin = "" + c.getInt(0);
int total = Integer.parseInt(bin, 2);
Related
I want to check if there's a record in my table Users corresponding to an id_user, in case there isn't I will add it. The problem is that my Cursor.getCount() returns 1 and it doesn't make sense because my table is completely empty.
Cursor c = db.rawQuery("SELECT count(*) FROM Users WHERE id_user = '"
+ jsonObj.getString("id_user") + "'", null);
Log.i("getUser cursor",c.getCount() + ""); // it prints 1
c.moveToFirst();
int ic = c.getInt(0);
Log.i("getUser count2", ic + ""); // it prints 0
Why c.getCount() is giving me 1 when there is not absolutely any record. However, c.getInt(0) seems to work fine.
Thanks
Because you are getting a row back in your query.
Select count(*)
will return one rows containing the count of records. The count of records is 0, thus it returns one row, containing the value 0.
Select *
then
c.getCount()
Would return the 0 you are expecting because you are pulling back all rows, (not a count of rows) and there are no rows. But this is a bad approach since it can pull back extra data and might be slow.
in this case
int ic = c.getInt(0); is the proper way to get the data you want.
Why is my getAccountCount only returning 1 when there are multiple entries in my database. Is this not the proper way to get the number of entries in my ACCOUNTS table?
getAccountCount
int getAccountCount() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT COUNT (*) FROM " + ACCOUNTS, null);
int x = cur.getCount();
cur.close();
return x;
}
Calling it from another activity
dbHelper = new DatabaseHelper(this);
txtNo.setText(String.valueOf(dbHelper.getAccountCount()));
Slightly embarrassed with my slip-up so here's an attempt to recover a little dignity ;_;.
In any case apologies for my mistake and thank you for the help. I'm fiddling with a tutorial code which had SELECT * FROM myTable originally but I read somewhere that using SELECT * in a large db could potentially affect performance as SELECT * gives the list of records with all columns from the table whereas SELECT COUNT * just counts the rows. But when I replaced SELECT * FROM myTable with SELECT COUNT (*) FROM myTable I forgot to change the interpretation of cur and just continued under the assumption that my getAccountCount() was fine.
Again, thank you for the help and criticism, both are appreciated. Cheers!
Why is my getAccountCount only returning 1 when there are multiple
entries in my database
Because Cursor.getCount() return number for rows in current cursor instead of count value.
To get COUNT value from cursor use Cursor.getInt with 0 position :
cur.moveToFirst();
int x = mcursor.getInt(0);
This will return nomber of entries in table
int numRows =(int) DatabaseUtils.queryNumEntries(db, "table_name");
You don't want getCount().
Even if the result of Select COUNT (*) is 5, getCOunt() will be 1...
you should rather do something like
if (cursor.moveToFirst()) // data?
System.out.println(cursor.getInt(0);
my table look like this:
Client_Code Oder_ID NoOrd Weight
850458 5 1 12
850458 5 2 12
850458 6 1 5
i want to sum the Weight, but unique par Oder_ID.
so the resultat that i want is 17 = 12 + 5
not 29
how can i do that ?
my code like this;
public int GetPoids()
{
String SQL_syntax = "SELECT SUM("+ DBHelper.KEY_Poids +") as SumPoids FROM " + DBHelper.tableName + " GROUP BY " + DBHelper.KEY_CodeClient +","+DBHelper.KEY_NoOrdre ;
Cursor c = database.rawQuery(SQL_syntax, null);
if (c != null)
c.moveToFirst();
int Poids = c.getInt(0);
c.close();
return Poids;
}
Give a try, First you need to get unique OrderIds then take only one record of that OrderId with one more condition NoOrd=1 (it must have atleast NoOrd=1 in each record)
select sum(Weight) from Table_Name where Order_ID in (select distinct Order_ID from Table_Name) and NoOrd=1
Sorry if it doesn't help you, actually I tried on a online tool due to lack of your database structure.
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.
I am querying several columns in a table for some words (essentially querying m text columns whether they contain n terms which are entered by the user), and I want to rank these rows by how many matches occur.
So I have something like this query :
SELECT *, (COLUMN1 LIKE '%TERM1%') + (COLUMN1 LIKE '%TERM2%') + ... + (COLUMN1 LIKE '%TERMN%') + (COLUMN2 LIKE '%TERM1%') + ... + (COLUMNM LIKE '%TERMN%') AS SCORE
FROM TABLE_NAME
WHERE COLUMN1 LIKE '%TERM1%' OR ... OR COLUMNM LIKE '%TERMN%'
ORDER BY SCORE DESC LIMIT 200;
But this query does not seem to work all the time, sometimes all the results seem to have score 0, even when there are matches. Can anybody suggest what the problem is? I suspect it might be something to do with the type of result of LIKE operator and the type of score column.
Also, is there some better way of doing the same thing without generating this verbose query?
yes there another way using code
try this
long cnt = countdata("COLUMN1 LIKE %TERM1%")
:
public Long countdata(String whereClause) {
long count = 0;
Cursor c = mDb.rawQuery("SELECT count(*) FROM TABLENAME WHERE " + whereClause, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Log.i("Count", c.getString(0));
count = c.getLong(0);
c.moveToNext();
}
c.close();
return Long.valueOf(count);
}