how to make checkbox stay checked when program closes? - java

In my program I have around 20 check boxes however when I check them and close the program then go back on the check boxes they are always unchecked how can I make the check box remember to stay checked.

In your onPause function, write the states to a file or to a SharedPreference. In your onResume, read that file/Preference in and set the checkboxes. You may want to look at PreferenceActivity to do this for you.

You can use SharedPreferences to do this.
So first, when your application goes to onPause, you'll want to store the state of each checkbox in SharedPreferences:
SharedPreferences prefs = this.getSharedPreferences("com.example.myapp", Context.MODE_PRIVATE);
prefs.putBoolean("checkbox1", checkbox1.isChecked()).commit();
// do this for all 20
Then you can check the checkboxes onResume and onCreate:
checkbox1.setChecked(prefs.getBoolean("checkbox1", false));

You should look into using Shared Preferences .
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Writing to Shared Preferences :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Reading from Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Also here is a very simple tutorial on implementing them.
Requested Example Code :
Main Activity Class :
package com.zeus.example;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.CheckBox;
public class MainActivity extends Activity {
CheckBox chkBox1, chkBox2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chkBox1 = (CheckBox) findViewById(R.id.checkBox1);
chkBox2 = (CheckBox) findViewById(R.id.checkBox2);
SharedPreferences getPrefs =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean value = getPrefs.getBoolean("checkbox_preference", true);
chkBox1.setSelected(value); // Setting the value reflected from the preference
chkBox2.setSelected(!value); // Setting the value opposite of the preference(Just an example)
}
}
Preference Activity Class :
package com.zeus.example;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Prefs extends PreferenceActivity{
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
Settings XML :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="checkbox_preference"
android:defaultValue="false"
android:title="CheckBox1"
/>
</PreferenceScreen>
Although this method is easy, it's deprecated and is recommended to use Preference Fragments instead

Use SharedPreferences. The simplest way to store small values forever.
Since you have multiple check boxes use SharedPreferences.Editor putStringSet (String key, Set<String> values)
You can use SimpleSharedPreferences in which putStringSet is backported to API-1.
Usage: No Edit, No Commit.
SimpleSharedPreferences mPreferences = new SimpleSharedPreferences(getApplicationContext()); //Init.
mPreferences.putStringSet("STRING_SET_KEY", mStringSet); //Single Line
mPreferences.getStringSet("STRING_SET_KEY", null); // Get String set.
mPreferences.putBoolean("INTEGER_BOOL", true); //Just an example.
Note : I am the author of SimpleSharePreferences.

Related

My settings activity makes my app crash (using shared preferences)

I am working on my first app (so please forgive me if I've made a silly mistake, I am relatively new to coding). I created a settings activity for my app, but the moment I click on the settings button from the action bar, my app crashes. I tried debugging the app, turns out the moment I remove the lines where I keep the switches on setchecked, it works fine, but then if I remove the app from memory and open it again, the setting isnt saved, the switches aren't on. Please help.
package com.example.taskmasterv3;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Switch;
public class SettingsActivity extends AppCompatActivity {
public static final String SETTINGS_PREFERENCES = "com.example.taskmasterv3.SettingsPreferences";
Switch switchReminder, switchNotifications;
boolean reminders;
boolean notifications;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
SharedPreferences prefs = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE);
reminders = prefs.getBoolean("reminders", false);
notifications = prefs.getBoolean("notifications", false);
switchReminder.setChecked(reminders);
switchNotifications.setChecked(notifications);
switchReminder = findViewById(R.id.switchReminder);
switchNotifications = findViewById(R.id.switchNotifications);
if (switchReminder.isChecked()) {
reminders = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("reminders", reminders);
editor.commit();
}
if (switchNotifications.isChecked()) {
notifications = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("notifications", notifications);
editor.commit();
}
}
}
You're not using findViewById to retrieve your switches in onCreate before you're using them, so they're null:
switchReminder.setChecked(reminders);
switchNotifications.setChecked(notifications); <-- wrong order
switchReminder = findViewById(R.id.switchReminder); <-- too late, already tried to use it above
switchNotifications = findViewById(R.id.switchNotifications);
it should be:
switchReminder = findViewById(R.id.switchReminder);
switchNotifications = findViewById(R.id.switchNotifications);
switchReminder.setChecked(reminders);
switchNotifications.setChecked(notifications);

