simple select query arguments passing issue - android

I am new with android.
I just wanted to take the count of number of rows in table against particular user in DB (uid is column in db).
For this purpose i made following function:
public int getCount(int uid)
{
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid=?";
Cursor c = ourDB.rawQuery(query,uid);
}
But its giving me error:
The method rawQuery(String, String[]) in the type SQLiteDatabase is
not applicable for the arguments (String, int)
also want to know how can i be able to return count from this?
Please help me.

you should use this WAY:
public int getCount(int uid)
{
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid="+uid+"";
Cursor c = ourDB.rawQuery(query,null);
if(c.getCount()>0)
c.moveToFirst();
do{
int id = c.getInt(0);
}while(c.moveToNext());
}

Try this way
public int getCount(int uid){
try{
String query = "select count(*)'count' from "+TABLE_MESSAGES+ " WHERE uid="+uid+"";
Cursor c = ourDB.rawQuery(query,null);
if (c.moveToFirst()) {
return Integer.parseInt(cursor.getString(0));
}
}catch (Throwable e) {
e.printStackTrace();
}
return 0;
}

change your query to:
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid="+uid;
Cursor c = ourDB.rawQuery(query);

The method rawQuery(String, String[]) in the type SQLiteDatabase is
not applicable for the arguments (String, int)
Clearly states you are passing int instead of expected String[]
Cursor c = ourDB.rawQuery(query,new String[]{ uid });

use the query as :
"SELECT * FROM <DB_NAME> WHERE uid="+uid
and then use the getCount() method on the cursor
like :
Cursor csr = db.rawQuery("above query string here");
int count = csr.getCount();

Related

SQLite Query to Get Column Data

Using following query to get column data:
public String getR(String str) {
String strR = "SELECT col_no FROM tracking where col_id = '"+str+"' ORDER BY col_no DESC LIMIT 1";
return strR;
}
In Activity, I am trying to read returned strR :
String string = mydb.getR("1400");
Toast.makeText(SyncAll.this, string, Toast.LENGTH_SHORT).show();
But in Toast, I am getting my Select query itself instead of Record, like this:
SELECT col_no FROM tracking where col_id = '1400' ORDER BY col_no DESC LIMIT 1
May I know ! Where I am doing mistake ?
I tried the same way suggested by prosper k above, and finally got the solution:
public String getR(String str) {
String strR = "SELECT col_no FROM tracking where col_id = '"+str+"' ORDER BY col_no DESC LIMIT 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(strR, null);
if (cursor != null)
cursor.moveToFirst();
strR = cursor.getString(0);
return strR;
}
You're calling the function getR, which is returning the string value strR.
I'm assuming that mydb is an extended object from class SQLiteOpenHelper, and that you have followed the documentation here https://developer.android.com/training/basics/data-storage/databases.html then you'll have to execute the query like:
Cursor cursor = null;
try {
SQLiteDatabase db = this.getWritableDatabase();
synchronized(this) {
cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
col_no = cursor.getInt(0);
}
}
} finally {
if (null != cursor)
cursor.close();
}
return col_no;

How to get row count in sqlite using Android?

