Android Sqllite not updating the column at all - android

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.

Related

SQLiteDatabase query method

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

How to get assign values to an arraylist item inside a cursor iterator

I am trying to assign one variable to an ArrayList item inside a cursor but it always returns me last value. Here is the code below.
Getting value from DB
public ArrayList<Bean> getPendingData(String s) {
SQLiteDatabase db = getWritableDatabase();
String[] columns = {name};
String[] selectionArgs = {s};
Cursor cursor = db.query(TABLE_NAME, columns, " pending= ? ", selectionArgs, null, null, null, null);
cursor.moveToFirst();
ArrayList<Bean> pending = new ArrayList<>();
String index0 = null;
Bean bean;
bean = new Bean();
while(!cursor.isAfterLast()) {
index0 = cursor.getString(cursor.getColumnIndex(name));
bean.setQuestion(index0);
pending.add(bean);
cursor.moveToNext();
}
cursor.close();
return pending;
}
Bean.java
public class Bean {
public static int id; // ans
public static String score;
public static String logo;
public static String image;
public static String getQuestion() {
return question;
}
public static void setQuestion(String question) {
Bean.question = question;
}
public static String question;
public static String description;
public static String option_three;
public static String OptionFour;
}
You should initialize your bean inside the while block:
while(!cursor.isAfterLast()) {
Bean bean = new Bean();
index0 = cursor.getString(cursor.getColumnIndex(name));
bean.setQuestion(index0);
pending.add(bean);
cursor.moveToNext();
}
The reason is that Java uses objects by reference, so you're always adding the same object to the array "pending", but in following iterations you're changing the value of this object, so finally you have the value of the last iteration.
cursor.isAfterLast() returns true when cursor is at last row position. Adding a ! (not) means perform till it is not at the end of cursor.
so while(!cursor.isAfterLast()){} means while loop will traverse till last record of cursor.
Use this method to fetch all rows returning from cursor.
if (cursor != null) {
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
homeClassesArrayList = new ArrayList<>();
do {
// fetching data
} while (cursor.moveToNext());
}
}
}

How to search for a string in an SQLite database [duplicate]

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

Failing to query the max number in database

I am trying to find the max number in a column of one of the tables in my database.
I thought I had this one sorted (I posted similar question previously), however after some testing I have realised my code isn't working as I thought.
The database consists of a table with the following columns:
_id, inspection_link, area_number, area_reference
I have created the following code in my database helper class:
public static final String AREAS_TABLE = "areas";
public static final String AREA_ID = "_id";
public static final String AREA_NUMBER = "area_number";
public static final String AREA_REF = "area_reference";
public static final String AREA_LINK = "area_link";
public static final String INSPECTION_LINK = "inspection_link";
public Cursor selectMaxAreaNumber (long inspectionId) {
String inspectionIdString = String.valueOf(inspectionId);
String[] tableColumns = new String[] {
AREA_NUMBER,
"(SELECT max(" + AREA_NUMBER + ") FROM " + AREAS_TABLE + ") AS max"
};
String whereClause = INSPECTION_LINK + " = ?";
String[] whereArgs = new String[] {
inspectionIdString
};
Cursor c = rmDb.query(AREAS_TABLE, tableColumns, whereClause, whereArgs,
null, null, null);
if (c != null) {
c.moveToFirst();
}
c.close();
return c;
}
Then in the activity where I want to query the database I have written the following:
public class AreaEdit extends Activity {
private EditText AreaNumber;
private EditText AreaReference;
private Button saveButton;
private Button cancelButton;
protected boolean changesMade;
private AlertDialog unsavedChangesDialog;
private RMDbAdapter rmDbHelper;
private long inspectionId;
private long areaId;
private int nextAreaNumber = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rmDbHelper = new RMDbAdapter(this);
rmDbHelper.open();
Intent i = getIntent();
inspectionId = i.getLongExtra("Intent_InspectionID", -1);
areaId = i.getLongExtra("Intent_AreaID", -1);
if (areaId == -1) {
Cursor c = rmDbHelper.selectMaxAreaNumber(inspectionId);
startManagingCursor(c);
c.moveToFirst();
nextAreaNumber = c.getInt(c.getColumnIndex("max")) + 1;
}
setContentView(R.layout.edit_area);
setUpViews();
populateFields();
setTextChangedListeners();
}
private void setUpViews() {
AreaNumber =(EditText)findViewById(R.id.area_number);
AreaReference =(EditText)findViewById(R.id.area_reference);
saveButton = (Button)findViewById(R.id.area_save_button);
cancelButton = (Button)findViewById(R.id.area_cancel_button);
}
private void populateFields() {
if (areaId > 0) {
Cursor c = rmDbHelper.fetchArea(areaId);
startManagingCursor(c);
c.moveToFirst();
AreaNumber.setText(c.getString(
c.getColumnIndexOrThrow(RMDbAdapter.AREA_NUMBER)));
AreaReference.setText(c.getString(
c.getColumnIndexOrThrow(RMDbAdapter.AREA_REF)));
c.close();
}
else {
AreaNumber.setText(String.valueOf(nextAreaNumber));
}
}
However, when it returns the wrong number - it seems to pick up the maximum number from the whole table which includes data from other inspections.
I guess this may be down to the conversion between Strings and Longs etc maybe, but I have a brickwall with this?
Any help much appreciated.
You can simply try below:
String sql = "SELECT MAX(ColumnNameHere) AS MaxValue FROM myTable WHERE AnotherColumn = 'SomValue'";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
c.getInt(c.getColumnIndex("MaxValue"));
Detailed solution to this question found here:
Solution to this detailed in the following post: SELECT statement not returning MAX number
Basically, it was an issue with the query as thought and how I used the cursor.

Get String Array from Cursor

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

Categories

Resources