fetching value from database and displaying it in a TextView in android - 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();
}

Related

Android select statement returns no results via rawquery or query while using query directly works

I've spent the whole day so far trying to get a select query to execute viarawquery or query, but I've had no luck so far.
The select statement I want to run is as the following:
SELECT * FROM h_word WHERE category='GRE' AND DONE=0 ORDER BY RANDOM() LIMIT 1
category is a TEXT type column and DONE is an INTEGER type with the default value of 0.
While the query works fine when executed directly in SQLite, in android,it doesn't return any results.
I've tried the below with no luck (the method is located in a class extended from SQLiteAssetHelper which itself is a helper class originally extended from SQLiteOpenHelper originaly taken from here: https://github.com/jgilfelt/android-sqlite-asset-helper:
public Cursor getRandomWord() {
Cursor c;
SQLiteDatabase db = getWritableDatabase();
c=db.rawQuery(query, null);
String query = "SELECT * FROM h_word WHERE category='GRE' AND DONE='0'
ORDER BY RANDOM() LIMIT 1 ";
c=db.rawQuery(query, new String[] {});
c.moveToFirst();
db.close();
return c;
}
I also tested with GRE instead of 'GRE' and 0 instead of '0' but it made no difference.
did the following as well:
public Cursor getRandomWord() {
Cursor c;
SQLiteDatabase db = getReadableDatabase();
c=db.query(true, "h_word", new String[] {
"_id",
"word",
"english_meaning"
},
"category" + "=?" + " AND " +
"DONE" + "=?",
new String[]{"GRE" ,"0"},
null, null, "RANDOM() LIMIT 1" , null);
c.moveToFirst();
db.close();
return c;
}
but the cursor remains empty.
Any ideas what I might be doing wrong here?
Any help would be much appreciated.
PS: when running a simple select statement without a where clause it, works fine.
After another few hours of struggling, I figured it's a bug in android's SQLiteDatabase class.
I managed to solve the problem by changing the name of the "category" column to something else.
Seems like "category" is a key word in the android SQLiteDatabase code, and makes a query return nothing when written in where clauses on the android side.
Someone else also had this problem here:
Android rawquery with dynamic Where clause

Update Query not working in Android Sqlite

My Java code Update Data base Table
String qq="UPDATE ChallanItems SET Recieve ="+str+" WHERE ItemNo = "+code;
Log.d("Qry", qq);
myDbHelper.updatequery(qq);
updatequery method
public void updatequery(String qry)
{
Cursor c = myDataBase.rawQuery(qry, null);
Log.d("Up", ""+c.getCount());
}
When i updated Data base the count return 0 and table not updated
I am using this Also but not work
String qq="UPDATE ChallanItems SET Recieve ="+str+" WHERE ItemNo = "+"'"+code+"'";
Please Help Me how i can fix this problem
Thanks In Advance
Use execSQL() for such SQL and not rawQuery().
rawQuery() just compiles the SQL but does not run it. You'd need to call one of the move...() methods on the returned Cursor to execute a step of the compiled SQL program.
execSQL() both compiles and runs the SQL program.
There's also possibly a syntax problem with your literals - use parameters i.e. ? placeholders in SQL and String[] bind arguments to be safe.
To update sqlite query change
Cursor c = myDataBase.rawQuery(qry, null);
to this
myDataBase.execSQL(qry);
try to use this:
ContentValues values = new ContentValues();
values.put("Recieve", str);
db.update("ChallanItems", values2, "ItemNo = ?", new String[] { code });

Quering SqlLite database where clause Android

Hi I am developing an android app.I am trying to query from the database. I need to fetch everything from the table TASK where dbDate = AlarmDate and dbdTime = AlarmTime.
c = db.rawQuery("SELECT * FROM TASK WHERE dbDate = '"+AlarmDate+"' AND dbTime= '"+Alarmtime+"'", null);
The problem is ,the cursor c is null.
I am not sure where I am going wrong in the query. Please Help.
Thanks!
Android has binding method to avoid sql inject. You can use the second parameter to provide the variables of SQL.
Cursor cur = db.rawQuery("SELECT * FROM TASK WHERE dbDate = ? AND dbTime = ? ", new String[]{AlarmDate, AlarmDate});
Going by your comment 'I have used db = openOrCreateDatabase("Globus", 0, null); where Globus is the db name', you are not using SQLite properly with android.
What you should be doing is creating class which extends SQLiteOpenHelper, then make sure you override the onCreate and onUpgrade methods, these are the methods where you create tables and make changes, it has been said a hundred times on here so I will provide a link to a tutorial: http://www.codeproject.com/Articles/119293/Using-SQLite-Database-with-Android
When you do database operations, on the class call getWritableDatabase (http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#getWritableDatabase())
I say call getWritableDatabase because that way you don't need to worry if you can write to it, a writable database is also readable. Just FYI. Ask away for more details.
This should be the process of reading (writing is the same, just use what method you want instead of query):
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();//this should lock the tables you are reading
Cursor c = db.rawQuery("select 1 where 1=?", new String[]{"1"});
if(c.moveToFirst()){
do{
//Do what you want with the row
}while(c.moveToNext());
}
c.close();
db.setTransactionSuccessful();
db.endTransaction();
db.close();
Here is the source code of a database helper I wrote, maybe it will help, read through it, understand how it works. https://bitbucket.org/FabianCCook/dbhelper/src/af7a8eba8d1a3f139e4170bbef9f1a2d3fdf1b47/src/nz/smartlemon/DatabaseHelper/ApplicationDataDbHelper.java?at=master
And if you want to know the reason the open methods exist read through this code
(This class was made from the help of someone elses code)
https://bitbucket.org/FabianCCook/dbhelper/src/af7a8eba8d1a3f139e4170bbef9f1a2d3fdf1b47/src/nz/smartlemon/DatabaseHelper/SDCardSQLiteOpenHelper.java?at=master
SQLiteDatabase db = getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM TASK WHERE dbDate = '"+AlarmDate+"' AND dbTime = '"+AlarmTime+"'",new String [] {});
Make sure you have gotten a readable database for 'db' or it will return null everytime.
Also change the end of your raw query to new String [] {}
Hope this helps, this is what I use in my applications.

Get a cursor with a raw sql with ormlite

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

Does cursor copy the result set?

For example, if i use following code to query some data from database.
Uri uri = Uri.parse("content://com.android.contacts/contacts?address_book_index_extras=true");
String selection = "LEFT OUTER JOIN (select raw_contact_id, data1 from data where mimetype_id = 5) AS phone_data ON(_id = phone_data.raw_contact_id)";
Cursor c = getContentResolver().query(Contacts.CONTENT_URI, null, selection, null, null);
What i want to ask is after the query method, does database copy its result set to cursor or just make cursor something like a pointer and point to the first line of result set and query for more data when we call `moveToNext'
thanks
Yes. It is a readonly copy of the DB.
From Android Developers:
This interface provides random read-write access to the result set returned by a database query. Cursor implementations are not required to be synchronized so code using a Cursor from multiple threads should perform its own synchronization when using the Cursor.

Categories

Resources