I am creating task manager. I have tasklist and I want when I click on particular tasklist name if it empty then it goes on Add Task activity but if it has 2 or 3 tasks then it shows me those tasks into it in list form.
I am trying to get count in list. my database query is like:
public Cursor getTaskCount(long tasklist_Id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) });
if(cursor!=null && cursor.getCount()!=0)
cursor.moveToNext();
return cursor;
}
In My activity:
list_tasklistname.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,
android.view.View v, int position, long id) {
db = new TodoTask_Database(getApplicationContext());
Cursor c = db.getTaskCount(id);
System.out.println(c.getCount());
if(c.getCount()>0) {
System.out.println(c);
Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
task = adapter.getItem(position);
int taskList_id = task.getTaskListId();
taskListID.putExtra("TaskList_ID", taskList_id);
startActivity(taskListID);
}
else {
Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
startActivity(addTask);
}
}
});
db.close();
}
but when I am clicking on tasklist name it is returning 1, bot number of tasks into it.
Using DatabaseUtils.queryNumEntries():
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
or (more inefficiently)
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
In Activity:
int profile_counts = db.getProfilesCount();
db.close();
Use android.database.DatabaseUtils to get number of count.
public long getTaskCount(long tasklist_Id) {
return DatabaseUtils.queryNumEntries(readableDatabase, TABLE_NAME);
}
It is easy utility that has multiple wrapper methods to achieve database operations.
c.getCount() returns 1 because the cursor contains a single row (the one with the real COUNT(*)). The count you need is the int value of first row in cursor.
public int getTaskCount(long tasklist_Id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery(
"SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) }
);
int count = 0;
if(null != cursor)
if(cursor.getCount() > 0){
cursor.moveToFirst();
count = cursor.getInt(0);
}
cursor.close();
}
db.close();
return count;
}
I know it is been answered long time ago, but i would like to share this also:
This code works very well:
SQLiteDatabase db = this.getReadableDatabase();
long taskCount = DatabaseUtils.queryNumEntries(db, TABLE_TODOTASK);
BUT what if i dont want to count all rows and i have a condition to apply?
DatabaseUtils have another function for this: DatabaseUtils.longForQuery
long taskCount = DatabaseUtils.longForQuery(db, "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) });
The longForQuery documentation says:
Utility method to run the query on the db and return the value in the first column of the first row.
public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs)
It is performance friendly and save you some time and boilerplate code
Hope this will help somebody someday :)
Change your getTaskCount Method to this:
public int getTaskCount(long tasklist_id){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?", new String[] { String.valueOf(tasklist_id) });
cursor.moveToFirst();
int count= cursor.getInt(0);
cursor.close();
return count;
}
Then, update the click handler accordingly:
public void onItemClick(AdapterView<?> arg0, android.view.View v, int position, long id) {
db = new TodoTask_Database(getApplicationContext());
// Get task list id
int tasklistid = adapter.getItem(position).getTaskListId();
if(db.getTaskCount(tasklistid) > 0) {
System.out.println(c);
Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
taskListID.putExtra("TaskList_ID", tasklistid);
startActivity(taskListID);
} else {
Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
startActivity(addTask);
}
}
In order to query a table for the number of rows in that table, you want your query to be as efficient as possible. Reference.
Use something like this:
/**
* Query the Number of Entries in a Sqlite Table
* */
public long QueryNumEntries()
{
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.queryNumEntries(db, "table_name");
}
Do you see what the DatabaseUtils.queryNumEntries() does? It's awful!
I use this.
public int getRowNumberByArgs(Object... args) {
String where = compileWhere(args);
String raw = String.format("SELECT count(*) FROM %s WHERE %s;", TABLE_NAME, where);
Cursor c = getWriteableDatabase().rawQuery(raw, null);
try {
return (c.moveToFirst()) ? c.getInt(0) : 0;
} finally {
c.close();
}
}
Sooo simple to get row count:
cursor = dbObj.rawQuery("select count(*) from TABLE where COLUMN_NAME = '1' ", null);
cursor.moveToFirst();
String count = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0)));
looking at the sources of DatabaseUtils we can see that queryNumEntries uses a select count(*)... query.
public static long queryNumEntries(SQLiteDatabase db, String table, String selection,
String[] selectionArgs) {
String s = (!TextUtils.isEmpty(selection)) ? " where " + selection : "";
return longForQuery(db, "select count(*) from " + table + s,
selectionArgs);
}
Once you get the cursor you can do
Cursor.getCount()

How to query sqlite database from array in android

