Error while updating the column in SQLite Database Android - android

I am trying to update the column in the table using update method. I am thrown syntax error like this:
SQLiteException: no such column: DataStructures (code 1): , while compiling: UPDATE tbl_courses SET checked_status=? WHERE course_name=DataStructures
Here is my Database Query:
public static final String TABLE_COURSES = "tbl_courses";
public static final String COLUMN_COURSE_ID = "_id";
public static final String COLUMN_COURSE_NAME = "course_name";
public static final String COLUMN_COURSE_SELECTED = "checked_status";
public static final String COLUMN_COURSE_CODE = "course_code";
public void updateSelectedCourseField(String courseName, String courseSelected) {
ContentValues args = new ContentValues();
args.put(COLUMN_COURSE_SELECTED, courseSelected);
database.update(TABLE_COURSES, args, COLUMN_COURSE_NAME + "=" + courseName,null);
}
I am trying to change checked_status value in tbl_courses where course_name = DataStructures. I am sure its in the database but its throwing me the error. please guide me through this.

A better solution is to avoid string concatenation to build your query. Instead do this:
database.update(TABLE_COURSES, args, COLUMN_COURSE_NAME + "=?", new String[]{courseName});
This will not only take care of the quotes for you, but it will also avoid SQL injection attacks. Always be careful when using user input in a SQL query.

Related

CursorIndexOutOfBoundsException from SQLite query

I've been struggling a while with querying my SQLite database using one of my table field. I successfully query using the ForeignId field, but not with the Available field of my table QuizTable. I was hoping you could point out something I missed. Here is the call I make to the function queryQuiz. Please note the whereClause (kind of cut off) which is supposed to filter the available field for a value of 1. (side note: what if you want to query for different data types?)
QuizCursorWrapper cursor = db.queryQuiz(QuizTable.Cols.AVAILABLE + "=?", new String[]{"1"});
This is my queryQuiz function in a class that extends SQLiteOpenHelper.
Here's the error I am getting from calling queryQuiz:
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
public QuizCursorWrapper queryQuiz(String whereClause, String[] whereArgs){
Cursor cursor = db.query(
QuizTable.NAME,
null,
whereClause,
whereArgs,
null,
null,
null
);
return new QuizCursorWrapper(cursor);
}
my QuizCursorWrapper class
public class QuizCursorWrapper extends CursorWrapper {
public QuizCursorWrapper(Cursor cursor){
super(cursor);
}
public String getQuiz(){
String paragraph = getString(getColumnIndex(QuizSchema.QuizTable.Cols.PARAGRAPH));
return paragraph;
}
public String getQuizUUID(){
String uuid = getString(getColumnIndex(QuizSchema.QuizTable.Cols.UUID));
return uuid;
}
}
and finally, my QuizSchema which defines the fields in my table.
public class QuizSchema {
public static final class QuizTable{
//nested class
public static final String NAME = "quizTable";
public static final class Cols{
public static final String SCORE = "score";
public static final String PARAGRAPH = "paragraph";
public static final String FOREIGNID = "foreignId";
public static final String UUID = "uuid";
public static final String AVAILABLE = "available";
}
}
}
I am very confused because I can clearly see rows with available fields equal to 1 in my quiz table . Sorry for the broad question, it's just that I can't put a finger on a problem and the debugger isn't too helpful. Please let me know if you need more info.
I believe that your issue is how column storage class/type affinity effects comparisons.
The solution is force the type affinity and thus how the comparisons are made. Forcing the type affinity can be achieved using CAST to set the type affinity.
As such a solution could be to CAST the values to type INTEGER for the comparison. You could do this by using :-
QuizCursorWrapper cursor = db.queryQuiz("CAST(" + QuizTable.Cols.AVAILABLE + " AS INTEGER) =CAST(? AS INTEGER)", new String[]{"1"});
You may wish to have a read of :-
Datatypes In SQLite Version 3

Deleting from a ContentProvider?

