Android Sqlite concat two columns - android

I have made the concatenation so far, but in the results, it displays
UncleSam.
What I want to do is to put a space between the two columns so the result would be
Uncle Sam.
This is the code I'm working on:
public Cursor getAllPatients()
{
Cursor localCursor = //
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_FNAME + "||" + KEY_LNAME, KEY_DIAGNOSIS, KEY_LASTFFUP }, null, null, null, null, null);
if (localCursor != null)
localCursor.moveToFirst();
return localCursor;
}
from DBHelper.java
and
Cursor cursor = dbHelper.getAllPatients();
String[] data = new String[]{
DBHelper.KEY_FNAME + "||" + DBHelper.KEY_LNAME, DBHelper.KEY_DIAGNOSIS, DBHelper.KEY_LASTFFUP};
//
int[] to = new int[] {R.id.fullname, R.id.diagnosis, R.id.lastffup};
dataAdapter = new SimpleCursorAdapter(this, R.layout.custom_row, cursor, data, to, 0);
from my MainActivity.
Any help will do. Thanks.

You can concat like this:
Cursor localCursor = this.myDataBase.rawQuery("SELECT (KEY_FNAME || ' ' || KEY_LNAME) AS fullname, KEY_ID, KEY_DIAGNOSIS, KEY_LASTFFUP FROM DB_TABLE");
Your concated full name will be in the cursor column 'fullname'.
In main activity:
String[] data = new String[]{ "fullname", DBHelper.KEY_DIAGNOSIS, DBHelper.KEY_LASTFFUP};
(You should probably assign a DBHelper constant for "fullname").

Android Sqlite concat two columns
After a little conversation with author of this thread i suggest you to don't concat columns (you really don't need it) and concat Strings retrieved from Cursor. Your statement will be more human-readable and solution cleaner.
Explanation:
Generally is very useful and efficient approach to represent your table on application layer with objects which will represent tables. For example if you had table User, so create new class User and columns in table will be equal to properties in this class. This way is i guess pretty elegant (if someone else will see your code, he won't be confused and scared)
Finally you can simply concat fname and lname when you'll add them to ListAdapter
So i prefer this way:
List<User> users = new ArrayList<User>();
User u = null;
String query = "select * from Table";
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
do {
u = new User();
u.setFirstName(c.getString(c.getColumnIndex("fname")));
u.setLastName(c.getString(c.getColumnIndex("lname")));
...
users.add(u);
} while (c.moveToNext());
}
And then somewhere in ListAdapter you can do:
textView.setText(u.getFirstname() + " " + u.getLastName());
Hope it helps.

I finally got it working.
public Cursor getAllPatients()
{
Cursor localCursor = //
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_FNAME + "|| ' ' ||" + KEY_LNAME, KEY_DIAGNOSIS, KEY_LASTFFUP }, null, null, null, null, null);
if (localCursor != null)
localCursor.moveToFirst();
return localCursor;
}
and
Cursor cursor = dbHelper.getAllPatients();
String[] data = new String[]{
DBHelper.KEY_FNAME + "|| ' ' ||" + DBHelper.KEY_LNAME, DBHelper.KEY_DIAGNOSIS, DBHelper.KEY_LASTFFUP};
//
int[] to = new int[] {R.id.fullname, R.id.diagnosis, R.id.lastffup};
dataAdapter = new SimpleCursorAdapter(this, R.layout.custom_row, cursor, data, to, 0);

Related

Multiple SelectionArgs for query

I have a String[] that looks like {1, 2, 3 ..} (a string of IDs).
I want to build a query in Android to obtain all the entries that match the IDs.
Here my code:
Cursor idFoodCursor = getContext().getContentResolver().query(
uriFood,
null,
CookingContract.FoodEntry.COLUMN_NAME + " LIKE ?",
new String[]{selectionArgs},
null
);
if (idFoodCursor.moveToFirst()) {
List<String> ids = new ArrayList<String>();
while (!idFoodCursor.isAfterLast()) {
ids.add(idFoodCursor.getString(idFoodCursor.getColumnIndex(CookingContract.FoodEntry._ID)));
idFoodCursor.moveToNext();
}
idFoodCursor.close();
//Convert the ArrayList in String[]
String[] idSelectionArg = new String[ids.size()];
ids.toArray(idSelectionArg);
return new CursorLoader(
getContext(),
uriFood,
FOOD_COLUMNS,
CookingContract.FoodEntry._ID + " = ?",
idSelectionArg,
sortOrder
);
}
The last query doesn't work because I should add as many "?" as my IDs in the array:
Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 3 because the index is out of range. The statement has 1 parameters.
How can I fix the problem, taking into account what I want to get? (the correspondence of all the ids in the table)
All the over-mentioned code can be replaced with:
return new CursorLoader(
getContext(),
uriFood,
FOOD_COLUMNS,
"_id IN (SELECT _id FROM food WHERE name LIKE ?)",
new String[] {selectionArgs},
sortOrder
);
That does the job I wanted.
public class Constants {
public static final String JOB_STATUS_CANCELLED = "Cancelled";
public static final String JOB_STATUS_COMPLETE = "Complete";
}
selection = JobListContract.JobEntry.COLUMN_NAME_JOB_STATUS + " NOT IN ( ? , ? ) ";
// The spaces matter!!!!
selectionArgs = new String[]{ Constants.JOB_STATUS_COMPLETE, Constants.JOB_STATUS_CANCELLED };
c = db != null ? db.query(
JobListContract.JobEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
JobListContract.JobEntry.COLUMN_NAME_ENTRY_ID + " desc" // The sort order
) : null;

Android database query with multiple selection

