How to put where condition and join in cursor Android - android

Hi i want to put a where condition and join tables in my query but i can't find any example
as for now i'm using this code, but i don't know where to put the join and where condition
public Cursor getUsers() {
Cursor localCursor =
this.myDataBase.query(TBL_INFO, new String[] {
KEY_ID,
KEY_NAME},
null,
null, null, null, null);
if (localCursor != null)
localCursor.moveToFirst();
return localCursor;
}
I'm wondering what's with the null value? is there any syntax that i can follow? thank you for the help!

db.query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy);
You need to put your where condition in the selection part
Eg:
String selection="columnA=123";
For join you could try something like, tableName can be given tableName="table1,table2";
then your selection can have the conditions.(Have not tried this just theoritical)

Related

Fetch Date from database that is shipped with android app

I am following this tutorial http://mobisys.in/blog/2012/01/tutorial-using-database-in-android-applications/ to have an external database with my android app.
I am not able to apply where clause while fetching the data from the database.
This is what I have done so far.
c=myDbHelper.query("level1", null, "_id=2", null, null,null, null);
if(c.moveToFirst())
{
do {
Toast.makeText(Level1.this,
"_id: " + c.getString(0) + "\n" +
"name: " + c.getString(1) + "\n"
,
Toast.LENGTH_LONG).show();
} while (c.moveToNext());
}
The databaseHelper class
public Cursor query(String table,String[] columns, String selection,String[] selectionArgs,String groupBy,String having,String orderBy){
return myDataBase.query("level1", null, "_id", null, null, null, null);
}
Can anyone help me with this?
You pass "_id=2" as selection when calling myDbHelper.query. But in your DB Helper query method, selection is never used (same goes for other parameters).
You probably want to change query to something like:
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy){
// double check parameters I did type that here (no IDE)
return myDataBase.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
}
See also, the documentation of SQLiteDatabase

Using String[] selectionArgs in SQLiteDatabase.query()

How do I use the String[] selectionArgs in SQLiteDatabase.query()? I wish I could just set it to null, as I have no use for it. I am just trying to load an entire unsorted table from a database into a Cursor. Any suggestions on how to achieve this?
selectionArgs replace any question marks in the selection string.
for example:
String[] args = { "first string", "second#string.com" };
Cursor cursor = db.query("TABLE_NAME", null, "name=? AND email=?", args, null);
as for your question - you can use null
Yes, you may set all parameters to null except the table name.
for example:
Cursor cursor = db.query("TABLE_NAME", null, null, null, null, null, null);

Query only the first data from a table

I'm trying to query only the first data from the table.
Cursor img_cursor = db.query(
IMAGE_URL_TABLE_NAME,
new String[]{"small_img_url" , "large_img_url"},
null",
null, null, null, null);
Could somebody tell me how to implement a query where only the first data is retrieved from a table?
Solution
I think I solved the answer:
Cursor img_cursor = db.query(
IMAGE_URL_TABLE_NAME,
new String[]{"small_img_url" , "large_img_url"},
null",
null, null, null, null , "1");
I used limit 1 first, but the application crashed. Only if I pass the number as a String will it work. The query has 8 parameters while we're using the limit parameter.
limit 1
From Documentation:
public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
so, put your last argument to be "limit 1".
Cursor img_cursor = db.query(
IMAGE_URL_TABLE_NAME,
new String[]{"small_img_url" , "large_img_url"},
null,
null, null, null, "limit 1");

how to add WHERE clause to Query on android

I would like to limit the results to those whose KEY_HOMEID is equal to journalId.
I've been on this for a couple days any help would be appreciated.
public Cursor fetchAllNotes(String journalId)
{
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_HEIGHT,
KEY_BODY, KEY_HOMEID},"FROM DATABASE_TABLE WHERE KEY_HOMEID = journalId",null, null, null, null,null);
}
Have a look at http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#query
Your query should look a little like this:
mDb.query(DATABASE_TABLE, // Table name
columnNames, // String[] containing your column names
KEY_HOMEID+" = "+jounalId, // your where statement, you do not include the WHERE or the FROM DATABASE_TABLE parts of the query,
null,
null,
null,
null
);
If you feel more comfortable writing sql queries you can also use:
mDb.rawQuery("SQL STATEMENT", null);
It makes your code more clear if you'll use it where arguments (in query parameters)
Example:
String [] settingsProjection = {
DBContract.Settings._ID,
DBContract.Settings.COLUMN_NAME_USER_ID,
DBContract.Settings.COLUMN_NAME_AUTO_LOGIN
};
String whereClause = DBContract.Settings.COLUMN_NAME_USER_ID+"=?";
String [] whereArgs = {userId.toString()};
Cursor c = db.query(
DBContract.Settings.TABLE_NAME,
settingsProjection,
whereClause,
whereArgs,
null,
null,
null
);
I was looking for an answer to my problem here as well.
It turned out that I tried to have a String instead of an Integer. My solution was to do it like that: 'String' instead of Integer.
Here is the code that worked for me in the end:
return db.query(TABLE_NAME_REMINDER, PROJECTION, REMINDER_REMINDER_TYPE+" = '"+rem_type+"'", null, null, null, null);

How do I get the _count in my content provider?

What should I do to get my content provider to return the _count column with the count of records? The documentation says it is automatic, but maybe it's only taking about some built-in content provider. Running a query to the database seems not to return it.
If you are using contentProvider then you have to do it like count(*) AS count.
If you use cursor.getCount(), that would not be as efficient as the above approach. With cursor.getCount() you are fetching all the records just to get counts. The entire code should look like following -
Cursor countCursor = getContentResolver().query(CONTENT_URI,
new String[] {"count(*) AS count"},
null,
null,
null);
countCursor.moveToFirst();
int count = countCursor.getInt(0);
The reason why this works is because android needs a column name to be defined.
If you are using ContentProvider.query() a Cursor is returned. Call Cursor.getCount() to get a count of records in the returned cursor.
I had a similiar problem and found this worked for me. In the example below I wanted to get the count of images from the MediaStore provider.
final String[] imageCountProjection = new String[] {
"count(" + MediaStore.Images.ImageColumns._ID + ")",
};
Cursor countCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
imageCountProjection,
null,
null,
null);
countCursor.moveToFirst();
int existingImageCount = countCursor.getInt(0);
With cursor.getCount() you can not assure that it returns the real number of items returned. There are much better ways:
1- If you are using Content Providers, you can do a query and use the Column (_COUNT) included in BaseColumns for your projection
#Override
public Cursor query(SQLiteDatabase db, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
...
projection = new String[] {
ContentContract.NotificationCursor.NotificationColumns._COUNT,
};
...
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, groupBy, having, sortOrder);
return cursor;
}
2- To do a rawQuery using SELECT COUNT(*) as #saurabh says in his response.

Categories

Resources