Why do i get android.database.sqlite.sqlitecursor # error - java

I get null value whenever I try to display the value of nexpdate. I get the following error android.database.sqlite.sqlitecursor # .
// insertion of values in renew table
public void insertrenew (String rcode, String nexpdate) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("rcode", rcode);
contentValues.put("nexpdate", nexpdate);
db.insert("renew", null, contentValues);
}
//java code to get the value of nexpdate
public String getrenew (String rcode) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT nexpdate from renew where rcode = " + rcode;
String cursor = String.valueOf(db.rawQuery(selectQuery, null));
return cursor;
}

I assume you are getting an error:
android.database.sqlite.sqlitecursor # XXXX // where XXXX indicates object code
Reason/Details:
Reason being here is you are directly casting Cursor object into the String and that's where an issue is!
String cursor = String.valueOf(db.rawQuery(selectQuery, null));
FYI, rawQuery() method actually returns Cursor value and we need to iterate through the cursor actually to get the needed data. You may refer How to retrieve data from cursor class for more details on getting data from the Cursor.

Related

updating method using content values

Helper
public boolean mMessagesSent(String ID,int Data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, ID);
contentValues.put(KEY_MESSAGES_SENT, Data);
db.update(TABLE_USER_DATA, contentValues, null, null);
return true;
}
Activity
mainData.mTotalMessages("MyData", +1);
mainData.mTotalMessagesSent("MyData",+1);
mainData.mMessages(MessageRecieverId,+1);
mainData.mMessagesSent(MessageRecieverId,+1);
Is this the correct method to update data... I want to increase the int value of data by 1 so i have put +1 but still the value is empty when i retrieve data
CODE AFTER FOLLOWING FIRST ANSWER
public boolean mMessagesSent(String ID,int Data) {
MainData mainData = new MainData(getApplicationContext());
SQLiteDatabase db = mainData.getWritableDatabase();
String newId = ID;
int newData = Data;
MainData helper = new MainData(this); //Change the name to your Helper Class name
Cursor data = helper.getData();
while (data.moveToNext()) {
newId = data.getString(data.getColumnIndex("Data"));
newData = data.getInt(data.getColumnIndex("TotalMessagesSent"));
}
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_DATA, newId);
contentValues.put(KEY_MESSAGES_SENT, (newData + 1)); //Change the value of newData(which is actually your old value) by incrementing
db.update(TABLE_USER_DATA, contentValues, null, null);
return true;
}
FETCHING
final MainData myDBHlpr = new MainData(getActivity());
Cursor csr = myDBHlpr.getAllQuestions(getActivity());
while (csr.moveToNext()) {
mTotalMessagesSent.setText(csr.getString(1));
mTotalMessagesRecieved.setText(csr.getString(csr.getColumnIndex("TotalMessagesRecieved")));
mTotalMessages.setText(csr.getString(csr.getColumnIndex("TotalMessages")));
}
csr.close();
Is this the correct method to update data... I want to increase the int value of data by 1 so i have put +1 but still the value is empty when i retrieve data
If you meant to increase the existing value of data by once each time you call the function mMessagesSent()
You can consider to first take the value from the database if it exists, and increment the value. Create a function in Helper as shown below
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
return db.rawQuery(query, null);
}
This will return a Cursor to the Database, to read the values in the database. Do not put the function mMessagesSent in Helper class, put it in the Activity. Now in your mMessagesSent function, call the above function getData() as shown
public void mMessagesSent() {
SQLiteDatabase db = this.getWritableDatabase();
String newId = "default value whatever you have specified";//These two lines may be removed and put outside. If you already have it, then
int newData = 0; //not required to declare here at all, just replace with those variable names
HelperClassName helper = new HelperClassName(this); //Change the name to your Helper Class name
Cursor data = helper.getData();
while(data.moveToNext()){
newId = data.getString(0);
newData = data.getInt(1);
}
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, ID);
contentValues.put(KEY_MESSAGES_SENT, (newData+1)); //Change the value of newData(which is actually your old value) by incrementing
long returnVariable = db.update(TABLE_USER_DATA, contentValues, null, null);
if(returnVariable == -1){
//-1 means there was an error updating the values
}
else{
//the return value if successful will be number of rows affected by the update
}
}
I hope you got your answer.

How to use prepared statement for sql?

