I cant start this sqlite select code - java

This sourch code for my app:
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM Note where Username = '"+acc+"'", null);
//Cursor cursor = db.rawQuery("SELECT * FROM Note ", null);
if (cursor.moveToFirst()) {
do {
Note_DTO note = new Note_DTO();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setDate(cursor.getString(1));
note.setUser(cursor.getString(2));
note.setContent(cursor.getString(3));
NoteList.add(note);
} while (cursor.moveToNext());
}
This function return nothing , but in debug mode , every single item was set .
Should it return a list of what i selected , i don't understand why and how it's not . Thanks for your help .

Use getReadableDatabase() for query purposes as follows.
SQLiteDatabase db = this.getReadableDatabase();
Please Read SQLiteOpenHelper documentation here for getReadableDatabase()
Create and/or open a database. This will be the same object returned
by getWritableDatabase() unless some problem, such as a full disk,
requires the database to be opened read-only. In that case, a
read-only database object will be returned. If the problem is fixed, a
future call to getWritableDatabase() may succeed, in which case the
read-only database object will be closed and the read/write object
will be returned in the future.
Read SQLiteOpenHelper documentation here for getWritableDatabase()
Create and/or open a database that will be used for reading and
writing. The first time this is called, the database will be opened
and onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int)
and/or onOpen(SQLiteDatabase) will be called.
Once opened successfully, the database is cached, so you can call this
method every time you need to write to the database. (Make sure to
call close() when you no longer need the database.) Errors such as bad
permissions or a full disk may cause this method to fail, but future
attempts may succeed if the problem is fixed.
According to the getWritableDatabase() documentation, it clearly mentions that it will cache the database. So it's possible to retrieve data from a cached copy of your database. As same as make sure you've closed the database connection after your transaction.
Finally your code would be like this
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM Note where Username = '"+acc+"'", null);
if (cursor.moveToFirst()) {
do {
Note_DTO note = new Note_DTO();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setDate(cursor.getString(1));
note.setUser(cursor.getString(2));
note.setContent(cursor.getString(3));
NoteList.add(note);
} while (cursor.moveToNext());
}

Try this
SQLiteDatabase database = this.getReadableDatabase();
String selectQuery = "SELECT * FROM Note where Username " + " LIKE '%" + acc + "%'";
Cursor cursor = database.rawQuery(selectQuery, null);
int count = cursor.getCount();
database.close();
if(count==0)
{
return result;
}
else
{
if (cursor.moveToFirst()) {
do {
Note_DTO note = new Note_DTO();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setDate(cursor.getString(1));
note.setUser(cursor.getString(2));
note.setContent(cursor.getString(3));
NoteList.add(note);
} while (cursor.moveToNext());
}

Related

trying to call user_id from sqlite

I'm trying to call user_id from sqlite database but I get this error
android.database.sqlite.SQLiteException: unknown error (code 0 SQLITE_OK): Queries can be performed using SQLiteDatabase query or rawQuery methods only.
at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
public Database user_id(){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT user_id FROM OrderDetails ;");
db.execSQL(query);
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
c.moveToFirst();
}
return user_id();
}
Please don't recommend another solution because I'm stuck with this for more than a day and I tried almost all solutions represented in stackoverflow and online
From: https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase#execSQL(java.lang.String)
public void execSQL (String sql) Execute a single SQL statement
that is NOT a SELECT or any other SQL statement that returns
data.
So remove this line:
db.execSQL(query);
The method execSQL() is not used to execute queries that fetch rows, like SELECT statements. You can use it with INSERT, UPDATE, CREATE, etc.
Also, I think that you want to return the user's ids as a Cursor, right?
So why:
public Database user_id()
this returns a Database object (whatever this is).
Change the method to this:
public Cursor user_id(){
SQLiteDatabase db = getReadableDatabase();
String query = "SELECT user_id FROM OrderDetails";
Cursor c = db.rawQuery(query, null);
return c;
}

Java SQL Database getWritableDatabase

In my DataBase Adapter I have a list of methods that puts data, upgrades data
and retrieves data. In each method I Instatiate like this
SQLiteDatabase db = this.getWritableDatabase();
I used to close the database on every method and my app used to crash. Then I left them open in every method so the crashing stopped.
Does the line of code open several database connections when I use several methods with the same line?
Is there a better approach to open the database?
Here's one of my methods
public int getAntalRows() throws Exception {
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCount= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_PRODUCTS,
null);
mCount.moveToFirst();
int x= mCount.getInt(0);
mCount.close();
return x;
}

