update rawQuery in to database is not working on android - android

In my project i'm updating the searchtag in the database by using this query
public void updatesearchtag(){
SQLiteDBHelper sqLiteDBHelper = new SQLiteDBHelper(context.getApplicationContext());
Cursor crs=sqLiteDBHelper.getWritableDatabase().rawQuery("update shoply_coupon set searchTag=(Select SearchTag from shoply_retailer_master where retailerId=shoply_coupon.retailerID)",null);
//Cursor crs=sqLiteDBHelper.getWritableDatabase().execSQL("update shoply_coupon set searchTag=(Select SearchTag from shoply_retailer_master where retailerId=shoply_coupon.retailerID)");
}
but the query is not working may i know what error i'm doing over here

Use execSQL() and not rawQuery() for SQL like this.
rawQuery() just compiles the SQL but doesn't run it. It is only run when the cursor is moved. execSQL() both compiles and runs the SQL.
Also, use getWritableDatabase() and not getReadableDatabase() for updates.

Share your code please which you are using for updating . Also about the SearchTag values.
I will suggest to make the Dbclass seprate in your code and use the functions like this. this is a easy way to do every thing such as update,delete,select etc
public boolean Update(String SearchTag , ContentValues values)
{
if (db.update(TABLE, values, "SearchTag = '"+YourValue+"'", null) > 0)
{
return true ;
}
return false ;
}

Use
sqLiteDBHelper.getWritableDatabase()
instead
sqLiteDBHelper.getReadableDatabase()
Since you are trying to write into a database which is in write prevention mode.

Related

What must I do to implement SQLite's rawQuery() method?

I'm trying to use the SQLite rawQuery method, based on the code here:
Android record exists() in database?
...but I get "The method rawQuery(String, String[]) is undefined for the type OdaaDBOpenHelper
Authorize_Activity_DynamicControls.java" with this code:
OdaaDBOH = new OdaaDBOpenHelper(this);
. . .
private boolean RecordExists(String _id) {
// This:
Cursor cursor = OdaaDBOH.rawQuery("select 1 from NAPOLEON_DYNAMITE_TABLE where _id=%s",
// or this:
//Cursor cursor = OdaaDOdaaDBOpenHelperBOH.rawQuery("select 1 from
NAPOLEON_DYNAMITE_TABLE where _id=%s",
new String[] { _id });
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
. . .
// from referenced unit:
public class OdaaDBOpenHelper extends SQLiteOpenHelper {
I tried it both using the instance name of my SQLiteOpenHelper-derived class, and using the class
name itself (commented out in the code above).
What must I do to implement rawQuery() or cause it to be recognized/acknowledged?
rawQuery() is a method on SQLiteDatabase, not SQLiteOpenHelper. Call getReadableDatabase() or getWritableDatabase() on your SQLiteOpenHelper to get a SQLiteDatabase.
From that question correct answer:
Consider that mDb is your SqlLiteDatabase class...
OdaaDBOH should be an instance of a SQLiteDatabase if you want to use rawQuery on it, most likely you are providing the implementation of a SQLiteOpenHelper there, which of course doesn't have a method rawQuery.

Ask, how to delete all data on sqlite

i want to make "clear-all" button which delete all data in my sqlite, my code is like this :
private void clearAll() {
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
Cursor notesCursor = mDbHelper.fetchAllNotes();
notesCursor.moveToFirst();
do{
for(int i=0;i<notesCursor.getCount();i++){
mDbHelper.deleteNote(i);
}
}while(notesCursor.moveToNext());
}
but i can't delete it, anyone can help me to solve this problem? thanks before
you should be able to use something like this:
mDbHelper.delete("tableName",null,null);
notesCursor.requery();
To delete all the values in your table and update your cursor.
It appears that you're getting the count of your "notes" table in order to pass in to use as the ID for the delete statement. Why? How can you guarantee that the IDs will match up? This is especially true after subsequent deletes. Why not just call the SQLiteDatabase delete() method without a specific ID to delete all the records?

Android Cursor with ORMLite to use in CursorAdapter

Is there any way to get Cursor for a query, which I am processing with ORMLite Dao object?
ORMLite now supports next(), previous(), moveRelative(offset), ... methods on the CloseableIterator class. This should allow you to move the underlying Cursor object around at will.
It also supports the following DAO Cursor methods:
dao.mapSelectStarRow(databaseResults) Return the latest row from the database results from a query to select *. With this you can change the cursor location (for example) and then get the current object.
dao.getSelectStarRowMapper() Provides a mapper that you can use to map the object outside of the Dao.
When you are building your own query with ORMLite, you use the QueryBuilder object. queryBuilder.prepare() returns a PreparedQuery which is used by various methods in the DAO. You can call dao.iterator(preparedQuery) which will return a CloseableIterator which is used to iterate through the results. There is a iterator.getRawResults() to get access to the DatabaseResults class. Under Android, this can be cast to an AndroidDatabaseResults which has a getCursor() method on it to return the Android Cursor.
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();
}
This is a bit complicated but you are definitely having to peer behind the vale to get to this object which is hidden by the database abstraction classes.
Did you try some of Gray's advice from this post? He explains how you can select a column as another name, such as, select id as _id.
If you're in an Activity and don't want to mess around with the QueryBuilder give the following a go, which is just as effective.
Cursor cursor = getHelper().getReadableDatabase().query(tableName, projection, selection, selectionArgs, groupBy, having, sortOrder)
If you mean the getHelper() method to reach the dao methods create etc. you only have to inherit from the OrmLiteBaseActivity<YourDBHelper> and you can call it. It will look sth like this:
public class YourClass extends OrmLiteBaseActivity<YourDBHelper> {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
getHelper().getDao().queryForAll();
...
}
}
If you mean the cursor to handle database operation: I don't think that you can reach it! But I don't understand why you should need it. ORMLite has nearly all functions of the cursor. So what do you need it for?

