Checkbox passing of action on reopening of the app - java

I have stored the checkbox value(check/uncheck) using shared preference,but I face problem while passing the action of checkbox on/after closing and reopening the app.Explantion: A button in different actvity hides/shows on clicking the checkbox(i.e check=shows & uncheck= hides) working correctly. when I close the app and reopen the checkbox stays checked but button is not appearing
checkbox code saved using shared preference
final CheckBox checkBox = (CheckBox) findViewById(R.id.add_fb);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
checkBox.setChecked(preferences.getBoolean("checked",false));
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedValue = isChecked;
editor.putBoolean("checked", isChecked);
editor.apply();
}
});
}
I tried to implement onStart() for passing data by providing if-else condition
#Override
protected void onStart() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
super.onStart();
if(checkBox.isChecked()) {
editor.putBoolean("checked", true);
editor.apply();
}else{
editor.putBoolean("checked", false);
editor.apply();
}
}
This is where i am passing the data once the checkbox is checked
#Override
public void onBubbleClick(BubbleLayout bubble) {
Intent in = new Intent(MainActivity.this, PopUpWindow.class);
in.putExtra("yourBoolName", isCheckedValue );
startActivity(in);
}

Instead of sending 'isCheckedValue' in 'onBubbleClickMethod'
try this -
in.putExtra("yourBoolName",preferences.getBoolean("checked",false));

Related

How can I display info from sharedPreferences after the activity or app gets closed?

I have put some information that I want to be displayed even after my app or activity gets closed. I have a function display and if I call it in onCreate() or onStart() my app crashes.
public void display() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo",
Context.MODE_PRIVATE);
mText1.setText(sharedPref.getString("mText1", ""));
}
Here's how the data gets saved
public void savemMed1() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mText1", addMed.getText().toString());
editor.apply();
Toast.makeText(this, "Added", Toast.LENGTH_LONG).show();
}
This is the line that does not fit in the picture:
java.lang.RuntimeException: Unable to start activity ComponentInfo{corina_holom.com.medplannerapp/corina_holom.com.medplannerapp.Reminder}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
This is my first time programming in java and android studio and I'm having trouble finding tutorials that help. I'm not sure how I should change this or if I should use onStart()
This is the Code from the activity in which I want the info displayed:
public class Reminder extends AppCompatActivity {
public TextView mText1, mText2, mText3;
private EditText addMed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
defineButtons();
}
public void defineButtons() {
findViewById(R.id.mB1).setOnClickListener(buttonClickListener);
findViewById(R.id.mB2).setOnClickListener(buttonClickListener);
//findViewById(R.id.mB3).setOnClickListener(buttonClickListener);
}
private View.OnClickListener buttonClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.mB1:
addMed = (EditText) findViewById(R.id.addMed);
mText1 = (TextView) findViewById(R.id.mText1);
mText1.setText(addMed.getText());
savemMed1();
break;
case R.id.mB2:
addMed = (EditText) findViewById(R.id.addMed);
mText2 = (TextView) findViewById(R.id.mText2);
mText2.setText(addMed.getText());
break;
}
}
};
public void savemMed1() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mText1", addMed.getText().toString());
editor.apply();
Toast.makeText(this, "Added", Toast.LENGTH_LONG).show();
}
}
The problem is that by the time you use setText your textview is not initialised. Make sure you do findViewById before you do setText. The best way is to do it first thing in onCreate. And of course make sure that the id is the same as in the layout.

How SharedPreferences with UpdateUI?

I am a noob on developing android apps. I want to ask. How my PreferenceActivity want to Update without back to MainActivity and goto PreferenceActivity again. In this, i give some feature to change the Theme of PreferenceActivity. This is my PreferenceActivity:
public class SettingsPreference extends PreferenceActivity
{
SwitchPreference themeSwitch;
String myPref = "preferences";
SharedPreferences.Editor editor;
String summary;
int theme;
#Override
public void onCreate(Bundle savedInstanceState)
{
// TODO: Implement this method
final SharedPreferences.Editor editor = getSharedPreferences(myPref, MODE_PRIVATE).edit();
final SharedPreferences prefs = getSharedPreferences(myPref, MODE_PRIVATE);
final String summary = prefs.getString("stringSummary", "Default theme");
final int theme = prefs.getInt("intTheme", (android.R.style.Theme_DeviceDefault_Light));
setTheme(theme);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_preference);
themeSwitch = (SwitchPreference) findPreference("switchTheme");
themeSwitch.setSummary(summary);
if (themeSwitch != null) {
themeSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference arg0, Object isOnObject) {
boolean isThemeOn = (Boolean) isOnObject;
if (isThemeOn) {
Toast.makeText(SettingsPreference.this, "Theme Dark ON", Toast.LENGTH_SHORT).show();
editor.putString("stringSummary", "Theme Dark ON");
editor.putInt("intTheme", (android.R.style.Theme_DeviceDefault));
editor.apply();
themeSwitch.setSummary(summary);
} else {
Toast.makeText(SettingsPreference.this, "Theme Dark OFF", Toast.LENGTH_SHORT).show();
editor.putString("stringSummary", "Theme Dark OFF");
editor.putInt("intTheme", (android.R.style.Theme_DeviceDefault_Light));
editor.apply();
themeSwitch.setSummary(summary);
}
return true;
}
});
}
}
}
If you change the Activity layout you just have to restart it.
Try to add this at the end of onPreferenceChange().
if you're in API11+, call in an Activity.
this.recreate();
Otherwise, we just have to finish the activity and start it again with the same intent.
Intent intent = getIntent();
finish();
startActivity(intent);
If you have update every 20 seconds for example , This is code :
import android.os.Handler;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//update UI
}
},2000);
Put this in a function and re-call in run .