How does Cursor work in android [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm having a hard time exactly visualizing 'Cursor' functionality in my program. I kind of get the jist of it, but can anyone explain it's functionality in detail?
By Cursor, I mean the Cursor interface.
I can't simply understand the role it plays with anything.
http://developer.android.com/reference/android/database/Cursor.html
A Cursor object is returned from a query on a SQLite database.
It will return all rows that the query returns.
Say you have a table called names in your database database configured as such:
_id _name
1 Space Ghost
2 Zorak
3 Moltar
4 Brak
If you want to get all data from this table and use it, you would do
something like this:
public HashMap<Integer, String> getNames(){
HashMap<Integer, String> data = new HashMap<Integer, String>();
try{
SQLiteOpenHelper helper = new MyOpenDbHelper(context);
SQLiteDatabase db = helper.getReadableDatabase();
String selectQuery = "SELECT * FROM names";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()){ //make sure you got results, and move to first row
do{
int mID = cursor.getInt(0); //column 0 for the current row
String mName = cursor.getString(1); //column 1 for the current row
data.put(mID, mName);
} while (cursor.moveToNext()); //move to next row in the query result
}
} catch (Exception ex) {
Log.e("MyApp", ex.getMessage());
} finally
{
if (cursor != null) {
cursor.close();
}
if (db != null) {
db.close();
}
}
return data;
}
Usually you will create your own class to extend SQLiteOpenHelper, as such:
public class MyOpenDbHelper extends SQLiteOpenHelper {
//........
}
From Wikipedia
In computer science, a database cursor is a control structure that enables traversal over the records in a database. Cursors facilitate subsequent processing in conjunction with the traversal, such as retrieval, addition and removal of database records. The database cursor characteristic of traversal makes cursors akin to the programming language concept of iterator.
From Here
A cursor is a tool that allows you to iterate the records in a set. It has concepts of order and current record.
From The documentation you pointed yourself
provides random read-write access to the result set returned by a database query.
So don' t think Cursor as a functionality, but as a mean for reaching records in a more efficient way from any database.
Are you reffering to this Cursor usage?
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();

SQLite query - date reserved word?

Am just curious, is date a reserved word i SQLite? I have a column which is named date, and trying to run this query:
DELETE FROM cases WHERE date <= date('now','-1 day')
By doing this:
String query = "DELETE FROM cases WHERE date <= date('now','-1 day')";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
boolean found = cursor.moveToFirst();
if(found) {
int result = cursor.getCount();
Log.w("DeleteOldCases: ", "Result: " + Integer.toString(result));
db.close();
}
But the cursor just gives me a false back, when calling moveToFirst. But in my database there are actually rows that are older than one day. Can anybody explain whats wrong here?
Thanks!
Yes it seems to be a reserved word.
look at: http://www.sqlite.org/lang_datefunc.html
date(timestring, modifier, modifier, ...)
It's strange to have a cursors form DELETE statement. Try to split the operation in
SELECT * FROM cases WHERE date <= date('now','-1 day')
then execute your checks
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
boolean found = cursor.moveToFirst();
if(found) {
int result = cursor.getCount();
Log.w("DeleteOldCases: ", "Result: " + Integer.toString(result));
db.close();
}
and then execute the DELETE part
DELETE FROM cases WHERE date <= date('now','-1 day')
This question is quite old but it deserves a proper answer.
No, date is not a reserved word.
The problem with your code is that you are using the method rawQuery() to delete from the table, which is not the way to do it.
rawQuery() should be used to return rows from the table in the form of a Cursor object.
Since your sql statement does not return any rows the method moveToFirst() returns false.
What you should use is the method delete() which returns the number of deleted rows:
int result = db.delete("cases", "date <= date('now', '-1 day')", null);

Not closing cursor or database object?

I get this error after going to this activity, starting a new one, coming back. It doesn't happen when I first load the activity. functionally everything works... but I still get this error.
ERROR/Cursor(1059): Finalizing a
Cursor that has not been deactivated
or closed. database =
/data/data/com.roger.testapp/databases/data,
table = null, query = SELECT MAX(_id)
FROM record
03-02 16:47:21.835:
ERROR/Cursor(1059):
android.database.sqlite.DatabaseObjectNotClosedException:
Application did not close the cursor
or database object that was opened
here
In onCreate:
mDbHelper = new CommonDbAdapter(this);
mDbHelper.open();
fillData();
fillData() calls fetchNote in my dbhelper, the cursor is used for a couple things, if rowId == 0, that means I didn't select an item to get into this activity and I want to get the last row in that table. if rowId = something else, then I grab that row. I think the problem is in here somewhere, I'm just not sure.
public Cursor fetchNote(long rowId, String table, String columns) throws SQLException {
if (rowId == 0) {
String query = "SELECT MAX(_id) FROM record";
Cursor cursor = mDb.rawQuery(query, null);
rowId = 0;
if (cursor.moveToFirst())
{
rowId = cursor.getInt(0);
}
}
Cursor mCursor =
mDb.query(true, table, new String[] {KEY_ROWID,
columns}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
In onDestroy:
super.onDestroy();
if (mDbHelper != null) {
mDbHelper.close();
}
Also, I am startManagingCursor
Don't close your database in onDestroy. Close it immediately after you're done using it(make sure every cursor is closed before the database is closed). onDestroy may not be called when you expect.
Also, close your Cursor object after you're done using it.
Edits:
Since your activity is managing your Cursor, you may consider stop managing it and closing everything in the onPause method, and in onResume open everything up and fillData once again. If you could change your code around so you dont rely on your activity managing the cursor, you wouldn't need to hold into open database objects and worry about them.
I would recommend not returning a cursor. It's a scarce resource.
In n-tiered Java EE, the best practice is to close all persistence resources (Connection, Statement and ResultSet) in the scope of the method in which they were created. Map a ResultSet into an object or collection and close the ResultSet.
I don't know if there's something special about Android that would invalidate this.
Take a look at the activity lifecycle - you can see that when you navigate away from your activity (onPause) if another activity needs memory your process is killed, but when your user then returns to the activity, it will hit onCreate again. This time you are opening a NEW CommonDbAdapter (but you never closed the original one) - thus when you eventually hit onDestroy you would only close the very latest mDbHelper.
As stated by others, your best method is not to pass the cursor back from the DBHelper, create an object with your data, close the cursor and pass your object back. Also close the DBHelper once you have used it, you can always create another if you need to use it again.

Categories