Get a cursor with a raw sql with ormlite - android

I'd like to use a SimpleCursorAdapter with a Spinner.
I found how to return a Cursor.
QueryBuilder<ChoixPointVerification, Integer> qb = choixPointVerificationDao.queryBuilder();
qb.where().eq(FIELD, id);
PreparedQuery<ChoixPointVerification> preparedQuery = qb.prepare();
AndroidCompiledStatement compiledStatement =
(AndroidCompiledStatement)preparedQuery.compile(db, StatementType.SELECT);
Cursor cursor = compiledStatement.getCursor();
return cursor;
But the Spinner require a _id field and I'll only have an object with an id field. I prefer to avoid the rename of the field.
How can I resolve that case ? I really need to associate an id to all spinner field.
I imagined that I can maybe issue a cursor from a rawsql but I din't find how with ormlite. It seems to be possible if I can create a PreparedQuery with a raw sql.
I also read that if I have an AndroidDatabase object I can issue a Cursor object but how can we create an AndroidDatabase with ormlite ?
I'm really open with all the solution
Regards

You can get the underlying Cursor object from ORMLite by using QueryBuilder without having to resort to a raw query. Take a look at this answer:
Android Cursor with ORMLite to use in CursorAdapter
You can do something like the following code:
// build your query
QueryBuilder<Foo, String> qb = fooDao.queryBuilder();
qb.where()...;
// when you are done, prepare your query and build an iterator
CloseableIterator<Foo> iterator = dao.iterator(qb.prepare());
try {
// get the raw results which can be cast under Android
AndroidDatabaseResults results =
(AndroidDatabaseResults)iterator.getRawResults();
Cursor cursor = results.getRawCursor();
...
} finally {
iterator.closeQuietly();
}

Well I just found a solution which seems to be efficient, simple, and compliant with ormlite.
I just have to get an AndroidDatabase with getHelper().getReadableDatabase().
and then use
Cursor cursor = db.query("choixpointverification",
new String[] { "id", "id as _id", "nom" },
"masque = 0 and idPointVerification = " + idPointVerification.toString(),
null, null, null, "tri");

Related

Why Sqlite return only last row not all rows data?

