I need some help getting a checkbox's state. Basically I want to get if a checkbox from an activity is checked then if it is, show some text on the main activity. I've read lots and lots of SO Q&As but nothing worked. I got this:
CheckBox show = (CheckBox) findViewById(R.id.checkBox);
public CheckBox getShow() {
return show;
}
So I'd use
CheckBox setty = Settings.getCheck();
on the other class. But I get an error:
Cannot resolve method 'getCheck()'
How can I do this? I need to get if it's on or off and display it on the main activity. Remember that I can't use Intents because I won't have a button to transition, the text and value must be always there on the main class.
you can use shared preference to store a checkbox check/uncheck value..and based on that value you can show text in your other activity.
here is the code:
public static final String MyPREFERENCES = "MyPrefs";
initialize shared preference in onCreate() method of first activity
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
CheckBox check1 = (CheckBox) view.findViewById(R.id.your_checkbox_id);
//now initialize listener for checkbox
check1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("checked", "1");
editor.commit();
} else {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("checked", "0");
editor.commit();
}
}
});
Now in another activity you just have to load the shared preference data and show message based on condition
public void Load_checkbox() {
//define MyPREFERENCES in other activity too- same as first activity
SharedPreferences shared = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (shared.getString("checked", "").equals("1")) {
Toast.makeText(getApplicationContext(), "CheckBox Checked " ,Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "CheckBox unchecked " ,Toast.LENGTH_LONG).show();
}
}
call this Load_checkbox() method in your second activity where u want to check the checkbox state of first activity
Related
So my question is how I can get the state of a Switch.
I have this Code:
notificationSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(notificationSwitch.isChecked()){
System.out.println("Checked");
SharedPreferences.Editor editor = getSharedPreferences("save", MODE_PRIVATE).edit();
editor.putBoolean("value", true);
editor.apply();
notificationSwitch.setChecked(true);
}else{
System.out.println("not checked");
SharedPreferences.Editor editor = getSharedPreferences("save", MODE_PRIVATE).edit();
editor.putBoolean("value", false);
editor.apply();
notificationSwitch.setChecked(false);
}
}
});
The state of the switch is saved in the Shared Preferences and if I start the app the Switch is on the same state as when I left the app. But when I start the app is should print checked or not checked but it doesn't print out anything
I will answer based on the title:
To get the state of the switch in onCreate():
//in onCreate:
SharedPreferences prefrences = getSharedPreferences("save", MODE_PRIVATE);
//false mean if not found set to false as default
boolean stateSwitch = prefrences.getBoolean("value",false);
//set state for switch
notificationSwitch.setChecked(stateSwitch);
//log the state
if(stateSwitch == true){
Log.d("TAG","checked");
}else{
Log.d("TAG","not checked");
}
UPDATE
keep your onclicklistener the same, and add the code I provided before your onclicklistener in onCreate:
1) when you turn switch on and leave activity and come back it must stay on.
2) when you turn switch off and leave activity and come back it must stay off.
3) if you do nothing leave activity and come back it must stay off.
I am creating an android application, I am displaying images from drawable folder based on the numbering, my activity start showing images from number 1 and I am using buttons to show next or previous image.
I am trying to save the value of image user was viewing while pressed back button using shared preferences. my code looks like this
private int currentPage = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
final Button btnNext = findViewById(R.id.btnNext);
final Button btnBack = findViewById(R.id.btnBack);
listOfObjects = getResources().getStringArray(R.array.object_array);
images = getResources().obtainTypedArray(R.array.object_image);
itemImage = (ImageView)findViewById(R.id.imgSpace);
final Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,R.layout.my_spinner, listOfObjects);;
spinnerAdapter.setDropDownViewResource(R.layout.my_spinner);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
itemImage.setImageResource(images.getResourceId(spinner.getSelectedItemPosition(), -1));
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
final ImageView img = findViewById(R.id.imgSpace);
PhotoView photoView = (PhotoView) findViewById(R.id.imgSpace);
img.setImageResource(getResources().getIdentifier("page_"+currentPage,"drawable",getPackageName()));
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(spinner.getSelectedItemPosition() < spinner.getAdapter().getCount()){
spinner.setSelection(spinner.getSelectedItemPosition()+1);
}
}
} );
}
currentPage is the variable which I want to save after pressing back button or to go to any other activity and also if user minimises the application, I want to pass it to main activity in order to show the extra button of resume activity and also to show the exact image the user was seeing before pressing the back button when user clicks on resume activity button.
I am using Chris Banes's photoview to show the image. I know how to pass variables and et them in PHP however android is new for me. ANy help would be appreciated.
SharedPreferences prefs = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE).edit();
editor.putInt("image", R.imageID).commit();
#Override
onBackPressed(){
image = prefs.getInt("image", defaultValue) //Default value is taken if the pref doesn't exist yet
}
onBackPressed() is called automatically by android when pressing the phone back button. You can call it manually:
onBackPressed();
I don't understand the question completely but you could write:
SharedPreferences prefs = getSharedPreferences("nameOFPref", MODE_PRIVATE);
private int currentPage = prefs.getInt("image", 1);
The way it works is it saves a file in nameOfPref in the "image" section so you get it back when the program launches. Here we put 1 as default value so the value it will take is 1 the first time you launch the program. You should write:
SharedPreferences.Editor editor = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE).edit();
editor.putInt("image", idOFImageCurrentlyVIewed).commit();
Later in the program each time the user changes image. So it will change the preference and will make sure that when you launch the program back currentImage will take the right value.
In android studio you can look at the file system of emulated phones. For preferences you need to go in Android/data/com.yourPackageName/preferences and you should see your file there if everything goes fine.
I have a problem with shared preferences for my Android app. It saves data and also retrieves but wont work with counter.
When I click the button, it increments by 0.0005 in TextView, so SharePref must be saved in button event. Now when I restart the app it retrieves it but now on clicking button it gets same as counter does. After restarting app then after clicking it gets back as counter starts. It means that shared preferences data is somehow lost after clicking button.
public class MainActivity extends AppCompatActivity {
Button btn1;
TextView t1;
float counter = 0;
float adding = (float) 0.0005;
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView)findViewById(R.id.textView);
sharedpreferences = getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
t1.setText(String.valueOf(sharedpreferences.getFloat("key",0)));
}
public void AdButton(View v) //Button Onclick
{
counter = counter+adding;
strCounter = Float.toString(counter);
t1.setText(strCounter);
sharedpreferences = getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putFloat("key", counter);
editor.commit();
}
}
As I understands from your words, you want to save counter value is Shared Preferences and retrieve it again when App starts then on button click, you will increment it and save it again in Shared Preference. correct?
Simply, what you did is when app starts, you show the saved value (if exists) on the text view but you don't keep it in counter! so counter is zero
you have to keep it in counter after retrieving, add this line in onCreate after or before showing the value on textview.
counter = sharedpreferences.getFloat("key",0);
You forgot to retrieve the value of counter before adding it again.
Just use this :
public void AdButton(View v) //Button Onclick
{
sharedpreferences = getActivity().getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
counter = sharedpreferences.getFloat("key",0);
counter = counter + adding;
String strCounter = Float.toString(counter);
t1.setText(strCounter);
editor.putFloat("key", counter);
editor.commit();
}
I have got a DialogActivity with a "do not show anymore" CheckBox.
What I need it to do is exactly like the CheckBox says. When the CheckBox is checked the Activity doesn't have to be displayed to the user anymore, no matter if the app is restarted or killed.
public class PopUpInfoActivity extends Activity {
static final String PREFS = "preference_file";
#Override
public void onCreate(Bundle state) {
setContentView(R.layout.popupinfo_layout);
CheckBox chk = (CheckBox) findViewById(R.id.dontshow_checkbox);
chk.setChecked(PreferenceManager.getDefaultSharedPreferences(this).getBoolean("value", false));
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//store isChecked to Preferences
SharedPreferences settings = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isChecked", false);
PreferenceManager.getDefaultSharedPreferences(PopUpInfoActivity.this).edit().putBoolean("value", isChecked).apply();
}
});
Intent intent = new Intent(PopUpInfoActivity.this, ChordsListActivity.class);
if (!chk.isChecked()) {
// run activity
super.onCreate(state);
} else {
startActivity(intent);
}
}
}
If I do it like this the App crashes.
If I replace the else with:
else {
onStop()
}
The code doesn't work as expected.
I would really appreciate if you could help me fix this problem!
EDIT:
This is what I have got in my ChordsListActivity, which is the activity that calls the PopUpInfoActivity but I do not get what I should put in my if() statement.
Intent legendaIntent = new Intent(ChordsListActivity.this, PopUpInfoActivity.class);
if(/*what's here?*/)
startActivity(legendaIntent);
In that MainActivity read your preference key (Show_Dialog), if it is true then launch PopUpInfoActivity otherwise launch ChordsListActivity.
The logic should be in the Mother Activity
In your PopUpInfoActivity you should only edit the preference key to false if the user checks out the ChekBox
To do so, please create a preferences.xml file under res/xml, inside this file you have to create a key (Boolean) that you will store inside the status of PopUpInfoActivity.Checkbox, the default will be (True).
here is an example
<CheckBoxPreference
android:key="Show_Dialog"
android:defaultValue="true" />
From your MainActivity you should read this value like this:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Boolean showDlg = sharedPref.getBoolean("Show_Dialog", true);
if the showDlg is true then you popup your dialog, otherwise continue what you want to do.
of course you need to change the value of Show_Dialog if the user checks the checkbox, you can do it like this:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor preferencesEditor = sharedPref.edit();
preferencesEditor.putBoolean("Show_Dialog", false);
preferencesEditor.commit();
in this way, you can be sure that your main activity will read the Show_Dialog as false next time the user launches your application
Good luck
Firstly, super.onCreate() must be the first call in any Activity's onCreate().
Secondly, store the value of the SharedPrefence in a boolean instead of directly setting the CheckBox, and use that before setContentView() to finish your current Activity and launch the next one if true. If not, carry on with the UI stuff and anything else you need.
I have some SwitchCompat in my Activity, I set the OnCheckedChangeListener to one of them but (using SharedPreferences), every time I start the Activity, the action of OnCheckedChangeListener is performed regardless of whether it is on or off (Which is very very bad for performance as the On state action is to run a shell script and show a SnackBar as it takes some time).
Here is a small piece of code...
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
//Private stuffs...
SwitchCompat play; //and many others
public static final String PREFS_NAME = "SwitchButton";
protected void onCreate(Bundle savedInstanceState) {
// ...
play = (SwitchCompat) findViewById(R.id.play_switch);
play.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Shell.SU.run("sh /data/data/br.com.packagename/play_on");
Snackbar snack_play_on = Snackbar.make(play, R.string.play_on, Snackbar.LENGTH_SHORT);
snack_play_on.show();
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onPlay", true);
editor.apply();
} else {
Shell.SU.run("sh /data/data/br.com.packagename/play_off");
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onPlay", false);
editor.apply();
Snackbar snack_play_off = Snackbar.make(play, R.string.play_off, Snackbar.LENGTH_SHORT);
snack_play_off.show();
}
}
});
play.setChecked(sharedPrefs.getBoolean("onPlay", false));
So... Every time a open the activity (ot the app itself) that Snackbar shows, and the linked action to the On state of the SwitchCompat runs.
This causes too many frames skip when loading the Activity (arround to 230 in a 1GB, 1.2GHz quad device). There is more then one Switch, four or five.
What should I do? Am I missing soomething or putting the code in the wrong place? Should I use other methods like OnResume, OnPause etc?
Calling setChecked() invokes the listener they same way a user click would.
I now handle setting up all checkboxes like this:
play = (SwitchCompat) findViewById(R.id.play_switch);
play.setOnCheckedChangeListener(null);
play.setChecked(sharedPrefs.getBoolean("onPlay", false));
play.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
...