Tracker service not working on some devices - java

I have written an application for Tracker; with a service that runs every 5 minutes. It works fine on Samsung Galaxy J7 Prime (Android 7.0) and Samsung Galaxy Tab A (Android 7.1), But when I run on Lenovo A2010 (Android 5.1), the service does not work. I don't know whether it is my code or my device which is causing the problem.
This is the log from when the service stopped:
10-08 09:01:31.122 721-737/? E/JavaBinder: *** Uncaught remote exception! (Exceptions are not yet supported across processes.)
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.android.internal.os.BatteryStatsImpl.updateAllPhoneStateLocked(BatteryStatsImpl.java:3321)
at com.android.internal.os.BatteryStatsImpl.notePhoneSignalStrengthLocked(BatteryStatsImpl.java:3351)
at com.android.server.am.BatteryStatsService.notePhoneSignalStrength(BatteryStatsService.java:395)
at com.android.server.TelephonyRegistry.broadcastSignalStrengthChanged(TelephonyRegistry.java:1448)
at com.android.server.TelephonyRegistry.notifySignalStrengthForSubscriber(TelephonyRegistry.java:869)
at com.android.internal.telephony.ITelephonyRegistry$Stub.onTransact(ITelephonyRegistry.java:184)
at android.os.Binder.execTransact(Binder.java:451)
And here is my service, AppService.java:
public class AppService extends Service {
private MyThread thread;
PowerManager.WakeLock wl;
DatabaseHelper myDb;
private static final String tracker = "Tracker";
String result=null,status=null,statusresult=null;
String stusername;
String imeiids;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!thread.isAlive()) {
thread.start();
}
return START_STICKY;
}
#Override
public void onDestroy() {
if (thread.isAlive()) {
stopService(new Intent(this, AppService.class));
}
super.onDestroy();
}
#Override
public void onCreate() {
Toast.makeText(AppService.this,"Start...",Toast.LENGTH_SHORT).show();
thread = new MyThread();
myDb = new DatabaseHelper(this);
SharedPreferences shared = getSharedPreferences(tracker, Context.MODE_PRIVATE);
stusername = shared.getString("username", "not found!").toString();
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE)== PackageManager.PERMISSION_GRANTED){
TelephonyManager c=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
SharedPreferences.Editor editor = shared.edit();
if(c.getDeviceId()==null){
editor.commit();
}
else{
editor.putString("imeiid", c.getDeviceId());
editor.commit();
}
}
}
private class MyThread extends Thread {
private static final String tag = "Sevice Demo";
private static final int delay = 60000;//60000=30sec/1minute
private int roundNumber = 0;
private boolean finishService = false;
#Override
public void run() {
while (true) {
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(
getApplicationContext().POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
if(ContextCompat.checkSelfPermission(AppService.this, android.Manifest.permission.READ_PHONE_STATE)== PackageManager.PERMISSION_GRANTED){
TelephonyManager c=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imeiids = c.getDeviceId();
}
if(imeiids== null){
SharedPreferences shared = getSharedPreferences(tracker, Context.MODE_PRIVATE);
imeiids=shared.getString("imeiid", "").toString();
}
Date current = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String currentDateandTime = sdf.format(current);
if(!stusername.equals("not found!")){
//////////////////////////////////// Open GPS //////////////////////////////////////
int off=0;
try {
off = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
if(off==0){
Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(onGPS);
}
////////////////////////////////////////////////////////////////////////////////////
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDateString = formatter.format(currentTime);
SimpleDateFormat formatstr = new SimpleDateFormat("EEE", Locale.US);
final String formattedDayString = formatstr.format(currentTime);
if (!haveNetworkConnection()) {
/*no network connect*/
}
else{
Cursor res = myDb.getDatasync(stusername);
if(res.getCount()==0){
Log.d("dddd", "no data");
}
else{
String datetimes=null,lats=null,longs=null;
res.moveToFirst();
do{
final String ids=res.getString(0);
datetimes=res.getString(1);
lats=res.getString(3);
longs=res.getString(4);
final String finalDatetimes = datetimes;
final String finalLats = lats;
final String finalLongs = longs;
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
String location_url = "http://_____._________/__________/______________________.php";
try {
URL url = new URL(location_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("staffcode", "UTF-8") + "=" + URLEncoder.encode(stusername, "UTF-8")+ "&"
+ URLEncoder.encode("dateTime", "UTF-8") + "=" + URLEncoder.encode(finalDatetimes, "UTF-8") + "&"
+ URLEncoder.encode("lat", "UTF-8") + "=" + URLEncoder.encode(finalLats, "UTF-8") + "&"
+ URLEncoder.encode("lon", "UTF-8") + "=" + URLEncoder.encode(finalLongs, "UTF-8") + "&"
+ URLEncoder.encode("imei", "UTF-8") + "=" + URLEncoder.encode(imeiids, "UTF-8") + "&"
+ URLEncoder.encode("app", "UTF-8") + "=" + URLEncoder.encode("T:1.0", "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result = line;
}
JSONObject jsonObject = new JSONObject(result.toString());
for (int i = 0; i < jsonObject.length(); i++)
{
status=(jsonObject.getString("status")); //Get Status
statusresult=(jsonObject.getString("statusresult"));
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(status.equals("success")&& statusresult.equals("success")){
boolean isUpdate = myDb.updateDatasync(ids);
if(isUpdate) {
Log.d("Get Data ", "Updated");
}
else {
Log.d("Get Data ", "not updated");
}
}
else{
}
}
}.execute();
}while(res.moveToNext());
}
}
Cursor res = myDb.getData(stusername);
if (res.getCount() ==0) {
Log.d("dddd", "no data");
}
else {
res.moveToFirst();
do{
String asubstring = String.valueOf(res.getString(1)).substring(11, 16);
String datesub = res.getString(1).substring(0, 10);
if(currentDateandTime.equals(datesub)){ /* Today */ }
else{
//Not Today
if(!res.getString(5).equals("1")) { }
else{ // If Sync = 1 = Sync Success
boolean isDeleteSync = myDb.deleteDataSync(res.getString(0));
if(isDeleteSync) {
Log.d("Log Delete ", "Deleted");
}
else {
Log.d("Log Delete ", "Can't Deleted");
}
}
}
}while(res.moveToNext());
}
if (formattedDayString.equals("Sun")) {
}
else {
String hour = formattedDateString.substring(11, 13);
String minute = formattedDateString.substring(14, 16);
Integer ins = Integer.parseInt(minute);
if (hour.equals("08") || hour.equals("09") || hour.equals("10") || hour.equals("11") || hour.equals("12")
|| hour.equals("13") || hour.equals("14") || hour.equals("15") || hour.equals("16") || hour.equals("17")
|| hour.equals("18")) {
if((hour.equals("18"))&&(ins<=0)){
SimpleDateFormat formatterss = new SimpleDateFormat("HH:mm:ss");
String DateString = formatterss.format(currentTime);
String subtime= DateString.substring(3,5);
Integer minuteif=Integer.parseInt(subtime);
if(minuteif%5==0){
startService(new Intent(AppService.this, GetLocation.class));
}
}
if((!hour.equals("18"))){
SimpleDateFormat formatterss = new SimpleDateFormat("HH:mm:ss");
String DateString = formatterss.format(currentTime);
String subtime= DateString.substring(3,5);
Integer minuteif=Integer.parseInt(subtime);
if(minuteif%5==0){
startService(new Intent(AppService.this, GetLocation.class));
}
}
}
else{
}
}
try {
stopService(new Intent(AppService.this,GetLocation.class));
sleep(delay);
run();
}
catch (InterruptedException e) {
e.printStackTrace();
}
wl.release();
if (finishService) {
return;
}
}
}
}
}
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
}
It's my DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Tracker.db";
public static final String TABLE_NAME = "LocationMessenger";
public static final String COL_1 = "ID";
public static final String COL_2 = "DATE";
public static final String COL_3 = "USERNAME";
public static final String COL_4 = "LATITUDE";
public static final String COL_5 = "LONGITUDE";
public static final String COL_6 = "SYNC";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"DATE TEXT,USERNAME TEXT,LATITUDE TEXT,LONGITUDE TEXT,SYNC TEXT )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String dates,String username,String latitude,String longitude) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,dates);
contentValues.put(COL_3,username);
contentValues.put(COL_4,latitude);
contentValues.put(COL_5,longitude);
contentValues.put(COL_6,"0");
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1) {
return false;
}
else{
return true;
}
}
public boolean insertDataSuccess(String dates,String username,String latitude,String longitude) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,dates);
contentValues.put(COL_3,username);
contentValues.put(COL_4,latitude);
contentValues.put(COL_5,longitude);
contentValues.put(COL_6,"1");
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1) {
return false;
}
else{
return true;
}
}
public Cursor getData(String username) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,username);
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where USERNAME= ? ",new String[] { username });
return res;
}
public Cursor getDataforsync(String id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,id);
contentValues.put(COL_6,"0");
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where ID= ? and SYNC = ?",new String[] { id,"0" });
return res;
}
public Cursor getDatasync(String username) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,username);
contentValues.put(COL_6,"0");
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where USERNAME= ? and SYNC = ?",new String[] { username,"0" });
return res;
}
public boolean deleteData(String id){
SQLiteDatabase db =this.getWritableDatabase();
long rows = db.delete(TABLE_NAME, "ID = ?", new String[] { String.valueOf(id) });
db.close();
if(rows == -1) {
return false;
}
else{
return true;
}
}
public boolean deleteDataSync(String id){
SQLiteDatabase db =this.getWritableDatabase();
long rows = db.delete(TABLE_NAME, "ID = ?", new String[] { id });
db.close();
if(rows == -1) {
return false;
}
else{
return true;
}
}
public boolean updateDatasync(String id){
SQLiteDatabase db =this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_6,"1");
long result = db.update(TABLE_NAME,contentValues,"ID=" + id,null);
if(result == -1) {
return false;
}
else{
return true;
}
}
}