error while build Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $

package comviewappisome.google.sites.watchandearn;
public class SharedPreferences {
public static final String PREFS_NAME = "MyLoginPrefsFile";
}
package comviewappisome.google.sites.watchandearn;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import static comviewappisome.google.sites.watchandearn.SharedPreferences.PREFS_NAME;
public class login extends AppCompatActivity {
LinearLayout guestlogin = (LinearLayout )findViewById(R.id.guest);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
guestlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences settings = getSharedPreferences(comviewappisome.google.sites.watchandearn.SharedPreferences.PREFS_NAME, 0); // 0 - for private mode
SharedPreferences.Editor editor = settings.edit();
//Set "hasLoggedIn" to true
editor.putBoolean("hasLoggedIn", true);
// Commit the edits!
editor.commit();
Intent i = new Intent(login.this, ChoiceSelection.class);
startActivity(i);
}
});
}
}
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
SharedPreferences settings = getSharedPreferences(comviewappisome.google.sites.watchandearn.SharedPreferences.PREFS_NAME, 0);
//Get "hasLoggedIn" value. If the value doesn't exist yet false is returned
boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);
if(hasLoggedIn)
{
Intent i = new Intent(SplashScreen.this, login.class);
this.startActivity(i);
this.finish();
}
else
{
Intent n = new Intent(SplashScreen.this, ChoiceSelection.class);
this.startActivity(n);
this.finish();
}
}
}
This, I code in javafile and then this error show me while debug.I delete this files also and set file to previously, but I did not get any solution. My build.gradle and main.xml is also right and there is error showing while gradle sync only in debuging.I try Restart and Invalides Caches
I think this problem is caused by other classes. If you are using a web service, the json format returned from there is the wrong format.
Your client expects an array (or JSON array) but it gets an string (starts with '"') . check your string and find out the difference between. maybe it needs to remove quotation marks from start and end. but to be honest, you must LOG them to get a proper solution.
I fixed the problem by cleaning the build!

Android Get Shared Preferences of Another application

I'm trying to get some data from Word Readable Shared Preferences of another application.
I'm sure that other application Shared Preferences is World Readable and name is present.
But I'm retrieving empty string.
Here is my code:
package com.example.sharedpref;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import android.content.SharedPreferences;
public class MainActivity extends AppCompatActivity {
private TextView appContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContent = (TextView) findViewById(R.id.test1);
appContent.setText("Test Application\n");
appContent.setText(getName(this));
}
protected String getName(Context context){
Context packageContext = null;
try {
packageContext = context.createPackageContext("com.application", CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = packageContext.getSharedPreferences("name_conf", 0);
String name = sharedPreferences.getString("name", "");
return name; //HERE IS WHERE I PUT BREAKPOINT
}
catch (PackageManager.NameNotFoundException e) {
return null;
}
}
}
Here is some debug I retrieve from debug mode:
and piece of code from the app that I'm trying to access shared preferences:
/* access modifiers changed from: protected */
#SuppressLint({"WorldReadableFiles"})
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_welcome);
Editor edit = getApplicationContext().getSharedPreferences("name_conf", 0).edit();
edit.putBoolean("FIRSTRUN", false);
edit.putString("name", "Eddie");
edit.commit();
new DBHelper(this).getReadableDatabase();
PS. I Cant edit code of second app im trying access to!
Something im missing?
You can not edit it from another apps,
if you want, you can use FileWriter to create a txt file and use it in other apps

unused import statement in android studio and import is colored gray

