Android SQLite cannot bind argument - android-sqlite

I'm trying to do a simple query of my database, where a unique Identification number is stored for a PendingIntent. To allow me to cancel a notification set by AlarmManager if needed.
The insertion of a value works fine, but I am unable to overcome the error:
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
Database structure:
public class DBAdapter {
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID = "_id";
public static final String TASK = "task";
public static final String NOTIFICATION = "notification";
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_NOTIFICATION = 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, TASK, NOTIFICATION};
// DB info: it's name, and the table.
public static final String DATABASE_NAME = "TaskDB";
public static final String DATABASE_TABLE = "CurrentTasks";
public static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key, "
+ TASK + " text not null, "
+ NOTIFICATION + " integer"
+ ");";
Now I have created a method to extract the notification ID from the database as needed, using the following code:
public int getNotifID(long notifID){
String[] x = {ALL_KEYS[2]};
String[]args = new String[]{NOTIFICATION};
String where = NOTIFICATION + "=" + notifID;
int y = 0;
//String select = "SELECT "+NOTIFICATION+" FROM "+DATABASE_TABLE+" WHERE "+notifID+"="+NOTIFICATION;
//Cursor c = db.rawQuery(select,new String[]{});
Cursor c = db.query(true,DATABASE_TABLE,x,Long.toString(notifID),args,null,null,null,null,null);
if (c!= null && c.moveToFirst()){
y = c.getInt(COL_NOTIFICATION);
}
return y;
}
As you can see I have attempted to do this both with a rawQuery and a regular query, but with no success.

Rewrite your raw query to:
String select = "SELECT "+NOTIFICATION+" FROM "+DATABASE_TABLE+" WHERE "+NOTIFICATION+"=?";
Cursor c = db.rawQuery(select,new String[]{""+notifId});
if(c!=null && c.getCount()>0) {
c.moveToFirst();
}
c.close();

Related

Replacement for "GROUP BY" in ContentResolver query in Android Q ( Android 10, API 29 changes)

