Insert sensor data from android studio into SQLite database every 1 second? - android-sqlite

I am developing an app using Android Studio which stores the data gathered from the phone's sensors (accelerometer and gyroscope) into SQLite database. The app is working fine and the SQLite database is receiving the inserted values.
The problem now is, it is inserting too many values to the point where it inserts values every microsecond. I have tried every sampling period (SENSOR_DELAY_NORMAL,SENSOR_DELAY_UI) but to no avail. My aim is to only insert values every 1 second to reduce the computing usage. Is it possible to control the rate of data insertion and if so could you guys show me some pointers?
accelerometer & gyroscope listeners:
//Creating the sensor manager; SENSOR_SERVICE is used to access sensors.
sM = (SensorManager) getSystemService(SENSOR_SERVICE);
//Accelerometer Sensor.
accelerometer = sM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if(accelerometer != null){
//Register sensor listener;
sM.registerListener(this, accelerometer, 100_000_000);
Log.d("TAG 1 Accelerometer ", "onCreate initializing accelerometer");
} else{
xText.setText("Accelerometer not supported");
yText.setText("Accelerometer not supported");
zText.setText("Accelerometer not supported");
}
//GYRO Sensor.
gyroscope = sM.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if(gyroscope != null){
//Register sensor listener;
sM.registerListener(this, gyroscope, 100_000_000);
Log.d("TAG 2 Gyroscope", "onCreate initializing gyroscope");
} else{
xTextGyro.setText("GYROSCOPE not supported");
yTextGyro.setText("GYROSCOPE not supported");
zTextGyro.setText("GYROSCOPE not supported");
}
onSensorChanged():
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensorType = event.sensor;
Location location = null;
if(sensorType.getType()==Sensor.TYPE_ACCELEROMETER) {
accelX = event.values[0];
accelY = event.values[1];
accelZ = event.values[2];
xText.setText("X: " + event.values[0]);
yText.setText("Y: " + event.values[1]);
zText.setText("Z: " + event.values[2]);
xText.setText("X: " + accelX);
yText.setText("Y: " + accelY);
zText.setText("Z: " + accelZ);
} else if (sensorType.getType() == Sensor.TYPE_GYROSCOPE){
xTextGyro.setText("X: " + event.values[0]);
yTextGyro.setText("Y: " + event.values[1]);
zTextGyro.setText("Z: " + event.values[2]);
gyroX = event.values[0];
gyroY = event.values[1];
gyroZ = event.values[2];
}
DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String SENSOR_TABLE = "SENSOR_TABLE";
public static final String COLUMN_ACCEL_X = "ACCEL_X";
public static final String COLUMN_ACCEL_Y = "ACCEL_Y";
public static final String COLUMN_ACCEL_Z = "ACCEL_Z";
public static final String COLUMN_GYRO_X = "GYRO_X";
public static final String COLUMN_GYRO_Y = "GYRO_Y";
public static final String COLUMN_GYRO_Z = "GYRO_Z";
public static final String COLUMN_CURRENT_SPEED = "CURRENT_SPEED";
private static DatabaseHelper mInstance;
public DatabaseHelper(Context context) {
super(context, String.valueOf(Calendar.getInstance().getTime())+".db", null, 1);
//Date currentTime = Calendar.getInstance().getTime();
// Log.d("TAG DATE", ""+ currentTime);
// super(context, "Live_Test.db", null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
public static DatabaseHelper getInstance(){
if(mInstance == null){
synchronized (DatabaseHelper.class){
if(mInstance == null){
mInstance = new DatabaseHelper(BaseApp.getApp());
}
}
}
return mInstance;
}
#Override
public void onCreate(SQLiteDatabase db) {
//String createTableStatement= "CREATE TABLE " + SENSOR_TABLE + "( " + COLUMN_ACCEL_X + " REAL, " + COLUMN_ACCEL_Y + " REAL, " + COLUMN_ACCEL_Z + " REAL, time DATETIME DEFAULT CURRENT_TIME)";
String createTableStatement= "CREATE TABLE " + SENSOR_TABLE + "( time DATETIME DEFAULT CURRENT_TIME, " + COLUMN_ACCEL_X + " REAL, " + COLUMN_ACCEL_Y + " REAL, " + COLUMN_ACCEL_Z + " REAL, " + COLUMN_GYRO_X + " REAL, " + COLUMN_GYRO_Y + " REAL, " + COLUMN_GYRO_Z + " REAL, " + COLUMN_CURRENT_SPEED + " REAL)";
db.execSQL(createTableStatement);
Log.d("TAG database :", "DATABASE CREATED");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+SENSOR_TABLE);
onCreate(db);
}
public void insertTable(float x, float y, float z ,float a, float b , float c, double speed){ //put onSensorChanged data to database
ContentValues contentvalues = new ContentValues();
contentvalues.put("ACCEL_X", x);
contentvalues.put("ACCEL_Y", y);
contentvalues.put("ACCEL_Z", z);
contentvalues.put("GYRO_X", a);
contentvalues.put("GYRO_Y", b);
contentvalues.put("GYRO_Z", c);
contentvalues.put("CURRENT_SPEED", speed);
getWritableDatabase().insert(SENSOR_TABLE, null, contentvalues);
}
}

Something like this should help:
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
long now = System.currentTimeMillis();
if(lastSensed + SAMPLING_PERIOD_MS < now) {
// do what you want to do
saveToSQLiteDb();
lastSensed = System.currentTimeMillis();
}
}
When we register the sensor listener, I tried to keep the sampling of that to the default like SensorManager.SENSOR_DELAY_NORMAL, which is like 200,000 microseconds.
That if sentence is satisifed if we keep the SAMPLING_PERIOD_MS to something greater than the default one, so that data is saved to database only after SAMPLING_PERIOD_MS.
Keeping listener's sampling high ensures that fixed interval of delay is achieved