I know how to query for a single selection with the following:
Cursor cursor = database.query(true, TABLE, COLUMNS, "name = ?", new String[]{"Bob"},null,null,null,null);
But suppose I want to make a function as follows:
public Cursor queryNames(String[] names)
where the function returns a cursor where the name = names[0] OR name = names[1] ... etc. So for example, if I called the function queryNames(new String[] {"Alice","Bob","Charlie"}), the function should return a cursor where the name is any of the three (Alice, Bob, or Charlie). How would I write this? Thanks!
Your method might want to look like this:
public Cursor queryNames(String[] names) {
SQLiteDatabase mDb = this.getReadableDatabase();
String whereStatement = "";
for(int i = 0; i < names.length; i++) {
if (i != (names.length - 1))
whereStatement = whereStatement + "name = ? OR "
else
whereStatement = whereStatement + "name = ?"
Cursor cursor = mDb.query(true, TABLE, COLUMNS, whereStatement, names, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
mDb.close();
return cursor;
}
Hope this helps!
try:
Cursor cursor = db.query(true, TABLE, COLUMNS, "name IN (?)", new String[]{" 'moe', 'larry', 'curly'"}, null, null, null, null);
It would probably be best to build the String[] separately than to guess at the number of names.
Enclose the whole thing in double quotes, the individual names in single quotes, comma-separated.

SELECT and WHERE in android (SQlite)

I want to search if there are exact course_no, semester ,and year value in the table.
I problem is that I can only filter course_no.
Cursor cursor = database.query(DatabaseHelper.TABLE_COURSE, CourseItemDataSource.allColumns, DatabaseHelper.KEY_COURSE_COURSE_NO + "=?", new String[] { notiItem.getCourseNo() }, null, null, null);
When I tried to add other filter it doesn't seems to work
[Edited] Sorry for being not informative, the problem is that when I pass the below code filter don't work. Note that notiItem.getCourseNo() and notiItem.getYear() is a String.
The following column in the table is a TEXT.
Cursor cursor = database.query(DatabaseHelper.TABLE_COURSE, CourseItemDataSource.allColumns, DatabaseHelper.KEY_COURSE_COURSE_NO + "=? AND "+DatabaseHelper.KEY_COURSE_YEAR+"=?", new String[] { notiItem.getCourseNo() ,notiItem.getYear()}, null, null, null);
This is code the method I tried
public CourseItem searchToCourse(NotificationItem notiItem){
/**Check if exact course_no, semester, year of notiItem exist in Course Table
* return null if not found
*
*/
String [] columns = new String[]{ "*"};
Cursor cursor = database.query(DatabaseHelper.TABLE_COURSE, CourseItemDataSource.allColumns, DatabaseHelper.KEY_COURSE_COURSE_NO + "=?", new String[] { notiItem.getCourseNo() }, null, null, null);
Log.i("DATA SOURCE", "AFTER QUERY ");
if (cursor != null) {
cursor.moveToFirst();
}
CourseItem courseItem = CourseItemDataSource.cursorToCourseItem(cursor);
return courseItem;
}
How can I search multiple column at a time??

Limit number of rows in Cursor query

I need to get contacts from an android phone. so I am using this code:
Cursor phones = getActivity().getContentResolver().query(Phone.CONTENT_URI,
new String[] { Phone.NUMBER, Phone.TYPE },
" DISPLAY_NAME = ?", new String[] { displayName }, null);
while (phones.moveToNext()) {
//do work here
}
I want to tell the cursor to limit the response to 50 with something like "LIMIT 50". Where do I pass that information to the cursor? Please copy and paste my code and make edit there.
There is no limit in Android API, but you can apply it in your code like this:
Cursor phones = getActivity().getContentResolver().query(Phone.CONTENT_URI,
new String[] { Phone.NUMBER, Phone.TYPE },
" DISPLAY_NAME = ?", new String[] { displayName }, null);
for (int i = 0; i < 50 && phones.moveToNext(); ++i) {
// do work here
}
phones.close();
Order by id DESC Limit 1:
db.query("table", null, "column=?", new String[]{"value"}, null, null, "id DESC", "50");
If you have the DB and the table name you can use that, but Content providers don't have a limit argument in their query statement.
mDb = new DBHelper (this);
Cursor c = mDB.getReadableDatase().query(
<Phone_Table_Name>,
new String[] { Phone.NUMBER, Phone.TYPE },
"DISPLAY_NAME = ?",
new String[] { displayName }, null),
null,
null,
null,
"50");

About Android ContentResolver Query Group By

I test sql and it works fine in Sqlite Spy:
select ifnull(_name, _number) as identifer, count(_id) as amount from call group by identifer
And I wanna use it in ContentConsolver but it can't work with "group by":
String[] projections = new String[] { "ifnull(name, number) as identifer", "count(_id) as amount" };
String group = "identifer";
//String selection = ") GROUP BY (" + group;
Cursor cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, projections, null, null, null /*!group*/ );
What should I do?
#njzk2 did the trick by using HashSet: Group By in ContentResolver in Ice Cream Sandwich, But it didn't work with count() if you want sum.
I think the best solution is to make a copy of CallLog Database, then you can use rawQuery() or whatever you want (maybe it is a waste of performance).
private void refreshDbCache()
{
CallDbCache dbCache = new CallDbCache(this);
dbCache.clear(CallDbCache.TB_CALL);
String[] columns = new String[] { CallLog.Calls._ID, CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME };
Cursor cursor = getContentResolver().query(URI_CALL, columns, null, null, null);
while (cursor != null && cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(CallLog.Calls._ID));
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
dbCache.insert(CallDbCache.TB_CALL, new LogData(id, number, name, "", "", "", ""));
}
cursor.close();
dbCache.close();
}

Categories

Resources