I want to delete the first item in my content provider. I'm trying to do this by deleting the row with id 0 (as shown below). This does not work--the app will not run with this code.
public void onClickDeleteExercise(View view){
int ret_val = getContentResolver().delete(MyProvider.CONTENT_URI, MyProvider.id+ " = ? ", new String[]{"0"});
Toast.makeText(getBaseContext(), "First exercise deleted", Toast.LENGTH_LONG).show();
}
My provider has defined these:
static final String PROVIDER_NAME = "com.example.contentproviderexample.MyProvider";
static final String URL = "content://" + PROVIDER_NAME + "/cte";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String id = "id";
static final String name = "name";
static final int uriCode = 1;
How would I go about deleting from this? Thank you!!
app:
getContentResolver().delete(Provider.CONTENT_URI,Provider._ID + "=" + id, null);
provider:
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/")
public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_URI,
ENTRIES_TABLE_NAME);
public static final String _ID = "_id";
#Override
public int delete(Uri uri, String where, String[] whereArgs) {
database.delete(ENTRIES_TABLE_NAME, where, whereArgs);
return 0;
}
hint:
to exclude errors if u use android studio make breakpoint on
public int delete(..) {
database.delete() <= here breakpoint
}
and see if after execute in app getContentResolver() the debugger will move you to this breakpoint
if it fails u have not registered content provider properly
if u will hit breakpoint implementation of database.delete is incorect
If I want to delete the first item, would I just set id to 0?
depends if your _id is PRIMARY_KEY in table
SQlite database Engine has a mechanism that creates a unique ROWID for every new row you insert.
if you table have a PRIMARY_KEY then it will eventually becomes the alias for that ROW_ID
class SQLiteDatabase
/**
* Convenience method for deleting rows in the database.
*
* #param table the table to delete from
* #param whereClause the optional WHERE clause to apply when deleting.
* Passing null will delete all rows.
* #param whereArgs You may include ?s in the where clause, which
* will be replaced by the values from whereArgs. The values
* will be bound as Strings.
* #return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int delete(String table, String whereClause, String[] whereArgs) {}
so to pas id as int u need:
database.delete(TABLE_NAME, KEY_ID + " = ?",new String[]{Long.toString(id)});
or simple:
String[] whereArgs = new String[] {String.valueOf(rowId)};
Caution: Rowids will change when the db is vacuumed
So please take extra care when you define a table and need to reference records using rowids.
From the official documentation:
“Rowids can change at any time and without notice. If you need to depend on your rowid, make it an INTEGER PRIMARY KEY, then it is guaranteed not to change”.
add also AUTOINCREMENT so you are sure that the same rowid(s) are not reused when rows are deleted.
In one of my tables
I got key message_id and it is beginning from value = 1
If u not sure about Key Value use on Android device SQLIte Debugger very excellent app

Yet another 'column _id does not exist' issue

I think I have checked all the previous posts on this issue but none seem to be helping me...
Basic stuff - trying to use a cursor adaptor bound to my database but I am getting:
java.lang.IllegalArgumentException: column '_id' does not exist
My schema has that column defined (although I do have 2 tables, both with the same name - is that an issue?), like this:
public static abstract class dbMain implements BaseColumns {
public static final String TABLE_NAME = "mpgMain";
public static final String ENTRY_ID = "_id";
public static final String VEHICLE_NAME = "v_name";
}
public static abstract class dbHistory implements BaseColumns {
public static final String TABLE_NAME = "mpgHistory";
public static final String ENTRY_ID = "_id";
public static final String TRIP_DATE = "date";
}
From other posts, I have put _id in my cursor porjection:
String[] projection = {dbMain.ENTRY_ID, dbMain.VEHICLE_NAME};
Cursor mpgCur = mpgDB.query(dbMain.TABLE_NAME, projection, null, null, null, null, null);
...but then my stack trace gives the same error, on the query line. If I remove the ENTRY_ID from the projection, the same error but on the later line instantiating the adaptor:
String[] fromColumns = {dbMain.VEHICLE_NAME};
int[] toViews = {R.id.displayVehicle};
SimpleCursorAdapter vehAdapter = new SimpleCursorAdapter(this,
R.layout.activity_first_screen, mpgCur, fromColumns, toViews, 0); <--- HERE
I've also tried putting a space in the CREATE TABLE command, before the _id field:
private static final String SQL_CREATE_MAIN_TABLE =
"CREATE TABLE " + dbMain.TABLE_NAME + " ( " +
dbMain.ENTRY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
Any ideas gratefully received...
If I'm not mistaken, by implementing BaseColumns, you don't have to specify "_id" in your schema. Just use the constant _ID (so, dbMain._ID and dbHistory._ID)

How to update table in sqlite android

In my app i want to update my database table based on two column.Means update salary where firstname="ekant" and last name="kancha".So can any body plz tell me what will be the query i have to write.
public int updateStatus(int salary,String fname,String lName)
{
ContentValues cv=new ContentValues();
String where = fname+ "=" + "ekanta";
cv.put("salary",salary);
return sdb.update(DATABASE_TABLENAME, cv, where, null);
}
this code works only when i want to update based on first name..But i want to update based on firstname and lastname.
plz help me.thanx
Use placeholders. This makes it easier to read the SQL query and protects against SQL Injection (accidental or otherwise).
public int updateSalary (int salary, String fname, String lName)
{
ContentValues cv = new ContentValues();
cv.put("salary", salary);
/* use COLUMN NAMES here */
String where = "firstname = ? and lastname = ?";
/* bind VALUES here */
String[] whereArgs = new { fname, lname };
return sdb.update(DATABASE_TABLENAME, cv, where, whereArgs);
}
If you have constants (e.g. private final static COLUMN_FNAME = "firstname") for the COLUMN NAMES, then you can build where using these constants.
However, do not put VALUES in the where string. Instead, use ? and supply any VALUES via the whereArgs array as per the above example.
Also, it is possible for people (even within the same organization) to share the same first name and last name. Basing the database queries/updates around such a pairing will break in such cases so it may be prudent to work on designing the API to work with a better record identifier.
use this...
String where = fname+ "=" + "ekanta" + " and " + lname + "=" + "your lastname";

