I'm in the middle of making an app and I'm running into a road block.
Basically I have a checkbox... If the checkbox is checked, it is supposed enable the entry of text in an edit text preference, and use that value. But here's where the problem lies... If the box is unchecked it uses the value in the EditTextPreference. If the box is checked, it uses the hard coded value.
Part of my activity:
private void loadURI()
{
PreferenceManager.setDefaultValues(this, R.xml.settings, true);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("default_uri", false)){
String defaultURI = getString(R.string.dream_uri);
this.mWebView.loadUrl(defaultURI);
}
else {
String customURI = settings.getString("custom_uri", "");
this.mWebView.loadUrl(customURI);
}
}
Settings.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Backdrop Settings" >
<CheckBoxPreference
android:title="Use Custom Backdrop URL"
android:id="#id/checkBox1"
android:key="default_uri"
android:defaultValue="true"/>
<EditTextPreference
android:title="Custom Backdrop URL"
android:summary="Tap here to enter custom URL"
android:id="#id/editText1"
android:defaultValue="Enter Custom URL here"
android:key="custom_uri"
android:dependency="default_uri" />
<CheckBoxPreference
android:title="Use a Custom Slideshow Period?"
android:key="slide_duration"
android:defaultValue="false"/>
<ListPreference
android:title="Slideshow Duration"
android:summary="How long should each slide be displayed?"
android:key="list_duration"
android:dependency="slide_duration"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Other">
<Preference
android:title="Test Dream"
android:summary="Tap here to test the dream"
android:key="testDream" />
<Preference
android:title="About"
android:key="AboutApp"
android:summary="About this app" />
</PreferenceCategory>
</PreferenceScreen>
And my Preferences activity:
public class mollySettings extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
Preference button = findPreference("testDream");
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.android.systemui", "com.android.systemui.Somnambulator");
startActivity(intent);
return true;
}
});
Preference about = findPreference("AboutApp");
about.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg1) {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.death2all110.flogging.molly", "com.death2all110.flogging.molly.About");
startActivity(intent);
return true;
}
});
}
}
Thanks in advance, and please let me know if there is anything else you need
Got it figured out.
I added an exclamation point to the if statement. So the loadURI method is now:
private void loadURI()
{
PreferenceManager.setDefaultValues(this, R.xml.settings, true);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (!settings.getBoolean("default_uri", false)){
String defaultURI = getString(R.string.dream_uri);
this.mWebView.loadUrl(defaultURI);
}
else {
String customURI = settings.getString("custom_uri", "");
this.mWebView.loadUrl(customURI);
}
}
Instead of:
private void loadURI()
{
PreferenceManager.setDefaultValues(this, R.xml.settings, true);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("default_uri", false)){
String defaultURI = getString(R.string.dream_uri);
this.mWebView.loadUrl(defaultURI);
}
else {
String customURI = settings.getString("custom_uri", "");
this.mWebView.loadUrl(customURI);
}
}
Related
In the app there is two radiobuttons and each buttons has its own value that is first radiobutton has value of "2" and second radiobutton has the value of "4". Now i successfully implemented the shared preference in order to save the value by clicking the radiobutton. But there is one thing is missing which is if i select radiobutton 1 and if i close the app and again open the app then the radiobutton 1 is not selected. I also tried to add the radiobutton.setChecked but it get crash. Below is the xml and java code.
custom_dialog.xml
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp">
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioGroup" />
</ScrollView>
method0.xml
<resources>
<integer-array name="method0">
<item>2</item>
</integer-array>
</resources>
method1.xml
<resources>
<integer-array name="method1">
<item>4</item>
</integer-array>
</resources>
CustomDialog.java
public class CustomDialog extends AppCompatDialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
LayoutInflater layoutInflater=getActivity().getLayoutInflater();
final View view=layoutInflater.inflate(R.layout.custom_dialog,null);
RadioGroup radioGroup=view.findViewById(R.id.radioGroup);
final int[] num0=getResources().getIntArray(R.array.method0);
final int[] num1=getResources().getIntArray(R.array.method1);
RadioButton radioButton0=new RadioButton(getActivity());
RadioButton radioButton1=new RadioButton(getActivity());
radioButton0.setText("A");
radioButton0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int method=num0[0];
SharedPreferences sharedPreferences=getActivity().getSharedPreferences("METHOD",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("key", method);
editor.apply();
}
});
radioButton0.setPadding(0,50,0,50);
radioButton0.setTextSize(17);
radioButton0.setTypeface(null, Typeface.BOLD);
radioButton0.setChecked(Update("key")); //Here this line it is getting crashed
radioButton1.setText("B");
radioButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int method=num1[0];
SharedPreferences sharedPreferences=getActivity().getSharedPreferences("METHOD",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("key", method);
editor.apply();
}
});
radioButton1.setPadding(0,50,0,50);
radioButton1.setTextSize(17);
radioButton1.setTypeface(null, Typeface.BOLD);
radioGroup.addView(radioButton0);
radioGroup.addView(radioButton1);
builder.setView(view)
.setTitle("Select Any Methods")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
private boolean Update(String key){
SharedPreferences sharedPreferences=getActivity().getSharedPreferences("METHOD",Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(key,false); //Here this line it is getting crashed
}
}
MainActivity.java
btnMethod.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog(); //this will open the dialog along with two radiobuttons
}
});
private void openDialog() {
CustomDialog customDialog=new CustomDialog();
customDialog.show(getSupportFragmentManager(),"Custom Dialog");
}
Logcat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nabil.myapplication, PID: 17062
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Boolean
at android.app.SharedPreferencesImpl.getBoolean(SharedPreferencesImpl.java:326)
at com.nabil.myapplication.CustomDialog.Update(CustomDialog.java:295)
at com.nabil.myapplication.CustomDialog.onCreateDialog(CustomDialog.java:69)
I am not much aware of the android codes, However, if I just go through your error, then it is coming because there is no parent-child relationship between the two classes Integer and boolean.
It is because you are storing an integer in the shared preferences and then trying to retrieve a Boolean.
I suggest storing the value of the radio button like so:
editor.putBoolean("radioButton0", radioButton0.isChecked());
...
editor.putBoolean("radioButton1", radioButton1.isChecked());
EDITED:
Instead of using
editor.putInt("key", method);
Use:
editor.putBoolean("radioButton0", radioButton0.isChecked());
AND
Instead of using
radioButton0.setChecked(Update("key"));
Use:
radioButton0.setChecked(Update("radioButton0"));
This should work like you want it to.
I am new at programing in Java and I am taking a course of Android application. I am building a button inside an activity. But when I exit the activity, the button changes to it's original state. I know I am not doing anything to save its state, but how do I do it?
Here is the xml file (only the button part):
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Catch"
android:id="#+id/button"
android:onClick="toggleCatch" />
And here is toggleCatch:
private boolean isCaught = false;
#SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
Button button = findViewById(R.id.button);
if (isCaught) {
button.setText("Catch");
isCaught = false;
} else {
button.setText("Release");
isCaught = true;
}
}
What could I do to make it work?
you should store the data that indicate on it state in some place:
1. SQLlite
2. Server
3. SharedPreference
and then when you create the activity you set the state of the btn based on the data you loaded.
if you do it just for practice, I believe that the sharepreference will be just fine.
https://developer.android.com/training/data-storage/shared-preferences
to store any data locally in the sharedPreference:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", trueOrFalse);
editor.commit();
to get the saved data:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean stateBtn = sharedPref.getBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", defaultValueForExTrue);
sharedPref.getBoolean can be used also for sharedPref.getString, sharedPref.getInt Etc..
hope that helped..
My recommendation for you is to read about the subjects above.(SQLlite, SharedPreference)
You need to save button state in persistent storage; there are several types of persistent storage that Android supports, like SharedPreference, DataBase, internal/external storage File... The most appropriate for your question is the SharedPreference as it stores small data.
To achieve that in your code sample
public static final String PREFS_NAME = "PREFS_NAME";
public static final String BUTTON_STATUS = "status";
private boolean isCaught = false;
#SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
Button button = findViewById(R.id.button);
if (isCaught) {
button.setText("Catch");
isCaught = false;
} else {
button.setText("Release");
isCaught = true;
}
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(BUTTON_STATUS, isCaught);
editor.apply();
}
And you need to retrieve the value again from the shared preference when the app is launched, so in your activity onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
isCaught = prefs.getBoolean(BUTTON_STATUS, false);
if (isCaught) {
button.setText("Release");
} else {
button.setText("Catch");
}
}
I don't understand how preferences work.
I have a preferences activity and one field on it:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key = "#string/pr_rest_service_url"
android:title = "#string/rest_service_url"
android:summary = "%s"
android:shouldDisableView="false"
android:selectable="true"
android:enabled="true"
android:defaultValue="543543543"
/>
</PreferenceScreen>
In preference activity i use this code to edit it:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
String editTextPrefKey = getString(R.string.pr_rest_service_url);
EditTextPreference restUrlTExtEdit = (EditTextPreference) findPreference(editTextPrefKey);
restUrlTExtEdit.getEditText().setInputType(InputType.TYPE_CLASS_TEXT);
restUrlTExtEdit.setSummary(restUrlTExtEdit.getText());
restUrlTExtEdit.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(newValue.toString());
return true;
}
});
Preference saveButton = findPreference(getString(R.string.preference_save_button));
saveButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
finish();
return true;
}
});
}
}
And its works. Works nice.
Now i want to get preferense from another parts of application. I put this code in MainActivity:
String key = this.getString(R.string.pr_rest_service_url);
SharedPreferences mSharedPreferences = getSharedPreferences(key, Context.MODE_PRIVATE);
String g = mSharedPreferences.getString(key, null);
And got null.
So how gonna work with preferences?
Or i made mistake on ths start and should not use PreferenceActivity as settings screen? Or preferenses binded to activity?
So how can i get
UPDATE
I tried
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String name = sp.getString("myKey", "");
But got empty string.
Update: Use this then:
SharedPreferences yourOutputdata =
context.getSharedPreferences("YourKEY", MODE_PRIVATE); // Save as YourKEY in the Activity which you're passing data to this one ...
Because of this:
String key = this.getString(R.string.pr_rest_service_url);
You are actually getting string from resource file and saving it to preference which I believe this causes the null.
Try this:
To save:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("key","your text-data here");
editor.apply();
And to get:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("key", "");
🚩Get Android Shared Preferences from default shared preferences in java language:-
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences.getString("your_key", null);
Hope this works...😊
I have a preference activity in which I have a PreferenceCheckBox.
My preference activity:
package com.tjs.balr;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class SettingsActivity extends PreferenceActivity{
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource( R.xml.preferences);
}
}
My checkbox:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Audio">
<CheckBoxPreference
android:id="#+id/checkSound"
android:summary="Turn sounds on or off"
android:defaultValue="true"
android:title="Sounds"
android:key="soundPref"
/>
</PreferenceCategory>
</PreferenceScreen>
In my main activity I try to get the value of my checkbox using:
private void showUserSettings() {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
musicPlaying = sharedPrefs.getBoolean("checkSound", true);
if(musicPlaying){
Toast.makeText(this, "music is turned on", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "music is turned off ", Toast.LENGTH_SHORT).show();
}
}
A LOT of people here on stackoverflow describe musicPlaying = sharedPrefs.getBoolean("checkSound", true); as the way to get the value of the checkbox, but in my case it stays true. Mainly because I say the default value of checkSound is true. Am I forgetting something in order to change the value of my PreferenceCheckBox? To my understanding of an PreferenceActivity all data is saved automatically, is this correct?
In getBoolean(key, defaultValue) , you need to pass the Key not the id.
You get always true because he dont find the CheckBox with checkSound as key so it return the default value (true in your case).
To fix that, just change
musicPlaying = sharedPrefs.getBoolean("checkSound", true);
to
musicPlaying = sharedPrefs.getBoolean("soundPref", true);
My EditTextPreference is this:
<EditTextPreference
android:title="Name"
android:summary="namepreferences"
android:inputType="text"
android:dialogTitle="name"
/>
in my PreferencesActivity:
namePref = (EditTextPreference)getPreferenceManager().findPreference("namepreferences");
well so far no problem.. now, i have a service with a notification. My goal is pass the namePref value in the Title of the notification.. I wrote this in the service:
SharedPreferences sp = PreferenceManager.getDefaultPreferences(this);
String name;
#Override
public void onCreate() {
name = sp.getText("namepreferences", "NA");
}
and i insert name in the title of notification but the app crashes sayng that name is null.. I can't solve..
Change to
SharedPreferences sp;
String name;
#Override
public void onCreate() {
super.onCreate();
sp = PreferenceManager.getDefaultPreferences(getApplicationContext());
name = sp.getText("namepreferences", "NA");
}