I am using the query method of SQLiteDatabase. How do I do a query that gives me items by a particular STRING?
this query :
public ArrayList<RecipeInfo> getTypeRecipe() {
ArrayList<RecipeInfo> recipeInfo = new ArrayList();
Cursor cursor = null;
try {
cursor = db.query(TABLE_RECIPES_NAME, TABLE_RECIPE_COLUMNS,
RECIPE_COLUMN_TITLE+" =lunch", null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
RecipeInfo ri=cursorToRecipes(cursor);
recipeInfo.add(ri);
cursor.moveToNext();
}
}
catch (Throwable t){
t.printStackTrace();
}
return recipeInfo;
}
If you want the record corresponding to a particular String as its title, (say, title="lunch"), you do the query as follows:
cursor=db.query(TABLE_RECIPES_NAME, TABLE_RECIPE_COLUMNS,
"title=?", new String[]{"lunch"}, null, null, null);
OR
cursor=db.query(TABLE_RECIPES_NAME, TABLE_RECIPE_COLUMNS,
RECIPE_COLUMN_TITLE+"=?", new String[]{"lunch"}, null, null, null);
This will query the table TABLE_RECIPES_NAME and return all columns specified by TABLE_RECIPE_COLUMNS , corresponding to the record where "title" is "lunch".
//database info
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "cookpadDB";
//recipe table
private static final String TABLE_RECIPES_NAME ="recipes";
private static final String RECIPE_COLUMN_ID ="id";
private static final String RECIPE_COLUMN_TITLE ="title";
private static final String RECIPE_COLUMN_DESCRIPTION ="description";
private static final String RECIPE_COLUMN_FOOD_IMAGE = "food_image";
private static final String RECIPE_COLUMN_TYPE="type";
private static final String RECIPE_COLUMN_LIKE="like";
private static final String[] TABLE_RECIPE_COLUMNS = {RECIPE_COLUMN_ID, RECIPE_COLUMN_TITLE,
RECIPE_COLUMN_DESCRIPTION, RECIPE_COLUMN_FOOD_IMAGE,RECIPE_COLUMN_TYPE,RECIPE_COLUMN_LIKE};
Related
I need to update the column,i am able to add properly but I am not able to update.
Here is my code for updating.
public void setStatus(boolean status,int id,Context c){
InitilizeSqlite(c);
SQLiteDatabase db=userHelper.getReadableDatabase();
Cursor cursor = db.query(ReminderDetails.ReminderItem.Table_Name,new String[]{
ReminderDetails.ReminderItem.Id,
ReminderDetails.ReminderItem.Date,
ReminderDetails.ReminderItem.Time,
ReminderDetails.ReminderItem.Medicine,
ReminderDetails.ReminderItem.Reminder_Status}
,ReminderDetails.ReminderItem.Id+ "=?",
new String[] {String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
int getId=Integer.parseInt(cursor.getString(0));
String date=cursor.getString(1);
String time=cursor.getString(2);
String medicine=cursor.getString(3);
getstatus=Boolean.parseBoolean(cursor.getString(4));
SQLiteDatabase dbUpdate=userHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ReminderDetails.ReminderItem.Id,getId);
values.put(ReminderDetails.ReminderItem.Date,date);
values.put(ReminderDetails.ReminderItem.Time,time);
values.put(ReminderDetails.ReminderItem.Medicine,medicine);
values.put(ReminderDetails.ReminderItem.Reminder_Status,status);
dbUpdate.update(ReminderDetails.ReminderItem.Table_Name,values,ReminderDetails.ReminderItem.Id+ "=?",new String[]{String.valueOf(id)});
}
//Here is my column Detail
public class ReminderDetails {
public static abstract class ReminderItem{
public static final String Id="item_id";
public static final String Time="time";
public static final String Date="date";
public static final String Medicine="medicine";
public static final String Table_Name="reminder_details";
public static final String Reminder_Status="reminder_status";
}
}
Can any one help to me address what is the issue why am not able to update reminder status ?
I found the solution actually values.put(ReminderDetails.ReminderItem.Reminder_Status,status) here I was passing status in boolean but in my table I saved string so I just change to values.put(ReminderDetails.ReminderItem.Reminder_Status,"true") then its working fine. Thank you all who give time for this question.
I have a Content Provider that can create one type of database. My database contains 5 columns and one table, and with my program, I want to be able to create a new table with the same columns as my first table. How can I change my Content Provider to do this ? I need to mach some uri, but how can I do this will I am in my program ?
My columns are :
_id, THEME, QUESTION, REPONSE, DIFFICULTE
Here is my Content Provider :
public class CardContentProvider extends ContentProvider {
private StockCard stock;
public static String authority = "com.example.jean.cartememoire.CardContentProvider";
private static String path ="Cartes_table";
public static final String _ID = "_id";
public static final String THEME = "THEME";
public static final String QUESTION = "QUESTION";
public static final String REPONSE = "REPONSE";
public static final String DIFFICULTE = "DIFFICULTE"; //# = un chiffre
public static final String STOCK_TABLE = "Cartes_table";
private static final int ID_STOCK_TABLE = 1;
private static final int ID_THEME = 2;
private static final int ID_QUESTION = 3;
private static final int ID_REPONSE = 4;
private static final int ID_DIFFICULTE = 5;
private static final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
matcher.addURI(authority, STOCK_TABLE, ID_STOCK_TABLE);
matcher.addURI(authority, STOCK_TABLE+"/*", ID_STOCK_TABLE);
}
#Override
public boolean onCreate() {
stock = StockCard.getInstance(getContext());
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = stock.getReadableDatabase();
int code = matcher.match(uri);
long id;
Cursor cursor;
switch (code)
{
case ID_STOCK_TABLE:
cursor = db.query(STOCK_TABLE, projection, selection,
selectionArgs, null, null, sortOrder);
break;
default:
Log.d("Uri provider =", uri.toString());
throw new UnsupportedOperationException("Pas encore implémenté");
}
return cursor;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = stock.getWritableDatabase();
int code = matcher.match(uri);
long id;
Uri.Builder builder = new Uri.Builder();
switch(code)
{
case ID_STOCK_TABLE:
System.out.println(values.toString());
id = db.insert(STOCK_TABLE, null, values);
builder.appendPath(STOCK_TABLE);
break;
default:
throw new UnsupportedOperationException("Pas encore implémenté");
}
builder.authority(authority);
builder = ContentUris.appendId(builder, id);
return builder.build();
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = stock.getWritableDatabase();
int code = matcher.match(uri);
int i;
switch(code)
{
case ID_STOCK_TABLE:
long id = ContentUris.parseId(uri);
i = db.delete(STOCK_TABLE, "_id=" + id, null);
break;
default:
throw new UnsupportedOperationException("Pas encore implémenté");
}
return 0;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
Thank you guys !
EDIT : I said rows instead of columns...
This question already has answers here:
Using String[] selectionArgs in SQLiteDatabase.query()
(2 answers)
Closed 6 years ago.
I am new to SQLite in Android. I have successfully created the database with this schema:
public final class BookDbSchema {
private BookDbSchema() {
}
public static final class BookEntry implements BaseColumns{
public static final String NAME = "bookItems";
public static final String ID = "id";
public static final String URL = "url";
public static final String TITLE = "title";
}
}
The problem I am having is searching the database for a particular string.
I want to search the id column if 1993 exists. Please how do I do that?
I have read the documentation but I don’t know where to input "1993" for in the query method.
i belive you are looking for this
Context context;
BookDbSchema mDbHelper;
public BookDbSchema (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
...
ArrayList<String> urls = new ArrayList<>();
ArrayList<String> titles = new ArrayList<>();
ArrayList<String> ids= new ArrayList<>();
mDbHelper = new BookDbSchema(context);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
FeedEntry.ID,
FeedEntry.URL,
FeedEntry.TITLE
};
String selection = FeedEntry.ID + " LIKE ? "; //WHERE
String[] selectionArgs = {"1993"}; //VALUE
Cursor c = db.query(
FeedEntry.NAME, // Your Table Name
projection,
selection,
selectionArgs,
null,
null,
null
);
if(c.getCount() != 0) {
c.moveToFirst();
for(int i = 0; i<c.getCount(); i++) {
urls.add(c.getString(c.getColumnIndex(FeedEntry.URL)));
titles.add(c.getString(c.getColumnIndex(FeedEntry.TITLE)));
ids.add(c.getString(c.getColumnIndex(FeedEntry.ID)));
c.moveToNext();
}
String firstUrl = urls.get(0); //Returns the first url found
String firstID = ids.get(0); //Returns the first id found
int urlSize = urls.size(); // returns the count of urls found
}else{
//Nothing found
}
c.close();
db.close();
You can use the below method :
Cursor query (String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit)
query(NAME, new String[]{ID, URL, TITLE}, ID + "=?", new String[]{"1993"}, null, null, null, null);
When I send a sms in Android mobile phone, I can select multiple contact (Please see A.png ), and the sms will be as one record.
Can the sms be query using "content://sms/" ? will the field "address" return multiple phone numbers?
Thanks!
A.png
public static List<String> ListDeleteOld(Context myContext, SMSRange mSMSRange, int beforeDays ) {
List<String> mListSmsID=new ArrayList<String>();
Uri uri=PublicParFun.GetUriBySMSRange(mSMSRange);
Date beforeDate=getCurrentBefore(beforeDays);
String[] projection = new String[] {"_id","address"};
Cursor cur = myContext.getContentResolver().query(uri, projection, "date<=" + beforeDate.getTime(), null, "date desc");
while(cur.moveToNext()){
String s=cur.getString(cur.getColumnIndex("address"));
}
cur.close();
return mListSmsID;
}
public static Uri GetUriBySMSRange(SMSRange mSMSRange){
Uri uri=null;
final String SMS_URI_ALL = "content://sms/";
final String SMS_URI_INBOX = "content://sms/inbox";
final String SMS_URI_SEND = "content://sms/sent";
final String SMS_URI_OUTBOX = "content://sms/outbox";
final String SMS_URI_DRAFT = "content://sms/draft";
switch (mSMSRange){
case All:
uri = Uri.parse(SMS_URI_ALL);
break;
case Inbox:
uri = Uri.parse(SMS_URI_INBOX);
break;
case Sentbox:
uri = Uri.parse(SMS_URI_SEND);
break;
case Outbox:
uri = Uri.parse(SMS_URI_OUTBOX);
break;
case Draft:
uri = Uri.parse(SMS_URI_DRAFT);
break;
}
return uri;
}
set variables for example:
private static final Uri SMS_SENT_URI = Uri.parse("content://sms/sent");
private static final String SMS_ORDER = "date DESC";
private static final String ADDRESS_COLUMN_NAME = "address";
private static final String DATE_COLUMN_NAME = "date";
private static final String BODY_COLUMN_NAME = "body";
private static final String TYPE_COLUMN_NAME = "type";
private static final String ID_COLUMN_NAME = "_id";
private static final String SMS_PREFERENCES = "SMS_PREFERENCES";
You have to crete SmsObject.
Then just loop trough Cursor.
The whole code: (call checkNewOutgoingSms(context))
private void checkNewOutgoingSms(Context context) {
Cursor smsCursor = getSmsCursor(context);
List<Sms> smsList = getLastSmsList(smsCursor,context);
if (smsList != null && smsList.size() > 0) {
ProtectorWSODao mwtProtectorDao = new ProtectorWSODao();
for (Sms sms : smsList) {
//
//
//read sms content
//
//
}
Manager.getInstance(context).sendDataToServer(mwtProtectorDao);
}
smsCursor.close();
}
public static Cursor getSmsCursor(Context context) {
return context.getContentResolver().query(SMS_SENT_URI, null, null, null, SMS_ORDER);
}
private List<Sms> getLastSmsList(Cursor smsCursor, Context context) {
List<Sms> smsList = new ArrayList<Sms>();
final int lastSmsIntercepted = smsStorage.getLastSmsIntercepted();
boolean update = false;
if (smsCursor != null) {
if (smsCursor.moveToFirst()) {
do {
Sms smsParsed = parseSms(smsCursor, context);
smsList.add(smsParsed);
} while (smsCursor.moveToNext());
}
}
return smsList;
}
public static Sms parseSms(Cursor cursor, Context context) {
String number = cursor.getString(cursor.getColumnIndex(ADDRESS_COLUMN_NAME));
String date = cursor.getString(cursor.getColumnIndex(DATE_COLUMN_NAME));
String content = cursor.getString(cursor.getColumnIndex(BODY_COLUMN_NAME));
int smsId = cursor.getInt(cursor.getColumnIndex(ID_COLUMN_NAME));
return new Sms(Sms.SEND, smsId, number, date, content);
}
I have a SQLite Database with 45 different entries, each with:
public static final String TABLE = "Table";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_HOUR = "hour";
public static final String COLUMN_WEEK = "week";
public static final String COLUMN_DAY = "day";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_COLOUR = "colour";
public static final String COLUMN_ROOM = "room";
now I want to read out all. I Do this with following:
public Cursor fetchAllSubject(){
Cursor mCursor = database.query(true, TABLE, new String[] {
COLUMN_ID, COLUMN_HOUR, COLUMN_WEEK, COLUMN_DAY, COLUMN_NAME, COLUMN_DESCRIPTION, COLUMN_COLOUR, COLUMN_ROOM},null
, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
In a other class I have this code to read all out:
dao = new DAO(this);
Cursor subjectList = dao.fetchAllSubject();
Now I want to have for each entry an array with ID, Hour, week, ... but I have no idea how to do that.
My first try was following:
ArrayList<String> mo1h = new ArrayList<String>();
subjectList.moveToFirst();
while(!subjectList.isAfterLast()) {
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ID)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_HOUR)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_WEEK)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DAY)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_NAME)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DESCRIPTION)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_COLOUR)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ROOM)));
subjectList.moveToNext();
}
But everything is in mo1h, and I dont know how to devide it.
The best would be to have a String[] for each. Has anybody an Idea?
Thanks!
You can create on Bean class and then create one ArrayList (Collection class)
public class Bean
{
public Bean();
String id, hour, week, day, name, description, color, room;
}
now create list of Bean
ArrayList<Bean> mo1h = new ArrayList<Bean>();
subjectList.moveToFirst();
while(!subjectList.isAfterLast()) {
Bean b = new Bean();
b.id = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ID));
b.hour =subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_HOUR));
...
...
// all your column
mo1h.add(b);
}
Why not continue with your strategy, but instead use an ArrayList of String[]:
ArrayList<String[]> mo1h = new ArrayList<String[]>();
subjectList.moveToFirst();
while(!subjectList.isAfterLast()) {
String[] toUse = new String[8];
toUse[0] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ID));
toUse[1] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_HOUR));
toUse[2] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_WEEK));
toUse[3] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DAY));
toUse[4] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_NAME));
toUse[5] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DESCRIPTION));
toUse[6] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_COLOUR));
toUse[7] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ROOM));
mo1h.add(toUse);
subjectList.moveToNext();
}