Related

Android studio: I am trying to change the shared preferences and want to store the data in the SQLite database [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am new in Java Programming.
Now, I am facing the problem that I want to change the shared preferences and want to use the SQLite database to store these data. I had created the table for store these data and I am trying to save these data in SQLite.
How can I do? Anyone can help me ????
MyDatabase-Table
This is my code that using shared preferences :
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
reg = new AC_Class.Register();
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
// Check preferences/create if nonexistent
prefs = this.getSharedPreferences("com.presoft.androidmobilestock", Context.MODE_PRIVATE);
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
prefs.edit().putString("UUID", uniqueID).commit();
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
finish();
}
//On return of intent
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 7) {
url = data.getStringExtra("URLKey");
urlStr = data.getStringExtra("URLStr");
Log.i("custDebug", url + ", " + urlStr);
binding.txtURL.setText(urlStr);
if (!TextUtils.isEmpty(binding.txtURL.getText().toString())) {
new GetModules(Login.this).execute(url);
new GetLoginList(Login.this).execute(url);
new SetDevice(Login.this).execute(url);
}
}
}
//Open connection settings
public void btnSetClicked(View view) {
Intent intent = new Intent(Login.this, ConnectionSettings.class);
startActivityForResult(intent, 7);
}
//Reset Database
public void btnResetDbClicked(final View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Reset DB");
builder.setMessage("Are you sure you want to reset the Database?");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (input.getText().toString().equals("presoftmobile")) {
db.close();
deleteDatabase("AutoCountDatabase");
} else {
// Toast.makeText(getApplicationContext(), "Incorrect Password", Toast.LENGTH_SHORT);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
//Login button
public void btnLoginBtnClicked(View view) {
if (TextUtils.isEmpty(binding.txtURL.getText().toString())) {
binding.txtURL.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtID.getText().toString())) {
binding.txtID.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtpw.getText().toString())) {
binding.txtpw.setError("This field can't be blank.");
//return;
}
//Non-empty fields
else {
Cursor checkData = db.loginValidate(binding.txtID.getText().toString(),
binding.txtpw.getText().toString().toUpperCase());
if (checkData.getCount() > 0) {
checkData.moveToNext();
//Shared Preferences
prefs.edit().putString("URL", url).apply();
prefs.edit().putString("URLstr", binding.txtURL.getText().toString()).apply();
if (binding.rmbCheckBox.isChecked()) {
prefs.edit().putString("ID", binding.txtID.getText().toString()).apply();
prefs.edit().putString("pwd", binding.txtpw.getText().toString()).apply();
}
prefs.edit().putInt("EnableSetting", checkData.getInt(checkData.getColumnIndex("EnableSetting"))).apply();
prefs.edit().putInt("FilterByAgent", checkData.getInt(checkData.getColumnIndex("FilterByAgent"))).apply();
prefs.edit().putInt("Sales", checkData.getInt(checkData.getColumnIndex("Sales"))).apply();
prefs.edit().putInt("Purchase", checkData.getInt(checkData.getColumnIndex("Purchase"))).apply();
prefs.edit().putInt("Transfer", checkData.getInt(checkData.getColumnIndex("Transfer"))).apply();
if (url != null) {
try {
// Check Connection
new SetDevice(Login.this).execute(url);
// Go to main
Intent intent = new Intent(Login.this, Dashboard.class);
intent.putExtra("URLKey", url);
intent.putExtra("URLStr", binding.txtURL.getText().toString());
startActivity(intent);
finish();
} catch (Exception e) {
Log.i("custDebug", e.getMessage());
Toast.makeText(this, "Unable to connect to server", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(this, "Invalid login credentials", Toast.LENGTH_SHORT).show();
binding.txtpw.setText(null);
}
checkData.close();
}
}
This is the code that to save the data in SQLite database (but getting error):
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
db = new ACDatabase(this);
uniqueID = db.getReg("8");
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
db.updateREG("8", uniqueID);
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
mydatabasehelper
//GET value by id
public Cursor getReg(String id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT Value FROM " + TABLE_NAME_REG + " WHERE ID ='" + id + "'",null);
return data;
}
//update value
public boolean updateREG(String ID, String Value) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Value", Value);
String[] args = new String[]{ID};
database.update("Reg", cv, "ID = ?", args);
return true;
}
The following is a working example that acts very similar to shared prefs but stores the prefs in an SQLite database.
The table is very simple 2 columns. The key (name of the stored value) and the value itself. Which can be String, boolean, int, long or Float.
It includes methods to; insert (add) a key/value pair, update a key/value pair and to get a value according to the key and also to return a default value as passed (making it easy to detect if the value was retrieved).
The DatabaseHelper (sub class of SQLiteOpenHelper) has most of the code and is :-
class DBHelper extends SQLiteOpenHelper {
private static volatile DBHelper instance = null;
private SQLiteDatabase db = null;
public static final String DBNAME = "sharedpreferences.db";
public static final int DBVERSION = 1;
public static final String TBLNAME_SP = "_shared_preferences";
public static final String COLNAME_SP_KEY = "_key";
public static final String COLNAME_SP_VALUE = "_value";
private DBHelper(#Nullable Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TBLNAME_SP +
"(" +
COLNAME_SP_KEY + " PRIMARY KEY," +
COLNAME_SP_VALUE + " TEXT" +
")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
private long insertPrefsRow(ContentValues cv, String key) {
cv.put(COLNAME_SP_KEY,key);
return db.insertWithOnConflict(TBLNAME_SP,null,cv, SQLiteDatabase.CONFLICT_IGNORE);
}
public long insertPrefsValue (String key, int value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, String value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, long value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, boolean value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, float value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
private long updatePrefs(String key, ContentValues cv) {
return db.update(TBLNAME_SP,cv,COLNAME_SP_KEY + "=?",new String[]{key} );
}
public long updatePrefsStringValue(String key, String newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, boolean newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, int newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, long newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, Float newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
private Cursor getPrefsValue(String key) {
return db.query(TBLNAME_SP,new String[]{COLNAME_SP_VALUE},COLNAME_SP_KEY + "=?",new String[]{key},null,null,null);
}
public String getPrefsStringValue(String key, String default_value) {
String rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Boolean getPrefsBooleanValue(String key, boolean default_value ) {
Boolean rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE)) != 0;
csr.close();
}
return rv;
}
public int getPrefsIntValue(String key, int default_value) {
int rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public long getPrefsLongValue(String key, long default_value) {
long rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Float getPrefsFLoatValue(String key, Float default_value) {
Float rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getFloat(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
}
The following is an activity that demonstrates usage:-
public class MainActivity extends AppCompatActivity {
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = DBHelper.getInstance(this);
db.insertPrefsValue("UUID","3FDE9813F93A47CBA6CD4F5DAAECEE01");
db.insertPrefsValue("taxInclusive",false);
db.insertPrefsValue("myprefs_int",100);
db.insertPrefsValue("myprefs_long",100L);
db.insertPrefsValue("myprefs_float",10.567F);
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
db.updatePrefsStringValue("UUID","FFFF9813F93A47CBA6CD4F5DAAECEE01");
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
}
}
When run (or rerun BUT when rerun the updated UUID rather than the original is retrieved) the log contains :-
D/PREFSINFO: Stored UUID is 3FDE9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
D/PREFSINFO: Stored UUID is FFFF9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
NOT STORED demonstrates the default value being returned when the Key/Name isn't stored.
As you can see UUID has been updated in the second line (if rerun both lines would show the updated value)

database records not updating android studio , sql-lite

Could someone help me? my records are not updating.
I guess the edittext stay the same but not too sure.
How to change the view values that is being put in the edittext to change to the values in updating edittexts.
Would appreciate some help with this
Thank you.
DatabaseManager
public Cursor selectRow(String ID) {
String query = "Select * from " + TABLE_NAME + " where studentID = " + ID;
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
public boolean updateData(String id, String fn, String ln, String ge, String cs, String a, String loc) {
ContentValues contentValues = new ContentValues();
contentValues.put("studentID", id);
contentValues.put("first_name", fn);
contentValues.put("last_name", ln);
contentValues.put("gender", ge);
contentValues.put("course_study", cs);
contentValues.put("age", a);
contentValues.put("location", loc);
db.update(TABLE_NAME, contentValues, "studentID = ?", new String[]{id});
return true;
}
The above is parts of my database that I use in this activity.
activity main.java
private void UpdateData() {
u.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.VISIBLE);
again.setVisibility(View.VISIBLE);
Cursor res = mydManager.selectRow(text);
if (res != null && res.moveToFirst()) {
String id = Integer.toString(res.getInt(0));
String nme = res.getString(1);
String lnme = res.getString(2);
String gen = res.getString(3);
String corse = res.getString(4);
String ag = Integer.toString(res.getInt(5));
String lo = res.getString(6);
studid.setText(id);
fname.setText(nme);
lname.setText(lnme);
gender.setText(gen);
course.setText(corse);
age.setText(ag);
loc.setText(lo);
}
}
}
);
}
public void UpdateData1() {
again.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.GONE);
String id = studid.getText().toString();
String nme = fname.getText().toString();
String lnme = lname.getText().toString();
String gen = gender.getText().toString();
String corse = course.getText().toString();
String ag = age.getText().toString();
String lo = loc.getText().toString();
boolean isUpdated = mydManager.updateData(id, nme , lnme, gen, corse ,ag , lo);
if (isUpdated == true)
Toast.makeText(Main4Activity.this, "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(Main4Activity.this, "Data Not Updated", Toast.LENGTH_LONG).show();
}
}
);
}
I tried having a button to set the data but it still stays the same.
Sorry din't read the code, take the sample if it helps
Just the logic..
public long updateNote(NoteModel noteModel) {
if (LOG_DEBUG) UtilLogger.showLogUpdate(TAG, noteModel, noteModel.getRow_pos());
long updatedRow = 0;
try {
ContentValues contentValues = new ContentValues();
contentValues.put(DBSchema.DB_TITLE, noteModel.getTitle());
contentValues.put(DBSchema.DB_IMAGE_PATH, noteModel.getImgUriPath());
contentValues.put(DBSchema.DB_SUB_TEXT, noteModel.getSub_text());
contentValues.put(DBSchema.DB_CREATE_DATE, noteModel.getCreateDate());
contentValues.put(DBSchema.DB_UPDATE_DATE, noteModel.getUpdateDate());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_LONG, noteModel.getScheduleTimeLong());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_WHEN, noteModel.getScheduledWhenLong());
contentValues.put(DBSchema.DB_SCHEDULED_TITLE, noteModel.getScheduledTitle());
contentValues.put(DBSchema.DB_IS_ALARM_SCHEDULED, noteModel.getIsAlarmScheduled());
contentValues.put(DBSchema.DB_IS_TASK_DONE, noteModel.getIsTaskDone());
contentValues.put(DBSchema.DB_IS_ARCHIVED, noteModel.getIsArchived());
updatedRow = mSqLiteDatabase.updateWithOnConflict(
DBSchema.DB_TABLE_NAME,
contentValues,
DBSchema.DB_ROW_ID + " =?", new String[]{String.valueOf(noteModel.get_id())}, mSqLiteDatabase.CONFLICT_REPLACE);
return updatedRow;
} catch (SQLException e) {
e.printStackTrace();
}
return updatedRow;
}
then take the cursor
public Cursor getCursorForAlarmScheduled(String passAlarmScheduledStatus) {
if (LOG_DEBUG)
Log.w(TAG, " pick all record with alarmScheduled 1 : " + passAlarmScheduledStatus);
return mSqLiteDatabase.rawQuery(DBSchema.DB_SELECT_ALL +
" WHERE " + DBSchema.DB_IS_ALARM_SCHEDULED + " = " + passAlarmScheduledStatus, null);
}
and then extract
//common operation for all,
public static List<NoteModel> extractCommonData(Cursor cursor, List<NoteModel> noteModelList) {
noteModelList = new ArrayList<>();
if (LOG_DEBUG) Log.i(TAG, "inside extractCommonData()");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
NoteModel noteModel = new NoteModel();
noteModel.set_id(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_ROW_ID)));
noteModel.setTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_TITLE)));
noteModel.setImgUriPath(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IMAGE_PATH)));
noteModel.setSub_text(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SUB_TEXT)));
noteModel.setCreateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_CREATE_DATE)));
noteModel.setUpdateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_UPDATE_DATE)));
noteModel.setScheduleTimeLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_LONG)));
noteModel.setScheduledWhenLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_WHEN)));
noteModel.setScheduledTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TITLE)));
noteModel.setIsAlarmScheduled(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ALARM_SCHEDULED)));
noteModel.setIsTaskDone(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_TASK_DONE)));
noteModel.setIsArchived(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ARCHIVED)));
noteModelList.add(noteModel);
} while (cursor.moveToNext());
}
cursor.close();
}
return noteModelList;
}
Again, I din't read,just copied from my old samples
Please do find the needful, cheers