I'm trying to have an SQLite database in android but I have a problem with that:
I'm trying to update the text value in the "response" column with id 0. The first problem I had was that the string I was using for the update used an apostrophe (') and it had syntax errors because sql closes the string with an '. So I now am using a prepared sql statement for that. The problem now is that the long that is returning gives a -1, so that means that no rows were effected. So how can I update my current string to the row with id=0?
Note: the first string also has an ' but was added using the addData funtion and it didn't give any errors just using db.insert, is that the problem, should I replace all my code with prepared statements?
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
public long updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
String sql = "UPDATE json_response SET response=? WHERE ID='0'";
SQLiteStatement statement = db.compileStatement(sql);
statement.bindString(1, newName); // matches second '?' in sql string
long rowId = statement.executeInsert();
return rowId;
}
I have not used prepared statements much so I can't say why that is not working, but why not use the db.update() method? It takes ContentValues as an argument similar to tour addData() method. Give this a shot.
public int updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("json_response",newName);
int rows = db.update(TABLE_NAME, cv, "ID=0", null);
return rows;
}
[EDIT] update() returns an integer representing the number of rows affected instead of which row was affected. Keep that in mind as your variable name rowId implies that is not what you are looking for.
[EDIT 2] And no, there is no problem with the addData() method that I can see. The apostrophe that was added did not cause an error because ContentValues parameterizes the string values before adding them into the database. Basically, all SQL-like syntax will be ignored when inserting values, which is great for security reasons.
The problem is, I think, that WHERE ID='0' will always fail; what you want is WHERE ID=0

I cant start this sqlite select code

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());
}

Android SQLite, update specific field from specific row

I am trying to update a specific column in my record within SQLite - the object has various attributes, but I just want to update a single field within that row. Here are my codes:
public boolean updateFavorite(String email, int isFavorite){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(EMAIL, email);
args.put(IS_FAV, isFavorite);
int i = db.update(TABLE_FAVORITES, args, EMAIL + "=" + email, null);
return i > 0;
}
I am using the email for my where clause, i.e update record from favorites, set isFavorite to (given value) where email is (passed in value).
There is a problem with my query, which was caught by logcat, as shown below
android.database.sqlite.SQLiteException: near "#sjisis": syntax error (code 1): , while compiling: UPDATE Favorites SET email=?,isFavorite=? WHERE email=sjkshs#sjisis.com
Can anyone help me identify what is wrong with my codes to produce this error?
P.S my FavoriteObject class has other attributes other than just email and isFavorite, but in this case I am not trying to update them at all
Try to make email in where clause be argument too, i try to change your code but didn't test yet :
public boolean updateFavorite(String email, int isFavorite){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values= new ContentValues();
values.put(EMAIL, email);
values.put(IS_FAV, isFavorite);
//add arguments for where clause
String[] args = new String[]{email};
int i = db.update(TABLE_FAVORITES, values, "EMAIL=?", args);
return i > 0;
}
Looks like it's complaining about the email address, perhaps the #.
try
int i = db.update(TABLE_FAVORITES, args, EMAIL + "= ' " + email + "'", null);
ie. single quotes around the email address.

how to update a varchar in the sqlite database in java

I have a problem with to update a varchar in the sqlite database in java.
when I run this source, than I get a error.
I want String a to update to String b.
This is my source:
public void onClick (View v){
String a = "Test1";
String b = "Test2";
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, a, null);
db.close();
}
And this is my Error:
Error updating Level1=Test2 using update Game SET Level1=? WHERE Test1.
can someone help me?
Thanks!
I'm not 100% sure what you are trying to achieve, however, you added a as a where clause and did not provide any arguments, so consequently you got the SQL statement shown in the error.
From the API:
public int update (String table, ContentValues values,
String whereClause, String[] whereArgs)
This one works ...
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, "Level1=?", new String[] {a} );
db.close();
... if this is the resulting SQL you want to execute:
update Game SET Level1=? WHERE Level1 = 'Test1'
update Game SET Level1=? WHERE Test1.
Where Test1 is.. what? Where is the conditional part of your update statement. It's expecting something like:
update Game SET Level1=? WHERE ColumnName='Test1'
Taken from this website:
If the UPDATE statement does not have a WHERE clause, all rows in the table are modified by the UPDATE. Otherwise, the UPDATE affects only those rows for which the result of evaluating the WHERE clause expression as a boolean expression is true.
A String on it's own is in no way a boolean expression.

Categories