I'm upgrading some legacy to target Android Q, and of course this code stop working:
String[] PROJECTION_BUCKET = {MediaStore.Images.ImageColumns.BUCKET_ID,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.DATA,
"COUNT(" + MediaStore.Images.ImageColumns._ID + ") AS COUNT",
MediaStore.Files.FileColumns.MEDIA_TYPE,
MediaStore.MediaColumns._ID};
String BUCKET_GROUP_BY = " 1) and " + BUCKET_WHERE.toString() + " GROUP BY 1,(2";
cur = context.getContentResolver().query(images, PROJECTION_BUCKET,
BUCKET_GROUP_BY, null, BUCKET_ORDER_BY);
android.database.sqlite.SQLiteException: near "GROUP": syntax error (code 1 SQLITE_ERROR[1])
Here it supposed to obtain list of images with album name, date, count of pictures - one image for each album, so we can create album picker screen without querying all pictures and loop through it to create albums.
Is it possible to group query results with contentResolver since SQL queries stoped work?
(I know that ImageColumns.DATA and "COUNT() AS COUNT" are deprecated too, but this is a question about GROUP BY)
(There is a way to query albums and separately query photo, to obtain photo uri for album cover, but i want to avoid overheads)
Unfortunately Group By is no longer supported in Android 10 and above, neither any aggregated functions such as COUNT. This is by design and there is no workaround.
The solution is what you are actually trying to avoid, which is to query, iterate, and get metrics.
To get you started you can use the next snipped, which will resolve the buckets (albums), and the amount of records in each one.
I haven't added code to resolve the thumbnails, but is easy. You must perform a query for each bucket Id from all the Album instances, and use the image from the first record.
public final class AlbumQuery
{
#NonNull
public static HashMap<String, AlbumQuery.Album> get(#NonNull final Context context)
{
final HashMap<String, AlbumQuery.Album> output = new HashMap<>();
final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
final String[] projection = {MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.BUCKET_ID};
try (final Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null, null))
{
if ((cursor != null) && (cursor.moveToFirst() == true))
{
final int columnBucketName = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
final int columnBucketId = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_ID);
do
{
final String bucketId = cursor.getString(columnBucketId);
final String bucketName = cursor.getString(columnBucketName);
if (output.containsKey(bucketId) == false)
{
final int count = AlbumQuery.getCount(context, contentUri, bucketId);
final AlbumQuery.Album album = new AlbumQuery.Album(bucketId, bucketName, count);
output.put(bucketId, album);
}
} while (cursor.moveToNext());
}
}
return output;
}
private static int getCount(#NonNull final Context context, #NonNull final Uri contentUri, #NonNull final String bucketId)
{
try (final Cursor cursor = context.getContentResolver().query(contentUri,
null, MediaStore.Images.Media.BUCKET_ID + "=?", new String[]{bucketId}, null))
{
return ((cursor == null) || (cursor.moveToFirst() == false)) ? 0 : cursor.getCount();
}
}
public static final class Album
{
#NonNull
public final String buckedId;
#NonNull
public final String bucketName;
public final int count;
Album(#NonNull final String bucketId, #NonNull final String bucketName, final int count)
{
this.buckedId = bucketId;
this.bucketName = bucketName;
this.count = count;
}
}
}
This is a more efficient(not perfect) way to do that.
I am doing it for videos, but doing so is the same for images to. just change MediaStore.Video.Media.X to MediaStore.Images.Media.X
public class QUtils {
/*created by Nasib June 6, 2020*/
#RequiresApi(api = Build.VERSION_CODES.Q)
public static ArrayList<FolderHolder> loadListOfFolders(Context context) {
ArrayList<FolderHolder> allFolders = new ArrayList<>();//list that we need
HashMap<Long, String> folders = new HashMap<>(); //hashmap to track(no duplicates) folders by using their ids
String[] projection = {MediaStore.Video.Media._ID,
MediaStore.Video.Media.BUCKET_ID,
MediaStore.Video.Media.BUCKET_DISPLAY_NAME,
MediaStore.Video.Media.DATE_ADDED};
ContentResolver CR = context.getContentResolver();
Uri root = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
Cursor c = CR.query(root, projection, null, null, MediaStore.Video.Media.DATE_ADDED + " desc");
if (c != null && c.moveToFirst()) {
int folderIdIndex = c.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_ID);
int folderNameIndex = c.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
int thumbIdIndex = c.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
int dateAddedIndex = c.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_ADDED);
do {
Long folderId = c.getLong(folderIdIndex);
if (folders.containsKey(folderId) == false) { //proceed only if the folder data has not been inserted already :)
long thumbId = c.getLong(thumbIdIndex);
String folderName = c.getString(folderNameIndex);
String dateAdded = c.getString(dateAddedIndex);
Uri thumbPath = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, thumbId);
folders.put(folderId, folderName);
allFolders.add(new FolderHolder(String.valueOf(thumbPath), folderName, dateAdded));
}
} while (c.moveToNext());
c.close(); //close cursor
folders.clear(); //clear the hashmap becuase it's no more useful
}
return allFolders;
}
}
FolderHolder model class
public class FolderHolder {
private String folderName;
public long dateAdded;
private String thumbnailPath;
public long folderId;
public void setPath(String thumbnailPath) {
this.thumbnailPath = thumbnailPath;
}
public String getthumbnailPath() {
return thumbnailPath;
}
public FolderHolder(long folderId, String thumbnailPath, String folderName, long dateAdded) {
this.folderId = folderId;
this.folderName = folderName;
this.thumbnailPath = thumbnailPath;
this.dateAdded = dateAdded;
}
public String getFolderName() {
return folderName;
}
}
GROUP_BY supporting in case of using Bundle:
val bundle = Bundle().apply {
putString(
ContentResolver.QUERY_ARG_SQL_SORT_ORDER,
"${MediaStore.MediaColumns.DATE_MODIFIED} DESC"
)
putString(
ContentResolver.QUERY_ARG_SQL_GROUP_BY,
MediaStore.Images.ImageColumns.BUCKET_ID
)
}
contentResolver.query(
uri,
arrayOf(
MediaStore.Images.ImageColumns.BUCKET_ID,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.DATA
),
bundle,
null
)