Related

reading the date from sqlite in android

I am storing some date in sqlite and when I try to retrieve data, it is returning null.
private ArrayList<String> file_list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> _list = db.get_file
(String.valueOf(myFiles.get(position).getId()), file_list);
Log.e("TAG","_list " + _list);
case R.id.get_file:
boolean save_file = db.add_file(String.valueOf(myFiles.get(position).getId()),
file_list);
if (save_file){
Toast.makeText(this, "saved successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "saved failed", Toast.LENGTH_SHORT).show();
}
public ArrayList<String> get_file(String id, ArrayList<String> arrayList){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + COL_FILE + " FROM "
+TABLE_NAME+" WHERE " + _ID +" =? " , new String[] {String.valueOf(id)});
if(cursor.moveToFirst()){
return arrayList;
} else {
return null;
}
}
public TrackGroupArray read_tga_file(String id, TrackGroupArray tga)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + TGA_FILE + " FROM "
+TABLE_NAME+" WHERE " + _ID +" =? " , new String[] {String.valueOf(id)});
if(cursor.moveToFirst()){
return tga;
} else {
return null;
}
}
TrackGroupArray read_tga = db.read_tga_file(String.valueOf(myFiles.get(position).getId()),
trackGroupArray);
Every time I save a file, it is saved successfully, I have checked in the db and the file is there. But when I want to retrieve it, Log.e("TAG","_list " + _list); returns null.
Your get_File method, even if there is a row and the moveToFirst succeeds, will always return null as in the event that a row is located/selected you do nothing other than return an un-instantiated arrayList.
You need to
a) instantiate the arrayList (otherwise it will be null) and then
b) add elements to the arrayList for each row that exists if any.
So something like :-
#SuppressLint("Range")
public ArrayList<String> get_file(String id, ArrayList<String> arrayList) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + COL_FILE + " FROM "
+ TABLE_NAME + " WHERE " + _ID + " =? ", new String[]{String.valueOf(id)});
ArrayList<String> rv = new ArrayList<>(); //<<<<< A instantiate the ArrayList<String>
/* Loop through the returned row(s) if any */
while (cursor.moveToNext()) {
/* for each iteration add an element to rv (the ArrayList) */
rv.add(cursor.getString(cursor.getColumnIndex(COL_FILE)));
}
cursor.close(); //<<<<< should ALWAYS close Cursors when done with them
return rv; // return the arraylist
}

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.

Android Volley with REST Api - POST will not insert into dB and respons incorrectly

I am using https://github.com/mevdschee/php-crud-api as REST Api to access my MySQL db. To access data from Android application I use Volley lib.
All works fine except POST (creating new item in db). But instead new item created I am getting JSON will all items (look like output from GET) and item is not created in dB.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "APP START");
tv = findViewById(R.id.textView);
buttonPost = findViewById(R.id.buttonPost);
buttonGet = findViewById(R.id.buttonGet);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
current_date = sd1.format(new Date(cal.getTimeInMillis()));
Log.d(TAG, "current_date=" + current_date);
cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
buttonGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "ButtonGet pressed");
tv.setText("");
getRest();
}
});
buttonPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "ButtonPost pressed");
tv.setText("");
postRest();
}
});
}
getRest()
tv.append("REST API - reading data via GET " + "\n");
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, endpointUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject vancuraLevel1 = response.getJSONObject("restdemo");
JSONArray vancuraLevel2 = vancuraLevel1.getJSONArray("records");
int JSONlenght2 = vancuraLevel2.length();
Log.d("JSON", "JSONlenght2 =" + JSONlenght2 );
for(int n = 0; n < JSONlenght2; n++) {
Log.d("JSON", "looping " + n );
JSONArray vancuraLevel3 = vancuraLevel2.getJSONArray(n);
int JSONlenght3 = vancuraLevel3.length();
String index = vancuraLevel3.getString(0);
String datum = vancuraLevel3.getString(1);
String subjekt = vancuraLevel3.getString(2);
String ovoce = vancuraLevel3.getString(3);
Log.d("JSON", "result datum" + datum + " subjekt=" + subjekt);
tv.append("Data : " + index + "/" + datum + "/" + subjekt + "/" + ovoce + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Volley REST error " + error.toString());
tv.append("ERROR " + error.toString() +"\n");
}
});
// fire Volley request
mRequestQueue.add(jsObjRequest);
postRest(){
final String whatToInsert = "foo subjekt " + current_date;
// POST - insert data
tv.append("REST API - inserting data via POST - payload=" + whatToInsert +"\n");
StringRequest postRequest = new StringRequest(Request.Method.POST, endpointUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
// tv.append(current_date + "\n");
tv.append("response = " + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.e("Error.Response", error.getMessage());
tv.append("ERROR " + error.toString() +"\n");
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//params.put("index", "NULL");
params.put("datum", "2017-12-30");
params.put("subjekt", whatToInsert);
params.put("ovoce", "2");
return params;
}
};
// fire Volley request
mRequestQueue.add(postRequest);
Result GET - it is OK
Result POST - fault
project is available at https://github.com/fanysoft/AndroidRESTapi
Looking closely at the code the GET method returns a JSONObject response while the POST method return a String response. The string response of the POST Method is very correct and it carries exactly the same result as the GET method result all you have to do is convert the String response to JSON object you ll have same JSONObject as the GET method
JSONObject jsonObject = new JSONObject(response);
Then you can parse the object for your result
Solved by disabling Volley cache
getRequest.setShouldCache(false);
postRequest.setShouldCache(false);

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.

Android SQLite cannot bind argument

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