Android SQLite: Database empty in second activity

I've searched all over the net for a solution to this so lets hope someone here can help.
My app has a start up task which populates a SQLite database before loading the main menu. A second activity that can be accessed from the main menu needs access to this. Therefore I close the database in the first activity in order to stop locking errors.
For some reason, the database seems to have no rows as soon as I close the connection, in both the same activity and the second activity.
Heres a code sample:
SQLiteDatabase db = getWritableDatabase(); // get instance of current database
db.beginTransaction(); // set exclusive mode to speed up
for(GulbArticle g : gulbArticles){
this.insert(g);
}
db.setTransactionSuccessful();
// counting here returns 315 rows using the all2() function below
db.close();
// counting here returns 0 rows using the all2() function below
Here is a function I made to get the count back
public void all2(){
SQLiteDatabase db = getReadableDatabase();
String sql = "SELECT COUNT(*) FROM "+TABLE_NAME;
SQLiteStatement statement =db.compileStatement(sql);
long count = statement.simpleQueryForLong();
Log.v("ccount2",count+"");
}
So in both cases I'm initializing an instance of the database, but for some reason as soon as I close it once I can't reopen it/there seems to be nothing in the database. Maybe I'm missing something simple but this has really stumped me.
It seems you forgot to call db.endTransaction();, i.e. to commit the transaction.
It should read:
db.setTransactionSuccessful();
db.endTransaction();
db.close();
Also it is good idea to surround it in try-catch-finaly like this:
try {
db.beginTransaction();
// do your DB manipulation
db.setTransactionSuccessful();
} catch(...) {
...
} finally {
db.endTransaction();
}
db.close();
You don't need to close database when you start second activity. SQLite is normal DB management system - which means that these kind of situation should be resolved.
Resolving of this usually done by transactions mechanism - which you're tried to use in your code.
In your case I believe you have to use non-eclusive transactions - i.e. when record is locked in exclusive mode - record in unaccessible, so basic idiom should looks like:
db.beginTransactionNonExclusive();
try
{
// do smth
db.setTransactionSuccessful();
}
finally
{
db.endTransaction();
}

Android Contentprovider - update within an insert method

Is it ok to call the SQLiteDatabase update method in the insert() overridden method of a content provider?
Basically it's fine, but since you didn't provided code, I just can post 2 possible ways for it
First:
// In your content provider
public Uri insert(...) {
long insertId = db.insert(...);
if(insertId == -1) {
// insert failed, do update
db.update(...);
}
}
Second:
public Uri insert(...) {
long insertId = db.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_REPLACE)
if(insertId == -1) {
// insert and update/replace failed
}
}
Check out SQLiteDatabase for reference on the forth parameter. In most cases the last method should be sufficient, unless you want only certain fields being updated if the row exists and have all fields if it doesn't.
Most useful need for insertWithOnConflict may be, that you could insert a row and if it already exists, ignore the insert and instead return the Uri/primary key of the already existing row.
It's your choice what you write in your overridden methods.
So yes, it is ok.
I don't know what you're trying to do, but you might want to to take a look on the SQLiteDatabase's replace() method too. Maybe it better suits your needs.

Categories

Resources