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.
Related
I am new to database in Android but now I know the way to apply CRUD (Create, Read, Update, Delete) operations on an activity but in case of fragments, getWritableDatabase() is not working. I would like to know the best way to apply CRUD operations in fragments.
In activities, I made a class to handle database operations and then made its' object in the activity and was able to work on it thereafter.
Try
DbHelper helper = DbHelper.getInstance(getContext());
SQLiteDatabase db = helper.getWritableDatabase();`
instead
Here I tried to illustrate calling db from fragment class :
SQLiteDatabase db = context.getWritableDatabase(); // 'this' for activity
Initialize db object inside onAttach() or onActivityCreated() any other method :
[onAttach() is preferable]
public Cursor getAllData() {
Cursor result = db.rawQuery("SELECT * FROM "+ TABLE_NAME, null);
return result;
}
Tips: You should use these type of db calls into the background threads, not to invoke or block the UI thread which will result a better performance.
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.
In my app I want to initialize some data stored in a SQLite database.
But it turns out the SQLiteOpenHelper onCreate method is not called when I read my database (it is when I write into my database).
My app crash when I read the db for a table that does not exist (it does not crash if I create the table before). I could catch the exception but does not seem very clean to me.
Is it the normal behavior regarding SQLiteOpenHelper onCreate method or am I missing something?
Here is the initialisation function called in activity OnCreate()
private void InitializeDbPlayerList() {
SQLiteDatabase db;
Cursor cursorPlayers;
DbPlayerData dbPlayerData;
db = mGameDbHelper.getReadableDatabase ();
// The following line crash the app if PLAYER_TABLE_NAME does not exist
cursorPlayers=db.query(GameDatabaseOpenHelper.PLAYER_TABLE_NAME,
GameDatabaseOpenHelper.player_columns, null, new String[] {}, null, null,
null);
cursorPlayers.moveToFirst();
for(int j=0;j<cursorPlayers.getCount();j++)
{
dbPlayerData = new DbPlayerData(cursorPlayers.getString(0),cursorPlayers.getFloat(1),cursorPlayers.getFloat(2),
cursorPlayers.getInt(3),cursorPlayers.getInt(4));
mDbPlayerList .add(dbPlayerData);
}
}
Thx
Fabien
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?
I have two classes, both are not activity, one is to perform database operation and one is to forward the values as mediator class. DataBase class calling openOrCreateDataBase method from a 3rd Connectivity class.
contextWrapper.openOrCreateDatabase(sqlDBName, MODE_PRIVATE, null);
but here since this class is not activity, i am unable to pass parameter of ContextWrapper. Is there any other way to open database. I have tried,
sqLiteDatabase = SQLiteDatabase.openDatabase(path, factory, flags);
sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(file, factory);
But these not working for me.
thanks
You can't create a database without Context. This is one of the thing context exists for: it allows you to access shared preferences, database and so on.
Yes there is a way. In the constructor of the db wrapper class you can add the ContextWrapper as a parameter and call it, like this:
public ctor(ContextWrapper wrapper) {
SQLiteDatabase db = wrapper.openOrCreateDatabase("myDB", wrapper.MODE_PRIVATE, null);
}