Database update without data loss. FATAL EXCEPTION: ModernAsyncTask #1

I need to implement an update of the database lying in the assets. User data, namely, in the "favorite" record or not, should be saved.
I already asked a question and they helped me -https://stackoverflow.com/a/53827525/10261947
Everything worked in a test application. But when I transferred the code (exactly the same) to the real application, an error occurs - E/AndroidRuntime: FATAL EXCEPTION: ModernAsyncTask #1
Process: rodionova.lyubov.brodsky, PID: 4196
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.support.v4.content.ModernAsyncTask$3.done(ModernAsyncTask.java:161)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:784)
Caused by: java.lang.IllegalArgumentException: the bind value at index 4 is null
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:169)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:205)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1397)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1239)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1110)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1278)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.insertCorePoem(PoemsDbHelper.java:121)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.getNewPoems(PoemsDbHelper.java:90)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.onUpgrade(PoemsDbHelper.java:41)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:197)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:254)
at rodionova.lyubov.brodsky.db.PoemsProvider.query(PoemsProvider.java:45)
at android.content.ContentProvider.query(ContentProvider.java:1057)
If you do not perform the update, the application is working properly, so I will post only the code DbHelper
public class PoemsDbHelper extends SQLiteAssetHelper {
public static final String DB_NAME = "brodsky.db";
public static final int DBVERSION = 3;
public static final String TBLNAME = "poems_table";
public static final String COL_ID = "id";
public static final String COL_TITLE = "title";
public static final String COl_POEM = "poem";
public static final String COL_SUBJECT = "subject";
public static final String COL_YEARS = "years";
public static final String COL_FAVOURITE = "favorite";
Context mContext;
public PoemsDbHelper(Context context) {
super(context, DB_NAME, null, DBVERSION);
mContext = context;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion)
getNewPoems(mContext, db);
}
private void getNewPoems(Context context, SQLiteDatabase db) {
InputStream is;
OutputStream os;
final String tempNewDbName = "temp_brodsky.db";
int buffersize = 4096;
byte[] buffer = new byte[buffersize];
String newDBPath = mContext.getDatabasePath(tempNewDbName).getPath();
File newDBFile = new File(newDBPath);
if (newDBFile.exists()) {
newDBFile.delete();
}
File newDBFileDirectory = newDBFile.getParentFile();
if (!newDBFileDirectory.exists()) {
newDBFileDirectory.mkdirs();
}
try {
is = context.getAssets().open("databases/" + DB_NAME);
os = new FileOutputStream(newDBFile);
int bytes_read;
while ((bytes_read = is.read(buffer,0,buffersize)) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Ouch updated database not copied - processing stopped - see stack-trace above.");
}
long id = maxid(db) + 1;
SQLiteDatabase newdb = SQLiteDatabase.openDatabase(newDBFile.getPath(),null,SQLiteDatabase.OPEN_READONLY);
Cursor csr = newdb.query(TBLNAME,null,null,null,null,null,null);
long insert_result;
db.beginTransaction();
while (csr.moveToNext()) {
insert_result = insertCorePoem(
db,
id,
csr.getString(csr.getColumnIndex(COL_TITLE)),
csr.getString(csr.getColumnIndex(COl_POEM)),
csr.getString(csr.getColumnIndex(COL_SUBJECT)),
csr.getString(csr.getColumnIndex(COL_YEARS)),
csr.getString(csr.getColumnIndex(COL_FAVOURITE))
);
if (insert_result > 0) {
id++;
}
}
db.setTransactionSuccessful();
db.endTransaction();
csr.close();
newDBFile.delete();
}
public long insertCorePoem(SQLiteDatabase db, long id, String title, String poem, String subject, String years, String favourite) {
String whereclause = COL_TITLE + "=? AND " + COl_POEM + "=? AND " + COL_SUBJECT + "=? AND " + COL_YEARS + "=?";
String[] whereargs = new String[]{
title,
poem,
subject,
years
};
Cursor csr = db.query(TBLNAME,null,whereclause,whereargs,null,null,null);
boolean rowexists = (csr.getCount() > 0);
csr.close();
if (rowexists) {
Log.d("INSERTCOREPOEM","Skipping insert of row");
return -2;
}
ContentValues cv = new ContentValues();
cv.put(COL_ID,id);
cv.put(COL_TITLE,title);
cv.put(COl_POEM,poem);
cv.put(COL_SUBJECT,subject);
cv.put(COL_YEARS,years);
cv.put(COL_FAVOURITE,favourite);
Log.d("INSERTCOREPOEM","Inserting new column with id " + String.valueOf(id));
return db.insert(TBLNAME, null, cv);
}
private long maxid(SQLiteDatabase db) {
long rv = 0;
String extractcolumn = "maxid";
String[] col = new String[]{"max(" + COL_ID + ") AS " + extractcolumn};
Cursor csr = db.query(TBLNAME,col,null,null,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(extractcolumn));
}
csr.close();
return rv;
}
}
I do not understand what is wrong. Identical code works great friend application. I would be grateful for the help.
Your issue is that you likely have a value of null in the years column of a row or rows in the updated database that data is being copied from.
Although you could change the code to handle (skip insertion or use provide a year value) the end result may not be desired. So the most likely fix would be to amend the database to have valid/useful year values.