It is possible to use SharedPreferences to set Newgame and Continue to latest activity

i have a question here that is possible to make sharedpreference set Newgame and Continue to latest activity?
i had 4 activity, menu.class, levelone.class, leveltwo.class, levelthree.class
i will explain with my menu.class code
public class menu extends Activity {
public static final String PREF_LEVEL = "Level";
public static final String PREF_IS_SET ="isSet";
public static final String PREF_LIFES = "Lifes";
int level;
Button newgame, continues, continuelocked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.menu);
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
// Check wether the pref is set or not.
if (pref.getBoolean(PREF_IS_SET, false)) {
// The prefs is set. Do some game logic here. Like checking for level.
if (pref.getInt(PREF_LEVEL,0) == 0) {
// Reset the level
resetPrefs(pref);
}
else {
//Do nothing at all.
}
}
else {
// if it's not set, just create it.
resetPrefs(pref);
}
//i got error on this newgame line
newgame=(Button)findViewById(R.id.buttonnewgame);
newgame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
pref.putInt(PREF_LEVEL,0);
}
});
}
private void resetPrefs(SharedPreferences pref) {
SharedPreferences.Editor editor = pref.edit();
editor.putInt(PREF_LIFES, 6);
editor.putInt(PREF_LEVEL, 0);
editor.putBoolean(PREF_IS_SET,true);
editor.commit();
}
//to saved the current level and if button continue clicked it will open the latest activity, but i dont know the complete code so i use this
public void onResume() {
super.onResume();
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
level = pref.getInt("Level", 0);
if(level == 0)
{
Intent i =new Intent(menu.this, levelone.class);
startActivity(i);
}
if(level == 1)
{
Intent i =new Intent(menu.this, leveltwo.class);
startActivity(i);
}
if(level == 2)
{
Intent i =new Intent(menu.this, levelthree.class);
startActivity(i);
}
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Level", level);
editor.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
in code line of i got 2 error
newgame=(Button)findViewById(R.id.buttonnewgame);
newgame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
pref.putInt(PREF_LEVEL,0);
}
});
and this is,
Multiple markers at this line
- The method putInt(String, int) is undefined for the type
SharedPreferences
- Cannot refer to the non-final local variable pref defined in an
enclosing scope
- Line breakpoint:aselectmenu [line: 63] - resetPrefs(SharedPreferences)
can anyone help me to fix this code problem?
and how to set continues button when clicked, will continue to latest activity that i had play?
Change this line
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
to this
final SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
Then you will need to access the SharedPreference.Editor to actually put the integer you want
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("PrefName", VALUE).commit();

Android saving state of checkbox if exit app

I have 5 checkboxs and when they are clicked they set a boolean in an abstract class to true or false using a onCheckedChangeListener. Example:
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
{
if(isChecked)
{
CheckboxData.checked = true;
}
else if(!isChecked)
{
CheckboxData.checked = false;
}
}
});
However when I leave the app and return the checkboxes are not clicked anymore, yet the boolean values are still true. How can I make the app remember that the check boxes are clicked.? Should I just check the boolean values in the main activity onCreate and set the checkboxs to checked or not then or is there a better/faster way to make the app remember the checkboxs states?
Just added this in the main activities onCreate method:
if(CheckboxData.checked)
{
CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
checkbox.setChecked(true);
}
But it does nothing
when Activity get destroyed check the checkbox state if true , and add the checkbox state in shared Preference
#Override
public void onDestroy() {
if(CheckboxData.checked){
SharedPreferences prefs = getSharedPreferences("private preference", Context.MODE_PRIVATE);
prefs.edit()
.putBoolean("CheckboxData",true)
.commit();
}
super. onDestroy();
}
And when Activity is launched back, In onCreate check for the checkbox state in preference and if true enable the checkbox
SharedPreferences prefs = getSharedPreferences("private preference", Context.MODE_PRIVATE);
boolean isChecked = prefs.getBoolean("CheckboxData",false);
if(isChecked)
checkBoxView.setChecked(true)

NullPointerException on SharedPreferences in Button OnClick

I'm trying to update a shared preference of whether or not a user has checked a box to not display a welcome screen anymore. I access my shared preferences my onClick listener for a button. I'm getting a Null Pointer Exception and I don't know how to fix it?
Here is my code....
public class WelcomeScreenActivity extends Activity {
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcomescreen);
final Button button = (Button) findViewById(R.id.welcomecontinue);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) findViewById(R.id.welcomecheckbox);
if(cb.isChecked()){
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference
Intent intent = new Intent(WelcomeScreenActivity.this, MainActivity.class);
startActivity(intent);
} else if(!cb.isChecked()){
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, false);
editor.commit(); // Very important to save the preference
Intent intent = new Intent(WelcomeScreenActivity.this, MainActivity.class);
startActivity(intent);
}
}
});
}
}
Can anyone shed some light into this?
SharedPreferences mPrefs;
You have never initialized it. Although you are using it
mPrefs.edit();
Do do something like:
SharedPreferences mPrefs = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
Before using it.
You are never setting mPrefs to anything s calling mPrefs.edit() will throw a NullPointerException

Categories

Resources