I don't know what's wrong with my code I follow the rule but I get wrong result. I want to search db and find all rows data but I only get last row from sqlite. my code to search database is bellow:
public ArrayList<ArrayList<ContractSaveDataFromDB>> ActiveContractData(String phone, String numberId)
{
ArrayList<ContractSaveDataFromDB> UserData = new ArrayList<ContractSaveDataFromDB>();
ArrayList<ArrayList<ContractSaveDataFromDB>> SendUserData =
new ArrayList<ArrayList<ContractSaveDataFromDB>>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
res2.moveToFirst();
do{
UserData.clear();
int index;
ContractSaveDataFromDB contractSaveDataFromDB=new ContractSaveDataFromDB();
index = res2.getColumnIndex("buyAmount");
String buyAmount = res2.getString(index);
contractSaveDataFromDB.setBuyAmount(buyAmount);
UserData.add(contractSaveDataFromDB);
SendUserData.add(UserData);
} while(res2.moveToNext());
res2.close();
db.close();
return SendUserData;
I don't know what's wrong. I appreciate if you help me to solve my problem.
you already added where clause so maybe it is filtering your results try to remove it by change this
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
to this
Cursor res2=db.query("usersAccount",null,null,null,null,null,orderBy);
I believe that your issues is that you are trying to use an ArrayList of ArrayList of ContractSaveDataFromDB objects.
I believe that an ArrayList of ContractSaveDataFromDB objects would suffice.
It would also help you if you learnt to do a bit of basic debugging, as an issue could be that you are not extracting multiple rows.
The following is an alternative method that :-
uses the ArrayList of ContractSaveDataFromDB objects,
introduces some debugging by the way of writing some potentially useful information to the log
and is more sound, as it will not crash if no rows are extracted
i.e. if you use moveToFirst and don't check the result (false means the move could not be accomplished) then you would get an error because you are trying to read row -1 (before the first row) as no rows exists in the cursor.
:-
public ArrayList<ContractSaveDataFromDB> ActiveContractData(String phone, String numberId) {
ArrayList<ContractSaveDataFromDB> SendUserData = new ArrayList<ContractSaveDataFromDB>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2 = db.query("usersAccount", null, whereClause, whereArgs, null, null, orderBy);
Log.d("RES2 COUNT", "Number of rows in Res2 Cursor is " + String.valueOf(res2.getCount()));
while (res2.moveToNext()) {
ContractSaveDataFromDB current_user_data = new ContractSaveDataFromDB();
current_user_data.setBuyAmount(res2.getString(res2.getColumnIndex("buyAmount")));
Log.d("NEWROW", "Adding data from row " + String.valueOf(res2.getPosition()));
SendUserData.add(current_user_data);
}
res2.close();
db.close();
Log.d("EXTRACTED", "The number of rows from which data was extracted was " + String.valueOf(SendUserData.size()));
return SendUserData;
}
If after running you check the log you should see :-
A line detailing how many rows were extracted from the table
A line for each row (if any were extracted) saying Adding data from row ? (where ? will be the row 0 being the first)
A line saying The number of rows from which data was extracted was ? (? will be the number of elements in the array to be returned)

Android Sql. Query single coloumn, multiple values

I have database with three columns.
I would like to query the database, based on one column which can have multiple values.
For single parameter we can the normal query method where cardName is String[]
Cursor cursor = database.query(Database.TABLE_COUPON_CARD, allColumns,Database.COLUMN_CARD_NAME + " = ?", cardName, null, null,null);
but if there are more than one value, I get a Android SQLite cannot bind argument exception
For multiple values of the same column we can use IN statement but, here how do I write the QUERY or how should i form the rawQuery
String whereClause = Database.COLUMN_CARD_NAME+ " IN(?)";
Cursor cursor = database.query(Database.TABLE_COUPON_CARD, allColumns,whereClause,new String[][]{cardName}, null, null,null);
Android QUERY doesnot take array of array.
What should the correct query be?
TEMPORARY SOLUTION
Currently I have created a method which dynamically creates the clause.
private static StringBuilder buildInClause(String[] myStringArray){
StringBuilder fullString=new StringBuilder();
fullString.append("(");
for(int i=0;i<myStringArray.length;i++){
fullString.append(" '"+myStringArray[i]+"' ");
if(i!=myStringArray.length-1){
fullString.append(",");
}
}
fullString.append(")");
return fullString;
}
If anyone has any other solution please do share.
For two values: IN(?,?). For three values: IN(?,?,?). Get the idea? Each ? corresponds to a single literal in the selection args array.

android cannt use data function in query

I cant get any result if i put "date('now', 'localtime')" in the query.
My original code is:
Cursor record = db.query(RECORD_TABLE, null, date(UTC_DATETIME,'localtime') = ? ",
new String[]{"date('now', 'localtime')"},null,null,null);
It doesn't return any result.
But I can get result if I use:
Cursor record = db.query(RECORD_TABLE,null, date(UTC_DATETIME,'localtime') = ? ",
new String[]{"2014-05-13"},null,null,null);
Is there a way that I can use "date('now', 'localtime')" in my query?
The whole point of parameters is to prevent their values from being interpreted as SQL expressions.
To call an SQL function, you have to put it into the SQL string:
Cursor record = db.query(RECORD_TABLE, null,
"date(UTC_DATETIME,'localtime') = date('now', 'localtime')",
null,null,null,null);
Please note that the localtime conversion affects both values in the same way, so you can omit it:
Cursor record = db.query(RECORD_TABLE, null,
"date(UTC_DATETIME) = date('now')",
null,null,null,null);
or even omit the first date call if the UTC_DATETIME column alread is in the correct yyyy-MM-dd format:
Cursor record = db.query(RECORD_TABLE, null,
"UTC_DATETIME = date('now')",
null,null,null,null);

Removing rows from an Android SQLite Cursor

I query and get a result set back, but I need to do some calculations that are impossible in the SQLite WHERE clause in order to determine what shows up in the ListView. How can I remove certain rows from the cursor? I know it is the same question as this Filter rows from Cursor so they don't show up in ListView but that answer does not help. Can an example be provided if there isn't a simpler way to do this?
It might work to simply retain all the rows in the Cursor, but then use a custom adapter to hide the unwanted rows at display time. For example, if you extend CursorAdapter, then you might have something like this in your bindView implementation:
View v = view.findViewById(R.id.my_list_entry);
boolean keepThisRow = .......; // do my calculations
v.setVisibility(keepThisRow ? View.VISIBLE : View.GONE);
There should be a better way to do this, but what I ended up doing is storing the ID of each row I wanted in a string ArrayList, and then requerying where _id IN arraListOfIds.toString(), replacing the square brackets with parentheses to fit SQL syntax.
// Get all of the rows from the database
mTasksCursor = mDbHelper.fetchAllTasks();
ArrayList<String> activeTaskIDs = new ArrayList<String>();
// calculate which ones belong
// .....
if (!hasCompleted)
activeTaskIDs.add(mTasksCursor.getString(TaskerDBadapter.INDEX_ID));
// requery on my list of IDs
mTasksCursor = mDbHelper.fetchActiveTasks(activeTaskIDs);
public Cursor fetchActiveTasks(ArrayList<String> activeTaskIDs)
{
String inClause = activeTaskIDs.toString();
inClause = inClause.replace('[', '(');
inClause = inClause.replace(']', ')');
Cursor mCursor = mDb.query(true, DATABASE_TABLE, columnStringArray(),
KEY_ROWID + " IN " + inClause,
null, null, null, null, null);
if (mCursor != null) { mCursor.moveToFirst(); }
return mCursor;
}
ContentResolver cr = getContentResolver();
Cursor groupCur = cr.query(
Groups.CONTENT_URI, // what table/content
new String [] {Groups._ID, Groups.NAME}, // what columns
"Groups.NAME NOT LIKE + 'System Group:%'", // where clause(s)
null, // ???
Groups.NAME + " ASC" // sort order
);
The "What Columns" piece above is where you can tell the cursor which rows to return. Using "null" returns them all.
I need to do some calculations that
are impossible in the SQLite WHERE
clause
I find this very hard to believe; my experience has been that SQL will let you query for just about anything you'd ever need (with the exception of heirarchical or recursive queries in SQLite's case). If there's some function you need that isn't supported, you can add it easily with sqlite_create_function() and use it in your app. Or perhaps a creative use of the SELECT clause can do what you are looking for.
Can you explain what these impossible calculations are?
EDIT: Nevermind, checking out this webpage reveals that the sqlite_create_function() adapter is all closed up by the Android SQLite wrapper. That's annoying.

fetching value from database and displaying it in a TextView in android

How can fetch values form database and display it in a textview in android?
Good to see you've given it some thought and tried on your own.
http://developer.android.com/guide/topics/data/data-storage.html#db has some good info on using SQLite on Android
It's also used in the Notepad tutorial: http://developer.android.com/resources/tutorials/notepad/notepad-ex1.html
I personally learned by using part of the guide from the "Hello, Android" book. The source code is available at: http://www.pragprog.com/titles/eband3/source_code - the SQL example is the one called 'Eventsv1'
You need SQLiteOpenHelper class to fetch readable instance of SQLiteDatabase in android. Then using query method you can get Cursor object of you query.
Can you explain more about what you want to do?
Try this,
Cursor c = db.query(TABLE_NAME, columns, null, null, null, null, null);
Then write
if(c!=null) {
c.moveToFirst();
while(!c.isAfterLast()) {
String col1Value = c.getString(1);//here you get col1 value
String col2Value = c.getString(2);//here you get col2 value
c.moveToNext();
}
c.deactivate();
c.close();
}

Categories

Resources