I'm new to android and I can't seemed to figure out what causes this error.
Im trying to experiment a text view or edit view where if you click the button, it will save the inputted text and display it on the text view once you return to the app.
The error prompt error: cannot find symbol variable textView and sometimes even error: cannot find symbol variable Connect.
Question:
why is it that textView got error even if I imported import android.widget.TextView;
Also, why is the import android.widget.TextView; is colored light gray?
below are the screenshots:
Import color to gray and
Compiler error
Here is my code
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText textView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (EditText) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
final SharedPreferences sharedPref = getPreferences(Connect.MODE_PRIVATE);
String oldItem = sharedPref.getString("oldItem", "Nothing created yet...");
textView.setText(oldItem);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("oldItem", textView.getText().toString());
editor.commit();
}
});
}
}
Update:
I din't add any ID on my EditText XML code thats why the machine cannot find it.
android:id="#+id/textView"
Also, I updated from this
final SharedPreferences sharedPref = getPreferences(Connect.MODE_PRIVATE);
to this
final SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
I'm not really sure what's the difference between Connect and Context.
Thanks to #Kapil G
Problem is: You are not using TextView.
textView = (EditText) findViewById(R.id.textView);
=>
textView = (TextView) findViewById(R.id.textView);
Yes, EditText is a kind of TextView, but it seems that in your xml, it will be TextView. So, how about cast to TextView ?
Check you XML file to see if you have declared R.id.textView as TextView or Edittext.
Both are different. Your input field is your EditText and your output field where you want to show the data is TextView.
also not sure what you have declared as Connect. but SharedPreference need the mode from a Context so your line should be like this -
final SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
Plus your import is coming as gray because you have not used TextView component anywhere in the activity.
It is simply nothing but unused.
If you think you need it keep it or else you can remove it.
Also most of the time imports are brought automatically so you dont have to worry.
If you want to bring imports simply just do:
Alt + Enter

Android SDK SharedPreferences troubles

I'm working on an app and would like to save the state of obe of my checkbox options, but when I try using the SharedPreferences class (first time using it) I get a nullpointer exception. I have been troubleshooting for a couple hours and cant find a solution. Could anyone look at this and tell me what's wrong? The full code is alot longer but this is the park giving me the null pointer exception. I know for a fact it has to do with SharedPreferences.
package us.mattmccoy.meanfind;
//import java.util.Arrays;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
//saved data stuff needed
SharedPreferences preferences = this.getSharedPreferences("us.mattmccoy.meanfind", Context.MODE_PRIVATE);
Editor edit = preferences.edit();
//private data using saved data
String autoclearKEY = "us.mattmccoy.meanfind.AUTOCLEAR";
boolean autoclear = preferences.getBoolean(autoclearKEY, false);
//normal private data
final Context con1 = this;
int dividend;String dataFixed;boolean tb;
private CheckBox myCBox, acBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerBoxes();
if(autoclear == true){
acBox.setChecked(true);
}else{
acBox.setChecked(false);
}
}
//check box listeners
public void addListenerBoxes(){
//instantiate boxes
acBox = (CheckBox) findViewById(R.id.chex2);
acBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//is acBox checked?
if (((CheckBox) v).isChecked()) {
edit.putBoolean(autoclearKEY, true).commit();
}else{
edit.putBoolean(autoclearKEY, false).commit();
}
}
});
myCBox = (CheckBox) findViewById(R.id.chex);
}
error message:
http://pastebin.com/5P2Mfwik
Change this line
SharedPreferences preferences = this.getSharedPreferences("us.mattmccoy.meanfind", Context.MODE_PRIVATE);
to
SharedPreferences preferences; = this.getSharedPreferences("us.mattmccoy.meanfind", Context.MODE_PRIVATE);
and put
preferences = this.getSharedPreferences("us.mattmccoy.meanfind", Context.MODE_PRIVATE);
in onCreate()
You are trying to use Context before establishing it with onCreate() so you are getting NPE on context. You will also want to move these lines
Editor edit = preferences.edit();
boolean autoclear = preferences.getBoolean(autoclearKEY, false);
into onCreate() after you initialize preferences or you will get another NPE since preferences will be null until you initialize it. So it should be something like
public class MainActivity extends Activity {
//saved data stuff needed
SharedPreferences preferences; //declare them
Editor edit;
//private data using saved data
String autoclearKEY = "us.mattmccoy.meanfind.AUTOCLEAR";
boolean autoclear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences; = this.getSharedPreferences("us.mattmccoy.meanfind", Context.MODE_PRIVATE);
Editor edit = preferences.edit(); //initialize them
boolean autoclear = preferences.getBoolean(autoclearKEY, false);
addListenerBoxes();
if(autoclear == true){
acBox.setChecked(true);
}else{
acBox.setChecked(false);
}
If this doesn't solve your problem then please post full logcat

Categories