query table columns for specific data values in sqlite android

i am trying to query my database so that it returns only rows with a specific value in a certain column.but when i run it, it still returns all the rows. please take a look at the code and see if i have done it incorrectly. I am trying to query for the string in the PRIORITY column. i want to display those specific rows in a listview. Thank you.
private static final String DATABASE_NAME = "MemoData.db";
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_TABLE = "Places";
public static final String KEY_ID = "_id";
public static final String NAME = "Title";
public static final String CATEGORY = "category";
public static final String PRIORITY = "priority";
private static final String TAG = "DBAdapter";
private static final String DATABASE_CREATE = "create table Places (_id integer primary key autoincrement, Title text, category text, priority text);";
public Cursor priorityData(){
String[] resultColumns = new String[] {KEY_ID,NAME,CATEGORY,PRIORITY };
String[] condition = {"High"};
Cursor cursor = db.query(DATABASE_TABLE, resultColumns, KEY_ID + "=" + "?", condition, null, null, null);
if(cursor.moveToNext()){
return cursor;
}
return cursor;
}
The values for priority columns can be "Low", "Medium" or "High". i am trying to query the database to return rows whose values are set as "High" in the PRIORITY column.
I am trying to query for the string in the PRIORITY column...
So your filter should be
PRIORITY + " = ?"
instead of
KEY_ID + "=" + "?"
Also it's not a good idea to have a text column to hold values from a limited set of possibilities that you are then filtering and your last if makes no sense.
I think he meant that you should use ENUM type to your PRIORITY variable, because it has limited set of possibilities.
So it should looks something like this:
priority ENUM('LOW','MEDIUM','HIGH') NOT NULL DEFAULT 'MEDIUM'

Categories

Resources