Not able to match or compare two dates

I am not able to match or compare two dates one from Database and second is current date.I have five checkboxes. When 1st user checkes a checkbox and insert its value by clicking the save button. 2nd time when he check 2 or more checkboxes Now here I want to update last record by date. I set date as primary key in that table.
NamazCounterActivity
package com.example.shakeelmughal.assanislam;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class NamazCounterActivity extends AppCompatActivity {
DatabaseHelper mydb;
CheckBox cb1,cb2,cb3,cb4,cb5;
Button B1,B2,B3;
TextView tv;
int vcb1=0,vcb2=0,vcb3=0,vcb4=0,vcb5=0;
Date date = new Date();
String a="1";
public static final String SHARED_PREF = "sharedPrefs";
public static final String CHECK1 = "check1";
public static final String CHECK2 = "check2";
public static final String CHECK3 = "check3";
public static final String CHECK4 = "check4";
public static final String CHECK5 = "check5";
private Boolean chb1,chb2,chb3,chb4,chb5;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_namaz_counter);
try {
mydb = new DatabaseHelper(this);
} catch (IOException e) {
e.printStackTrace();
}
tv = findViewById(R.id.textView24);
cb1 = findViewById(R.id.namaz1);
cb2 = findViewById(R.id.namaz2);
cb3 = findViewById(R.id.namaz3);
cb4 = findViewById(R.id.namaz4);
cb5 = findViewById(R.id.namaz5);
B1 = findViewById(R.id.result);
B2 = findViewById(R.id.dateee);
B3 = findViewById(R.id.sumr);
c_date();
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = mydb.getAllData1();
if (c.moveToFirst())
{
if(mydb.date().equals(c.getString(0)))
{
Updateingdata();
}
else
{
InsertingData();
}
}
else
{
InsertingData();
}
SaveData();
}
});
B3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = mydb.getAllData();
if(c.getCount() == 0)
{
Toast.makeText(NamazCounterActivity.this,"Empty",Toast.LENGTH_SHORT).show();
}
StringBuffer stringBuffer = new StringBuffer();
while (c.moveToNext())
{
stringBuffer.append("ID: " +c.getString(0 )+"\n");
stringBuffer.append("Fajar: " +c.getString(1)+"\n");
stringBuffer.append("Zohr: " +c.getString(2)+"\n");
stringBuffer.append("Asr: " +c.getString(3)+"\n");
stringBuffer.append("Magrib: " +c.getString(4)+"\n" );
stringBuffer.append("Isha: " +c.getString(5)+"\n");
}
showData("Data",stringBuffer.toString());
}
});
//home button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
//functions for save old values
loadData();
updateViews();
}
//function for going back to previous activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
public void InsertingData()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
}
else
{
vcb5 = 0;
}
boolean result = mydb.InsertData(date().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(result == true)
{
Toast.makeText(NamazCounterActivity.this, "Prayer Saved",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(NamazCounterActivity.this, "Some Error", Toast.LENGTH_LONG).show();
}
}
public void Updateingdata()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
}
else
{
vcb5 = 0;
}
boolean res = mydb.UpdateData(B2.getText().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(res == true)
{
Toast.makeText(NamazCounterActivity.this,"Data Updated",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(NamazCounterActivity.this,"Data Not Updated",Toast.LENGTH_SHORT).show();
}
}
//for date ()
public void c_date() {
date.setTime(System.currentTimeMillis()); //set to current time
B2.setText(date.toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEEEEEEE, MMM dd, yyyy");
B2.setText(dateFormat.format(date));
}
public void SaveData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(CHECK1, cb1.isChecked());
editor.putBoolean(CHECK2, cb2.isChecked());
editor.putBoolean(CHECK3, cb3.isChecked());
editor.putBoolean(CHECK4, cb4.isChecked());
editor.putBoolean(CHECK5, cb5.isChecked());
editor.apply();
}
public void loadData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF,MODE_PRIVATE);
chb1 = sharedPreferences.getBoolean(CHECK1, false);
chb2 = sharedPreferences.getBoolean(CHECK2, false);
chb3 = sharedPreferences.getBoolean(CHECK3, false);
chb4 = sharedPreferences.getBoolean(CHECK4, false);
chb5 = sharedPreferences.getBoolean(CHECK5, false);
}
public void updateViews()
{
cb1.setChecked(chb1);
cb2.setChecked(chb2);
cb3.setChecked(chb3);
cb4.setChecked(chb4);
cb5.setChecked(chb5);
}
public void showData(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public java.sql.Date date()
{
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
return date;
}
}
DatabaseHelper.java
package com.example.shakeelmughal.assanislam;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Date;
import static android.content.ContentValues.TAG;
import static java.time.LocalTime.now;
/**
* Created by Shakeel Mughal on 5/30/2018.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public Context context;
private SQLiteDatabase db2;
public AssetManager mngr;
SQLiteDatabase db;
private Resources mResources;
private InputStream inputstream = null;
private final static String Dbname = "NamazCounter.db";
private final static String Tbname = "DailyWork";
private final static String Tbname2 = "items";
private final static String Col_1 = "ID";
private final static String Col_2 = "Fajar";
private final static String Col_3 = "Zohr";
private final static String Col_4 = "Asr";
private final static String Col_5 = "Magrib";
private final static String Col_6 = "Isha";
private final static String NCol_1 = "date_for";
private final static String NCol_2 = "fajr";
private final static String NCol_3 = "shurooq";
private final static String NCol_4 = "dhuhr";
private final static String NCol_5 = "asr";
private final static String NCol_6 = "maghrib";
private final static String NCol_7 = "isha";
public DatabaseHelper(Context context) throws IOException {
super(context, Dbname, null, 1);
this.context = context;
mResources = context.getResources();
mngr = context.getAssets();
db = this.getWritableDatabase();
db = this.getReadableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
//namaz counter
final String Table1 = "CREATE TABLE "+Tbname+"(ID PRIMARY KEY TEXT, Fajar TEXT, Zohr TEXT, Asr TEXT, Magrib TEXT, Isha TEXT)";
//for namaz timing
final String Table2 = "CREATE TABLE "+Tbname2+"(date_for TEXT, fajr TEXT, shurooq TEXT, dhuhr TEXT, asr TEXT, maghrib TEXT,isha TEXT)";
db.execSQL(Table1);
db.execSQL(Table2);
Log.d(TAG, "DataBase Created");
try {
readDataToDb(db);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ Tbname);
db.execSQL("DROP TABLE IF EXISTS "+ Tbname2);
onCreate(db);
}
public void openDatabase() {
String dbPath = context.getDatabasePath(Dbname).getPath();
if (db != null) {
db.isOpen();
return;
}
db = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if (db != null) {
db.close();
}
}
//Json fun
private String readJsonDataFromFile() throws IOException {
StringBuilder builder = new StringBuilder();
try {
String jsonDataString = null;
inputstream = mngr.open("NamazTiming.json");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputstream, "UTF-8"));
while ((jsonDataString = bufferedReader.readLine()) != null) {
builder.append(jsonDataString);
}
} finally {
if (inputstream != null) {
inputstream.close();
}
}
return new String(builder);
}
public void readDataToDb(SQLiteDatabase db) throws IOException, JSONException {
final String date = "date_for";
final String namaz1 = "fajr";
final String namaz2 = "shurooq";
final String namaz3 = "dhuhr";
final String namaz4 = "asr";
final String namaz5 = "maghrib";
final String namaz6 = "isha";
try {
String jsonDataString = readJsonDataFromFile();
JSONArray jsonfileJSONArray = new JSONArray(jsonDataString);
for (int i = 0; i < jsonfileJSONArray.length(); i++) {
String dateid;
String nmz1;
String nmz2;
String nmz3;
String nmz4;
String nmz5;
String nmz6;
JSONObject jsonfileObject = jsonfileJSONArray.getJSONObject(i);
dateid = jsonfileObject.getString(date);
nmz1 = jsonfileObject.getString(namaz1);
nmz2 = jsonfileObject.getString(namaz2);
nmz3 = jsonfileObject.getString(namaz3);
nmz4 = jsonfileObject.getString(namaz4);
nmz5 = jsonfileObject.getString(namaz5);
nmz6 = jsonfileObject.getString(namaz6);
ContentValues jsonfilevalues = new ContentValues();
jsonfilevalues.put(NCol_1, dateid);
jsonfilevalues.put(NCol_2, nmz1);
jsonfilevalues.put(NCol_3, nmz2);
jsonfilevalues.put(NCol_4, nmz3);
jsonfilevalues.put(NCol_5, nmz4);
jsonfilevalues.put(NCol_6, nmz5);
jsonfilevalues.put(NCol_7, nmz6);
long rowID= db.insert(Tbname2, null, jsonfilevalues);
if(rowID>-1){
int catid=0;
Cursor cursor = db.rawQuery("SELECT "+ NCol_1 + " FROM "+ Tbname2+" where "+ NCol_1 + "='" + now() + "'" , null);
cursor.moveToFirst();
if (cursor.moveToNext()) {
catid = (cursor.getInt(0));
}
cursor.close();
JSONArray jsonitemsarray= (JSONArray) jsonfileObject.get("itemsList");
readitem(db,jsonitemsarray);
}
Log.d(TAG, "Inserted sucessfully" + jsonfilevalues);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private void readitem(SQLiteDatabase db,JSONArray jsonfileJSONArray) throws IOException, JSONException {
final String date1 = "date_for";
final String namaz1 = "fajr";
final String namaz2 = "shurooq";
final String namaz3 = "dhuhr";
final String namaz4 = "asr";
final String namaz5 = "maghrib";
final String namaz6 = "isha";
try {
for (int i = 0; i < jsonfileJSONArray.length(); i++) {
String Did;
String nmzz1 ;
String nmzz2 ;
String nmzz3 ;
String nmzz4 ;
String nmzz5 ;
String nmzz6 ;
JSONObject jsonfileObject1 = jsonfileJSONArray.getJSONObject(i);
Did = jsonfileObject1.getString(date1);
nmzz1 = jsonfileObject1.getString(namaz1);
nmzz2 = jsonfileObject1.getString(namaz2);
nmzz3 = jsonfileObject1.getString(namaz3);
nmzz4 = jsonfileObject1.getString(namaz4);
nmzz5 = jsonfileObject1.getString(namaz5);
nmzz6 = jsonfileObject1.getString(namaz6);
ContentValues jsonfilevalues1 = new ContentValues();
jsonfilevalues1.put(NCol_1, Did);
jsonfilevalues1.put(NCol_2, nmzz1);
jsonfilevalues1.put(NCol_3, nmzz2);
jsonfilevalues1.put(NCol_4, nmzz3);
jsonfilevalues1.put(NCol_5, nmzz4);
jsonfilevalues1.put(NCol_6, nmzz5);
jsonfilevalues1.put(NCol_7, nmzz6);
db.insert(Tbname2, null, jsonfilevalues1);
Log.d(TAG, "Inserted sucessfully" + jsonfilevalues1);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
}
}
//inserting for counter
public boolean InsertData(String d_date, String Fjr, String zhr, String assr, String mgrb, String isa)
{
SQLiteDatabase db = this.getReadableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_1,d_date);
contentValues.put(Col_2,Fjr);
contentValues.put(Col_3,zhr);
contentValues.put(Col_4,assr);
contentValues.put(Col_5,mgrb);
contentValues.put(Col_6,isa);
long success = db.insert(Tbname,null,contentValues);
if(success == -1)
{
return false;
}
else
{
return true;
}
}
public boolean UpdateData(String id,String n1, String n2, String n3,String n4,String n5)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_1,id);
contentValues.put(Col_2,n1);
contentValues.put(Col_3,n2);
contentValues.put(Col_4,n3);
contentValues.put(Col_3,n4);
contentValues.put(Col_4,n5);
db.update(Tbname,contentValues,"ID = ?", new String[]{id});
return true;
}
public Cursor getAllDataForNamaz()
{
openDatabase();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT * FROM "+ Tbname2 + " WHERE date_for = "+ date(),null);
closeDatabase();
return cs;
}
public Date date()
{
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
return date;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT * FROM "+ Tbname,null);
return cs;
}
public Cursor getAllData1()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT ID FROM "+ Tbname,null);
return cs;
}
}
I advise you to convert all your date into timestamp and use only timestamp for comparaison (you can also save date as timestamp in your database) :
System.currentTimeMillis() // Current timestamp
date.time // timestamp of the SQL Date object
if (timestamp1 > timestamp2) {
// timestamp1 after timestamp2
} else if (timestamp1 < timestamp2) {
// timestamp1 before timestamp2
} else {
// timestamp1 == timestamp2
}
Try this code first convert data into this format..."dd/mm/yyyy"
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
// define log
}

Android - Not reading few lines from database

Hi am new to android and would like some help. So in my app I am fetching data from an xml file on a server and storing it in a database. I manually checked the database and all went well. Now when I am trying to read the data from the connectToDB() method in ActivityTwo class I see no data on the screen but when I read the data from the offlineDatabase() in the same class, I see the data perfectly on the screen. I am completely baffled by this situation. Any help would be immensely appreciated. BTW: connectToDB() is called when the user is online and offlineDatabase() is called when the user is offline.
ActivityTwo.java
public class ActivityTwo extends Activity {
private ArrayList<String> eventsList = new ArrayList<String>();
private HandleXML handleXML;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.events);
if(netCheckPls() == false) {
new AlertDialog.Builder(this)
.setTitle("Internet Connection")
.setMessage("Not connected to the Internet!")
.setCancelable(true)
.setPositiveButton(R.string.ok, null)
.show();
offlineDatabase();
} else {
connectToDB();
}
}
#Override
public void onDestroy() {
//eventsData.close();
}
public void offlineDatabase() {
DBHelper dHelper = new DBHelper(this);
eventsList = dHelper.getAllEvents();
addMoreRows();
}
public void connectToDB() {
handleXML = new HandleXML(this, "http://eamplesite/example.xml");
handleXML.fetchXML();
//while(handleXML.parsingComplete);
//;
eventsList = handleXML.arrayList();
addMoreRows();
//offlineDatabase();
}
public void addMoreRows() {
TableLayout tl = (TableLayout)findViewById(R.id.linearLayout);
for(int i = 0; i < eventsList.size(); i++) {
TableRow row = new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
TextView tv = new TextView(this);
tv.setTextColor(Color.parseColor("#FFFFFF"));
tv.setText((String)eventsList.get(i));
row.addView(tv);
tl.addView(row);
}
}
public boolean netCheckPls() {
Context ctx = this;
ConnectivityManager connec = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// Check if wifi or mobile network is available or not. If any of them is
// available or connected then it will return true, otherwise false;
return wifi.isConnected() || mobile.isConnected();
}
}
HandleXML.java
public class HandleXML extends Activity {
private String title = "title";
private String link = "link";
private String description = "description";
private DBHelper dbHelper;
private ArrayList<String> titles = new ArrayList<String>();
private ArrayList<String> links = new ArrayList<String>();
private ArrayList<String> descriptions = new ArrayList<String>();
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public HandleXML(Context context, String url){
context.deleteDatabase("EventsDB.db");
dbHelper = new DBHelper(context);
this.urlString = url;
}
public ArrayList<String> arrayList() {
return dbHelper.getAllEvents();
}
public String getTheTitle(){
return title;
}
public String getLink(){
return link;
}
public String getDescription(){
return description;
}
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text=null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("title")){
title = text;
titles.add(text);
}
else if(name.equals("guid")){
link = text;
links.add(text);
}
else if(name.equals("description")){
description = text;
descriptions.add(text);
}
else{
}
break;
}
event = myParser.next();
}
parsingComplete = false;
//dbHelper.insertEvents(title, description, link);
addToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addToDB() {
for(int i = 0; i < titles.size(); i++) {
dbHelper.insertEvents(titles.get(i), descriptions.get(i), links.get(i));
}
}
public void fetchXML(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
} catch (Exception e) {
}
}
});
thread.start();
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "EventsDB.db";
public static final String EVENTS_TITLE = "title";
public static final String EVENTS_DESCRIPTION = "decription";
public static final String EVENTS_LINK = "link";
public static final String EVENTS_TABLE_NAME = "events";
public static final String EVENTS_COLUMN_NAME = "title";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table events " +
"(id integer primary key, title text, description text, link text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS events");
onCreate(db);
}
public boolean insertEvents (String title, String description, String link)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("title", title);
contentValues.put("description", description);
contentValues.put("link", link);
db.insert("events", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from events where id=" + id + "", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, EVENTS_TABLE_NAME);
return numRows;
}
public boolean updateEvents (Integer id, String title, String description, String link)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("title", title);
contentValues.put("description", description);
contentValues.put("link", link);
db.update("events", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
/*public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}*/
public ArrayList getAllEvents()
{
ArrayList array_list = new ArrayList();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from events", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(EVENTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
events.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:background="#drawable/bg2">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/linearLayout"
android:orientation="vertical">
</TableLayout>
</ScrollView>
</LinearLayout>
FYI the reason I want to delete the database, when the user comes online, is that I want to prevent similar data being added to the database (which I found was happening). Again would greatly appreciate some light on this matter. Thank You!
Your HandleXML class is calling context.deleteDatabase("EventsDB.db"); in its constructor.

Android Close() was never explicitly called on database

I keep getting the error message Close() was never explicitly called on database. From what I've read I'm not closing the database once the activity is destroyed, but I don't know how to implement it:
Database Helper:
public class ResultsDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "results.db";
private static final int DATABASE_VERSION = 2;
public static final String TABLE_NAME = "results";
public static final String _ID = BaseColumns._ID;
public static final String SAVED_NAME = "name";
public static final String COLUMN_NAME_CREATE_DATE = "date";
public static final String RIGHT_EAR = "right_ear";
public static final String LEFT_EAR = "left_ear";
public ResultsDatabase(Context context) {
// calls the super constructor, requesting the default cursor factory.
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ _ID + " INTEGER PRIMARY KEY,"
+ SAVED_NAME + " TEXT,"
+ COLUMN_NAME_CREATE_DATE + " INTEGER,"
+ RIGHT_EAR + " BLOB,"
+ LEFT_EAR + " BLOB"
+ ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
public static byte[] serializeObject(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
return null;
}
}
public static Object deserializeObject(byte[] b) {
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
Object object = in.readObject();
in.close();
return object;
} catch(ClassNotFoundException cnfe) {
Log.e("deserializeObject", "class not found error", cnfe);
return null;
} catch(IOException ioe) {
Log.e("deserializeObject", "io error", ioe);
return null;
}
}
}
I call this helper in my Tabbed Results Activity which displays the data in two different fragments as follows:
public class TabbedResultsActivity extends SherlockFragmentActivity{
TabHost mTabHost;
TabManager mTabManager;
public static final String IS_RIGHT_EAR = "is_right_ear";
private ArrayList<EarSrt> leftAnswerList;
private ArrayList<EarSrt> rightAnswerList;
private final static String TAG = "HearingTest";
private boolean isRightEarTab = true;
private boolean bothEarsBad;
private boolean leftEarBad;
private boolean rightEarBad;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_layout);
ActionBar ab = this.getSupportActionBar();
SherlockHelper.setupActionBar(ab, this);
View infoButton = findViewById(R.id.info_button);
infoButton.setVisibility(View.VISIBLE);
Intent intent = getIntent();
int rowId = intent.getIntExtra(ResultsDatabase._ID, -1);
if ( rowId != -1 ) {
ResultsDatabase db = new ResultsDatabase(this);
String select = "(" + ResultsDatabase._ID + " == " + rowId + ")";
Cursor c = db.getReadableDatabase().query(ResultsDatabase.TABLE_NAME, null, select, null, null, null,null);
if ( c.moveToFirst() ) {
int leftEarColumn = c.getColumnIndex(ResultsDatabase.LEFT_EAR);
byte[] leftEarByteArray = c.getBlob(leftEarColumn);
int rightEarColumn = c.getColumnIndex(ResultsDatabase.RIGHT_EAR);
byte[] rightEarByteArray = c.getBlob(rightEarColumn);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
} else {
byte[] leftEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.LEFT_EAR);
byte[] rightEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.RIGHT_EAR);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
isRightEarTab = getIntent().getBooleanExtra(IS_RIGHT_EAR, true);
GraphView graphView = new GraphView(this);
graphView.setPoints(rightAnswerList);
float leftAverage = calculateAverage(rightAnswerList);
graphView.setAverage(leftAverage);
graphView.setPoints(leftAnswerList);
float rightAverage = calculateAverage(leftAnswerList);
graphView.setAverage(rightAverage);
setResults(leftAnswerList, rightAnswerList);
String results = setResultCaption(bothEarsBad, leftEarBad, rightEarBad).toString();
Log.d(TAG, "The results were " + results);
Bundle leftbundle = new Bundle();
leftbundle.putString("results", results);
leftbundle.putParcelableArrayList("graph", leftAnswerList);
leftbundle.putFloat("average", leftAverage);
Bundle rightbundle = new Bundle();
rightbundle.putString("results", results);
rightbundle.putParcelableArrayList("graph", rightAnswerList);
rightbundle.putFloat("average", rightAverage);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
mTabManager.addTab(mTabHost.newTabSpec(getString(R.string.Left_ear)).setIndicator(getString(R.string.Left_ear)),
LeftEarResults.class, leftbundle);
mTabManager.addTab(mTabHost.newTabSpec("contacts").setIndicator(getString(R.string.Right_ear)),
RightEarResults.class, rightbundle);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return MenuActivity.createMenu(this, menu);
}
private float calculateAverage(List<EarSrt> steps) {
float srt = 0.0f;
int length = steps.size();
for (int i = (int)Math.ceil( (float)length/(float)2); i < length; i++) {
EarSrt es = steps.get(i);
srt += es.getSrt();
}
srt = srt / (length-(float)Math.ceil( (float)length/(float)2));
return srt;
}
private void setResults(List<EarSrt> leftEar, List<EarSrt> rightEar) {
float esLeft = calculateAverage(leftEar);
float esRight = calculateAverage(rightEar);
leftEarBad = (esLeft > 24.0);
rightEarBad = (esRight > 24.0);
bothEarsBad = (leftEarBad && rightEarBad);
}
private StringBuilder setResultCaption(boolean bothEarsBad, boolean leftEarBad, boolean rightEarBad) {
String resultCaption;
StringBuilder resultsText = new StringBuilder();
if (bothEarsBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else{
if (leftEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_left_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
} else if (rightEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_Right_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else {
resultsText.append(getString(R.string.There_is_no_indication_of_hearing_loss));
}
}
resultsText.append(getString(R.string.The_results_of_the_hearing_test_are_not_to_be_utilized_as_an_official_outcome_for_assessing_levels_of_hearing_loss_True_hearing_loss_assessments_can_only_be_determined_by_a_licensed_hearing_healthcare_provider));
Log.d(TAG, "The results were " + resultsText);
return resultsText;
}
public void infoView(View aView) {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
}
My quesiton is how and where should I close the connection?
Thanks
Just alter your storeResults method as follows
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase(); // opens the database connection
try {
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
catch(Exception e) {
e.printStackTrace();
// furher error handling
}
finally {
db.close(); // closes the database every time after access
}
}

Categories

Resources