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'
Related
In the DB I have implemented in my Android App, some columns are designed to contain text in different languages, for example this table:
CREATE TABLE "food" (
`_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`ID` INTEGER NOT NULL UNIQUE,
`name` TEXT NOT NULL,
`name_it` TEXT,
`name_rus` TEXT,
`description` TEXT,
`description_it` TEXT,
`description_rus` TEXT,
`kcal` INTEGER,
`icon_food` TEXT,
`image_food` TEXT,
`category_id` INTEGER,
FOREIGN KEY(`category_id`) REFERENCES category ( _id )
)
I want to use a static String to keep the name of the column, translated according to the language of the User's device
public static final class FoodEntry implements BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendEncodedPath(PATH_FOOD).build();
public static final String TABLE_NAME = "food";
public static final String COLUMN_ID = "ID";
**public static final String COLUMN_NAME = Resources.getSystem().getString(R.string.food_COLUMN_NAME);**
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_ICON_FOOD = "icon_food";
public static final String COLUMN_CATEGORY_ID = "category_id";
public static Uri buildFoodUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
}
Here the string.xml
<string name="food_COLUMN_NAME">name</string>
This does not work because of the following error:
Caused by: android.content.res.Resources$NotFoundException
How could I reach the goal to translate the column without touching more code? I wish to use a string resource that seems the perfect solution for my database structure
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
I would fully translate my Android app. (this includes the SQLite is displayed on the phone language)
This is like now connect;
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "quotes.db";
private static final String DB_PATH_SUFFIX = "/databases/";
private static final String TABLE_QUOTES = "quote";
private static final String KEY_ID = "_id";
static Context myContext;
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myContext = context;
}
I had thought to remove the name string database and pass it the name database using the strings.xml file.
super(context, context.getResources (). getString (R.string.DATABASE_NAME), null, DATABASE_VERSION);
Also look for the query to pass on through strings.xml, but can not find clear documentation.
I would appreciate if I do not guide a little. Many Thanks.
Example the query:
// Select All Query
String selectQuery = "SELECT name, COUNT(author_name ) AS count FROM author LEFT JOIN quote ON name = author_name WHERE name LIKE '%"
+ value + "%' GROUP BY name ORDER BY name ASC";
I modifing the table sqlite and code adding "+Locale.getDefault().getLanguage() +":
String selectQuery = "SELECT quote._id, quote.author_name_"+ Locale.getDefault().getLanguage() +", quote.qte_"+ Locale.getDefault().getLanguage() +
", quote.category_name_"+ Locale.getDefault().getLanguage() +",fav FROM quote,author where author.name_"+ Locale.getDefault().getLanguage()+
" = quote.author_name_"+ Locale.getDefault().getLanguage() +" and quote.category_name_"+ Locale.getDefault().getLanguage() +
"!='Tips Romanticos' ORDER BY quote.author_name_"+ Locale.getDefault().getLanguage() +" "+limit;
The query result is:
SELECT quote._id, quote.author_name_es, quote.qte_es,
quote.category_name_es,fav FROM quote,author where author.name_es =
quote.author_name_es and quote.category_name_es!='Tips Romanticos'
ORDER BY quote.author_name_es LIMIT 50
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)
I am trying to put together an SQL database but don't really know how to make it work. The intention is to have multiple columns, some with integers, some with strings in their cells. For this app, I want repetitions to be an integer and exercise to be a string. Here is the relevant parts of the code:
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_EXERCISE = "exercise";
public static final String KEY_REPS = "repetitions";
private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " ("
+ KEY_ROWID + " integer primary key autoincrement, "
+ KEY_DATE + " text not null, "
+ KEY_EXERCISE + " text not null, "
+ KEY_REPS + " int not null, "
public long createExercise(String exercise, int reps) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_EXERCISE, exercise);
initialValues.put(KEY_REPS, reps);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
I put data in this table using test strings. Then I try to pull the data with the following query:
public Cursor graphQuery(String exercise, String workout) {
return mDb.query(DATABASE_TABLE, new String[] {KEY_DATE, KEY_REPS}, null, null,
null, null, null);
From there I try to put the data into a number array but it gives me an error. It tells me to put KEY_REPS as a number when I declared it. But if I declare KEY_REPS as a number it doesn't let me build my databes.
Cursor cursor = mDbHelper.graphQuery(currentexercise, currentworkout);
startManagingCursor(cursor);
Number[] reps = new Number[]{workoutDbAdapter.KEY_REPS}; //error here
I feel like I am missing a key part in how to create my database. Can anyone help?
Code from book I am trying to follow (except using integers) (from comment on first answer)
private void fillData() {
Cursor remindersCursor = mDbHelper.fetchAllReminders();
startManagingCursor(remindersCursor);
// Create an array to specify the fields we want (only the TITLE)
String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};
That being said, if someone knows of a good website that teaches SQLite as it applies to Android that would be awesome. The only ones I have been able to find are generic SQL sites and they aren't very helpful.
Cursor cursor = mDbHelper.graphQuery(currentexercise, currentworkout);
startManagingCursor(cursor);
Number[] reps = new Number[]{WorkoutDbAdapter.KEY_REPS}; //error here
This code here doesn't do what (I think) you want it to. You need to iterate over the cursor and get the data from there. I'm pretty sure, if you followed the Android sample code for using databases that WorkoutDbAdapter.KEY_REPS is a string constant that holds reps column name.
Try doing something like this:
List<Number> allReps = new ArrayList<Number>();
Cursor cursor = mDbHelper.graphQuery(currentexercise, currentworkout);
while (cursor.moveToNext()) {
int reps = cursor.getInt(cursor.getColumnIndexOrThrow(mDbHelper.KEY_REPS));
allReps.add(reps);
}
Number[] repsArray = allReps.toArray(new Number[]{});
// do stuff with repsArray and don't forget to close cursor