SELECT and WHERE in android (SQlite) - android

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??

Related

How to get last record from table SQLite

I have problem with receiving last data from table in Android SQLite.
Adding values works great but I struggle with receiving last date from table, here is code:
int getKoniec() {
SQLiteDatabase db = this.getReadableDatabase();
String sortOrder = TABELA_koniec + " DESC LIMIT 1";
Cursor cursor = db.query(
TABELA,
new String[] { "koniec" },
null,
null,
null,
null,
sortOrder
);
if(cursor != null) {
cursor.moveToFirst();
}
int koniecINT = cursor.getInt(0);
Log.v("VALUE: ","" + koniecINT);
cursor.close();
return koniecINT;
}
While adding values 10,9,8,7.. output (return koniecINT) is always 10.
Can you help me to solve this problem? Thanks
Try this query
select * from table_name order by row_id desc limit 1
or
mCursor.moveToLast();

Changing order of listview results from SQlite

I have a listview in my application that displays records according to the primary key _ID field with the lowest _ID number first. How can I change that so it is the highest _ID number first in the listview? i.e reverse the order.
The db query currently generating the listview is below. Thanks!
public Cursor fetch() {
String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SLOC, DatabaseHelper.FLOC, DatabaseHelper.DSNM, DatabaseHelper.SDATE, DatabaseHelper.STIME };
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToLast();
}
return cursor;
}
use this query:
Cursor c = mDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
You can use rawQuery method to hit any custom query like this and add ORDER BY ASC or DESC as you wish.
public Cursor fetch() {
String queryString = "SELECT * FROM tablename ORDER BY _id DESC"
Cursor cursor = sqLiteDatabase.rawQuery(queryString);
if (cursor != null) {
cursor.moveToLast();
}
return cursor;
}

Sql search statement always returning empty even when there is data in database in android

I am using the following to fetch a string from my table. The cursor is always returning empty even when I have data in database. Is the query wrong?
public void find(String myNumber){
String[] thecolumns = new String[]{
ID,
FLAG};
cursor = sqlDb.query(MY_TABLE,
thecolumns, NUMBER + "='"
+ myNumber+ "'", null, null, null, null);
if (cursorToFetchAssets != null ) {
cursorToFetchAssets.moveToFirst();{
try{
//code to fetch
}catch{
//return when there are no rows found.
}
}
EDIT: NUMBER is of type string "...+ NUMBER + " TEXT,.. " and myNumber is also a string
FIXED: Issue was on the server side of my code. Not over here..
try this:
cursor = sqlDb.query(
MY_TABLE,
thecolumns,
NUMBER + "=?",
new String[]{String.valueOf(number)},
null, null, 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.

Android Sqlite concat two columns

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);

Categories

Resources