I am using the following, where AuthorName column value i want to find on the basis of AuthorID. catid is an array that contains AuthorID
public Cursor Authorname(String[] catid) {
myDataBase.rawQuery("SELECT AuthorName FROM AUTHOR_NAME WHERE AuthorID = ?",catid);
}
but it return IllegalArgumentException. Can anybody help me to short out this. Thanks in advance.
You can use only one query to get all the users. Here's an example.
private static final String QUERY = "SELECT AuthorName FROM AUTHOR_NAME WHERE AuthorID IN %ids";
public Cursor Authorname(String[] catid) {
// Build the string with all the IDs, e.g. "(1,2,3,4)"
StringBuilder ids = new StringBuilder();
ids.append("(");
for(int i = 0; i < catid.length; i++) {
ids.append(String.valueOf(catid[i]);
if (i < catid.length - 1) {
ids.append(",");
}
}
ids.append(")");
// Use the string with the ids in the query
String finalQuery = QUERY.replaceAll("%ids", ids.toString());
// Execute the query
return myDataBase.rawQuery(finalQuery);
}
Change your query
myDataBase.rawQuery("SELECT AuthorName FROM AUTHOR_NAME WHERE AuthorID = ?",catid);
as below
cursor = myDataBase.query("AUTHOR_NAME",
new String[] {"AuthorName"}, "AuthorID IN(?)", catid, null, null, null);
Try the above Solution hope it works for you.

rawQuery(query, selectionArgs)

I want to use select query for retrieving data from table. I have found, rawQuery(query, selectionArgs) method of SQLiteDatabase class to retrieve data. But I don't know how the query and selectionArgs should be passed to rawQuery method?
rawQuery("SELECT id, name FROM people WHERE name = ? AND id = ?", new String[] {"David", "2"});
You pass a string array with an equal number of elements as you have "?"
Maybe this can help you
Cursor c = db.rawQuery("query",null);
int id[] = new int[c.getCount()];
int i = 0;
if (c.getCount() > 0)
{
c.moveToFirst();
do {
id[i] = c.getInt(c.getColumnIndex("field_name"));
i++;
} while (c.moveToNext());
c.close();
}
One example of rawQuery - db.rawQuery("select * from table where column = ?",new String[]{"data"});
if your SQL query is this
SELECT id,name,roll FROM student WHERE name='Amit' AND roll='7'
then rawQuery will be
String query="SELECT id, name, roll FROM student WHERE name = ? AND roll = ?";
String[] selectionArgs = {"Amit","7"}
db.rawQuery(query, selectionArgs);
see below code it may help you.
String q = "SELECT * FROM customer";
Cursor mCursor = mDb.rawQuery(q, null);
or
String q = "SELECT * FROM customer WHERE _id = " + customerDbId ;
Cursor mCursor = mDb.rawQuery(q, null);
For completeness and correct resource management:
ICursor cursor = null;
try
{
cursor = db.RawQuery("SELECT * FROM " + RECORDS_TABLE + " WHERE " + RECORD_ID + "=?", new String[] { id + "" });
if (cursor.Count > 0)
{
cursor.MoveToFirst();
}
return GetRecordFromCursor(cursor); // Copy cursor props to custom obj
}
finally // IMPORTANT !!! Ensure cursor is not left hanging around ...
{
if(cursor != null)
cursor.Close();
}
String mQuery = "SELECT Name,Family From tblName";
Cursor mCur = db.rawQuery(mQuery, new String[]{});
mCur.moveToFirst();
while ( !mCur.isAfterLast()) {
String name= mCur.getString(mCur.getColumnIndex("Name"));
String family= mCur.getString(mCur.getColumnIndex("Family"));
mCur.moveToNext();
}
Name and family are your result

cursor index out of bounds "index 0 requested: with size 0"

I am getting cursor index out of bounds "index 0 requested: with size 0" error when I search my database for something. The item I am searching for in my database does not exist currently and i am aware of that but how do i handle a query where the item does not exist.
i send in a phone number
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.getIdFromPhone(number);
String test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
curs.close();
db.close();
return test;
}
query
public Cursor getIdFromPhone(String where){
Cursor cur = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + where + "'",null,null,null,null);
if(cur != null)
cur.moveToFirst();
return cur;
}
test search
from = messages.getDisplayOriginatingAddress();
String dbNumber = searchNumber(arg0,from);
if(dbNumber.equals(from)){
//do stuff
}else{
//do other stuff
}
if number is not found it should do the else statement but it does not get that far
Cursor.moveToFirst() returns false if the Cursor is empty. The returned Cursor from the query() call will never be null but it might be empty. You are never checking if the cursor is empty.
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + number + "'",null,null,null,null);
String test = null;
if(curs.moveToFirst()) { //edit
test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
}
curs.close();
db.close();
return test; // this will be null if the cursor is empty
}
And get rid of the getIdFromPhone() method.
While you retrive value you have to use cursor.moveToNext;
if (cursor.moveToFirst()){
do{
String data = cursor.getString(cursor.getColumnIndex("data"));
// do what ever you want here
}while(cursor.moveToNext());
}

Categories

Resources