Show Page number range of subreports in Master Report

I have a master report with 4 subreports in its details section. I want to display the page number range (for example 1- 2) of all the subreports in the Master report title section. I tried using subreport return value but it works only when I have 1 subreport not if there are more than 1 subreport
Here is the solution
Step1 : Create variables of any type inside each of the SubReport and the set the calculation, Increment Type and Reset Type to None. No need to specify the Expression as well Initial Value Expression
Step 2 : Create variables of String type inside the Master Report to hold the value of page number (eg. 1-2) and set the Calculation as System.
Step 3 : Add the variables created in Step2 on the Master Report Title section and set the evaluation time as Report.
Step 4 : Create scriptlet and set the page number in that
public class PageScriptlet extends JRDefaultScriptlet {
private static int mgmtReportPages;
private static int balanceSheetReportPages;
private static int incomeStmtReportPages;
private static int addInfoReportPages;
private static final String MGMT_REPORT_PAGENUM = "mgmtReportPageNum";
private static final String INCOME_STMT_PAGENUM = "incomeStmtPageNum";
private static final String BALANCE_SHEET_PAGENUM = "balanceSheetPageNum";
private static final String ADDINFO_PAGENUM = "addInfoPageNum";
private static final String MGMT_REPORT_INDEX = "mgmtReportIndex";
private static final String INCOMESTMT_INDEX = "incomeStmtIndex";
private static final String BALANCESHEET_INDEX = "balanceSheetIndex";
private static final String NOTES_INDEX = "notesIndex";
private static final String SIGNATURE_INDEX = "signatureIndex";
private static Integer firstPage = 2;
public PageScriptlet() {
super ();
}
#Override
public void afterPageInit() throws JRScriptletException{
Map<String, JRFillVariable> variablesMap = this.variablesMap;
if(variablesMap.containsKey(MGMT_REPORT_INDEX)){
Integer lastPage = mgmtReportPages+1;
String index = null;
if(firstPage == lastPage){
index = String.valueOf(firstPage);
}else{
index = String.valueOf(firstPage)+"-"+String.valueOf(lastPage);
}
this.setVariableValue(MGMT_REPORT_INDEX, index);
}
if(variablesMap.containsKey(INCOMESTMT_INDEX)){
Integer firstPage = mgmtReportPages + 2;
Integer lastPage = incomeStmtReportPages;
String index = null;
if(firstPage == lastPage){
index = String.valueOf(firstPage);
}else{
index = String.valueOf(firstPage)+"-"+String.valueOf(lastPage);
}
this.setVariableValue(INCOMESTMT_INDEX, index);
}
if(variablesMap.containsKey(BALANCESHEET_INDEX)){
Integer firstPage = incomeStmtReportPages+1;
Integer lastPage = balanceSheetReportPages;
String index = null;
if(firstPage == lastPage){
index = String.valueOf(firstPage);
}else{
index = String.valueOf(firstPage)+"-"+String.valueOf(lastPage);
}
this.setVariableValue(BALANCESHEET_INDEX, index);
}
if(variablesMap.containsKey(NOTES_INDEX)){
Integer firstPage = balanceSheetReportPages + 1;
Integer lastPage = addInfoReportPages;
String index = null;
if(firstPage == lastPage){
index = String.valueOf(firstPage);
}else{
index = String.valueOf(firstPage)+"-"+String.valueOf(lastPage);
}
this.setVariableValue(NOTES_INDEX, index);
}
if(variablesMap.containsKey(SIGNATURE_INDEX)){
Integer lastPage = addInfoReportPages;
String index = String.valueOf(lastPage);
this.setVariableValue(SIGNATURE_INDEX, index);
}
}
#Override
public void beforePageInit() throws JRScriptletException{
Map<String, JRFillVariable> variablesMap = this.variablesMap;
Integer pageNumber = (Integer)this.getVariableValue("PAGE_NUMBER");
if(variablesMap.containsKey(MGMT_REPORT_PAGENUM)){
mgmtReportPages = pageNumber == null ? 1 : pageNumber + 1;
}
if(variablesMap.containsKey(INCOME_STMT_PAGENUM)){
incomeStmtReportPages = pageNumber == null ? mgmtReportPages + 2 : incomeStmtReportPages + 1;
}
if(variablesMap.containsKey(BALANCE_SHEET_PAGENUM)){
balanceSheetReportPages = pageNumber == null ? incomeStmtReportPages + 1 : balanceSheetReportPages + 1;
}
if(variablesMap.containsKey(ADDINFO_PAGENUM)){
addInfoReportPages = pageNumber == null ? balanceSheetReportPages+1 : addInfoReportPages + 1;
}
}
}

SQLite database is not updating within an application

I am developing an application. When I modify my data, the previous data is displayed and not the updated data. This is the ModifyActivity.java file:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ModifyCountryActivity extends Activity implements OnClickListener {
private EditText titleText, dateText, timeText;
private Button updateBtn, deleteBtn;
public Calendars calendars;
private DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Modify Record");
setContentView(R.layout.activity_modify_record);
dbHelper = new DatabaseHelper(this);
calendars = new Calendars();
titleText = (EditText) findViewById(R.id.title_edittext_modify);
timeText = (EditText) findViewById(R.id.time_edittext_modify);
dateText = (EditText) findViewById(R.id.date_edittext_modify);
updateBtn = (Button) findViewById(R.id.btn_update);
deleteBtn = (Button) findViewById(R.id.btn_delete);
Intent intent = getIntent();
String title = intent.getStringExtra("title");
String time = intent.getStringExtra("time");
String date = intent.getStringExtra("date");
titleText.setText(title);
timeText.setText(time);
dateText.setText(date);
updateBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_update:
titleText.setText(titleText.getText().toString() + " ");
timeText.setText(dateText.getText().toString() + " ");
dateText.setText(timeText.getText().toString() + " ");
calendars.set_remindertitle(titleText.getText().toString() + " ");
calendars.set_reminderdate(dateText.getText().toString() + " ");
calendars.set_remindertime(timeText.getText().toString() + " ");
dbHelper.update(calendars);
this.returnHome();
break;
case R.id.btn_delete:
dbHelper.delete(calendars);
this.returnHome();
break;
}
}
public void returnHome() {
Intent home_intent = new Intent(getApplicationContext(), CountryListActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
}
}
The database doesn't update. It shows the previous data again. This is the database class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "calendar.db";
public static final String TABLE_REMINDER = "reminder";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_REMINDER_TITLE = "_remindertitle";
public static final String COLUMN_REMINDER_DESCRIPTION = "_reminderdescription";
public static final String COLUMN_REMINDER_DATE = "_reminderdate";
public static final String COLUMN_REMINDER_TIME = "_remindertime";
public static final String COLUMN_REMINDER_REPEAT = "_reminderrepeat";
public static final String COLUMN_REMINDER_SNOOZE = "_remindersnooze";
SQLiteDatabase database;
// Database Information
Class<? extends DatabaseHelper> context = getClass();
DatabaseHelper dbHelper;
// Creating table query
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_REMINDER + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_REMINDER_DATE + " TEXT, " + COLUMN_REMINDER_TIME + " TEXT, " + COLUMN_REMINDER_TITLE + " TEXT, "
+ COLUMN_REMINDER_DESCRIPTION + " TEXT, " + COLUMN_REMINDER_REPEAT + " TEXT, " + COLUMN_REMINDER_SNOOZE + " TEXT " + ");";
Log.i("Query", query);
db.execSQL(query);
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDER);
onCreate(db);
}
public ArrayList<Calendars> databaseToArrayList() {
ArrayList<Calendars> arrayList = new ArrayList();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_REMINDER;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("_reminderdate")) != null) {
Calendars calendars = new Calendars();
calendars.set_reminderdate(c.getString(c.getColumnIndex(COLUMN_REMINDER_DATE)));
calendars.set_remindertime(c.getString(c.getColumnIndex(COLUMN_REMINDER_TIME)));
calendars.set_remindertitle(c.getString(c.getColumnIndex(COLUMN_REMINDER_TITLE)));
calendars.set_reminderdescription(c.getString(c.getColumnIndex(COLUMN_REMINDER_DESCRIPTION)));
calendars.set_reminderrepeat(c.getString(c.getColumnIndex(COLUMN_REMINDER_REPEAT)));
calendars.set_remindersnooze(c.getString(c.getColumnIndex(COLUMN_REMINDER_SNOOZE)));
arrayList.add(calendars);
}
c.moveToNext();
}
c.close();
db.close();
return arrayList;
}
public void remove(String id) {
String string = String.valueOf(id);
SQLiteDatabase database = getReadableDatabase();
database.execSQL("DELETE FROM " + TABLE_REMINDER + " WHERE _id = '" + string + "'");
}
public void addReminder(Calendars calendars) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_REMINDER_DATE, calendars.get_reminderdate());
contentValues.put(COLUMN_REMINDER_TIME, calendars.get_remindertime());
contentValues.put(COLUMN_REMINDER_TITLE, calendars.get_remindertitle());
contentValues.put(COLUMN_REMINDER_DESCRIPTION, calendars.get_reminderdescription());
contentValues.put(COLUMN_REMINDER_REPEAT, calendars.get_reminderrepeat());
contentValues.put(COLUMN_REMINDER_SNOOZE, calendars.get_remindersnooze());
SQLiteDatabase database = getReadableDatabase();
database.insert(TABLE_REMINDER, null, contentValues);
Log.i("insData", "the data has been inseted");
database.close();
}
public Cursor fetch() {
String[] columns = new String[]{COLUMN_ID, /*COLUMN_REMINDER_DATE, COLUMN_REMINDER_TIME, COLUMN_REMINDER_TITLE,*/
COLUMN_REMINDER_DESCRIPTION, COLUMN_REMINDER_REPEAT, COLUMN_REMINDER_SNOOZE};
SQLiteDatabase database = getReadableDatabase();
Cursor cursor = database.query(TABLE_REMINDER, columns, null, null, null, null, null);
if (cursor != null)
{
cursor.moveToFirst();
}
return cursor;
}
public int update(Calendars calendars) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_REMINDER_DATE, calendars.get_reminderdate());
contentValues.put(COLUMN_REMINDER_TIME, calendars.get_remindertime());
contentValues.put(COLUMN_REMINDER_TITLE, calendars.get_remindertitle());/*
contentValues.put(COLUMN_REMINDER_DESCRIPTION, calendars.get_reminderdescription());
contentValues.put(COLUMN_REMINDER_REPEAT, calendars.get_reminderrepeat());
contentValues.put(COLUMN_REMINDER_SNOOZE, calendars.get_remindersnooze());*/
SQLiteDatabase database = getReadableDatabase();
int i = database.update(TABLE_REMINDER, contentValues, COLUMN_ID + " = " + calendars.get_id(), null);
database.close();
return i;
}
public void delete(Calendars calendars) {
database = getReadableDatabase();
database.delete(TABLE_REMINDER, COLUMN_ID + "=" + calendars.get_id(), null);
}
}
I believe that the update button should be working fine. I am new to Android and don't know how to solve this problem. Any suggestions on how to solve it?
If you're update function returns an int, then in your onClick function, rather than typing:
dbHelper.update(calendars);
You need to type:
int update = dbHelper.update(calendars);
Or:
if (dbHelper.update(calendars) > 0) {
// do something here
}
I would recommend the latter of the options. See how you go.

Mongo DB grouping datatype changes

I came across an odd occurrence while using mongodb + their java driver.
When I do a grouping query the datatype for the key changes from an int to a double.
(ie. I am grouping on a key for 'hours', which is stored as an int within all the objects, but the key changes into a double type in the results I get back).
It isn't a huge issue...but it is weird that it would just arbitrarily change the datatype of a key-value pair like that. Has anyone else had this come up? is this normal behaviour?
Thanks,
p.s. Doing a regular .find() query returns correct datatype, fyi.
Edit:
Some example code:
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.QueryOperators;
public class MongoTestQueries {
private static final String TESTDBNAME = "badgerbadgerbadger";
private static final String TESTCOLNAME = "mushroom";
private static final Long TESTMAX = 50L;
private static final String KEY1 = "a";
private static final String KEY2 = "snake";
private static final String KEY3 = "plane";
/**
* This starts running it.
*
* #param args
* the arguments.
*/
public static void main(final String[] args) {
//You'll need to write your own code here for connecting to db as you see fit.
MongoConnection mc = new MongoConnection("someserver.com", TESTDBNAME);
mc.setCurCol(TESTCOLNAME);
mc.getCurCol().drop();
mc.setCurCol(TESTCOLNAME);
DBCollection col = mc.getCurCol();
populateCollection(col);
System.out.println(col.count() + " inserted into db.");
regGroupSearch(col);
}
private static void populateCollection(DBCollection col) {
for (Long l = 0L; l < TESTMAX; l++) {
col.insert(new BasicDBObject(KEY1, new Integer(l.intValue())).append(KEY2,
Math.random()).append(KEY3, (TESTMAX - l) + "a string"));
}
}
private static void regGroupSearch(final DBCollection col) {
System.out.println("Group Search:");
DBObject key = new BasicDBObject(KEY1, true).append(KEY3, true);
DBObject cond = new BasicDBObject().append(KEY1, new BasicDBObject(QueryOperators.GT, 4.0));
DBObject initial = new BasicDBObject("count", 0).append("sum", 0);
String reduce = "function(obj,prev){prev.sum+=obj." + KEY2 + ",prev.count+=1}";
String finalize = "function(obj){obj.ave = obj.sum/obj.count}";
DBObject groupResult = col.group(key, cond, initial, reduce, finalize);
printDBObject(groupResult);
System.out.println("Done.");
}
private static void printDBObject(final DBObject toPrint) {
for (String k : toPrint.keySet()) {
System.out.println(k + ": " + toPrint.get(k));
}
}
}