Show current SeekBarPreference value into ScreenPreference - java

what's a good way to show current value of SeekBarPreference into ScreenPreference.
I've tried to insert textview but the app crashes.
Any suggestions?
preferences.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SeekBarPreference
android:id="#+id/seekbar_pref"
android:key="seekbar_x"
android:title="Value"
android:defaultValue="1"
android:max="60"/>
</PreferenceScreen>
Preferences.java
public class Preferences extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Main.java
private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.e("SHARED", "VAL: " + sharedPreferences.getInt("seekbar_x",10));
}
};

In your onCreate method add this line at the end (after adding preferences):
SeekBarPreference pref = (SeekBarPreference) findPreference("seekbar_pref");
Then add the listener on it like this:
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int value = mSeekBarPreference.getProgress(); //or (int) newValue
//You can now use this value wherever you like:
pref.setSummary("Value: " + value);
return true;
}
});

Related

Optimize night mode system

I created a day/night mode switch system in my app. Currently, I use a PreferenceFragmentCompat + SharedPreference to display and save the switch selection.
This is my code:
public class PreferencesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
PreferencesFragment preferencesFragment = new PreferencesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.preferences_container, preferencesFragment).commit();
}
public static class PreferencesFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
#Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (isAdded()) {
if (sharedPreferences.getBoolean(getString(R.string.KEY_PREF_NIGHT_MODE), false)) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
}
}
On top of that, I use the following code in the OnCreate method of my main Activity:
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int mode = sharedPreferences.getBoolean(getString(R.string.KEY_PREF_NIGHT_MODE), false) ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO;
if (AppCompatDelegate.getDefaultNightMode() != mode)
AppCompatDelegate.setDefaultNightMode(mode);
The problem is that when I activate the dark mode and I restart the application, it will launch then restart in the onCreate. Isn't there a more optimal way to implement this system?
you could create BaseActivity where you set the night mode
abstract class BaseActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
}
}
and then extend all your Activites from BaseActivity
public class PreferencesActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
}
then your night mode would be set in every activity before setContentView and no relaunch would be occured
UPDATE
change
#Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
to
#Override
public void onStart() {
super.onStart();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
onStart is called before view is visible
UPDATE 2
here is the singleton to access SharedPreferences
public class SharedManager {
private static SharedManager instance;
private final SharedPreferences preferences;
private SharedManager() {
preferences = MyApplication.getAppContext().getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
}
public static SharedManager getInstance() {
if (instance == null) {
synchronized (SharedManager.class) {
if (instance == null) {
instance = new SharedManager();
}
}
}
return instance;
}
public SharedPreferences getPreferences() {
return preferences;
}
}
with call SharedManager.getInstance().getPreferences() you can get access to Preferences

Custom PreferenceDialogFragment Android

I am trying to implement my own EditTextPreferenceDialogFragmentCompat. I would like to check if the user enter an IP address in the text field. If it's not the case, the user should not be able to validate the dialog. I have successfully shown my custom PreferenceDialogFragmentCompat, but I cannot save the text value anymore!
public class SettingsActivity extends AppCompatActivity {
public static final String PREF_IP_KEY = "ipDs1242_2";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
...
*/
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new Preferences()).commit();
}
//A Fragment needs to be a public static class
public static class Preferences extends PreferenceFragmentCompat {
private EditTextPreference mIpModulePref;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(getClass().getSimpleName(), "onCreate() frag Prefrences");
}
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.preferences_app);
Log.e(getClass().getSimpleName(), "onCreateFragment()");
mIpModulePref = findPreference(PREF_IP_KEY);
mIpModulePref.setSummary("Addresse IP : " + mIpModulePref.getText());
mIpModulePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.e(getClass().getSimpleName(), "new pref saved"); //never called...
return true;
}
});
mIpModulePref.setOnBindEditTextListener(this);
}
//shows my custom dialog
#Override
public void onDisplayPreferenceDialog(Preference preference) {
if (getFragmentManager().findFragmentByTag(DialogPreferenceFragment.TAG) != null) {
return;
}
if (preference instanceof EditTextPreference && preference.getKey().equals(PREF_IP_KEY)) {
DialogPreferenceFragment dialogPreferenceFragment = DialogPreferenceFragment.newInstance(PREF_IP_KEY);
dialogPreferenceFragment.setTargetFragment(this, DialogPreferenceFragment.REQUEST_CODE);
dialogPreferenceFragment.show(getFragmentManager(), DialogPreferenceFragment.TAG);
} else {
super.onDisplayPreferenceDialog(preference);
}
}
}
//the custom dialog to show
public static class DialogPreferenceFragment extends EditTextPreferenceDialogFragmentCompat {
public static final int REQUEST_CODE = 0;
public static final String TAG = "DialogPreferenceFragment_tag";
private Context mContext;
private EditTextPreference mEditTextPreference;
private SharedPreferences prefs;
public static DialogPreferenceFragment newInstance(String key){
Bundle bundle = new Bundle();
bundle.putString(ARG_KEY, key);
DialogPreferenceFragment dialogPreferenceFragment = new DialogPreferenceFragment();
dialogPreferenceFragment.setArguments(bundle);
return dialogPreferenceFragment;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mContext = context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
}
#Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
Log.e(getClass().getSimpleName(), "restore pref IP");
mEditTextPreference = ((EditTextPreference) getPreference());
String txtValue = prefs.getString(mEditTextPreference.getKey(), ""); //reads the right value
mEditTextPreference.setText(txtValue);
}
#Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder);
builder.setMessage("Enter the IP address");
}
#Override
public void onDialogClosed(boolean positiveResult) {
if(positiveResult){
Log.e(getClass().getSimpleName(), "save pref IP");
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
editor.putString(mEditTextPreference.getKey(), mEditTextPreference.getText());
editor.commit();
String value = prefs.getString(mEditTextPreference.getKey(), ""); //DOESN'T SAVE THE VALUE !
Log.e(getClass().getSimpleName(), value);
}
}
}
}
I can read the right value in the the onBindDialogView() function, but I cannot save my value.
Do you have an idea of what I missed?
Thank you for your help.

Get text from EditTextPreference and save it

I am trying to build a settings menu, but I'm having some troubles...
I cant get the text from EditTextPreference
I cant insert it on my sharedPreferences file
Can I have some help?
Prefs Class
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences.Editor editor = sharedPreferences.edit();
contact1 = (EditTextPreference) findPreference("contact1");
editor.putString("contact1", String.valueOf(contact1)).commit();
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
Prefs XML
<?xml version="1.0" encoding="utf-8"?>
<EditTextPreference
android:title="Contact 1"
android:key="#+id/contact1"
android:summary="Enter your contact">
</EditTextPreference>
<EditTextPreference
android:title="Contact 2"
android:key="#+id/contact2"
android:summary="Enter your contact">
</EditTextPreference>
Get data on main activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
number1 = settings.getString("contact1", "");
number2 = settings.getString("contact2", "");
contact1 = "tel: " + number1;
contact2 = "tel: " + number2;
use these way...
public class AdvancePreferenceExample extends PreferenceActivity implements OnSharedPreferenceChangeListener{
private static final String KEY_EDIT_TEXT_PREFERENCE = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#Override
protected void onResume(){
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
updatePreference(KEY_EDIT_TEXT_PREFERENCE);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
updatePreference(key);
}
private void updatePreference(String key){
if (key.equals(KEY_EDIT_TEXT_PREFERENCE)){
Preference preference = findPreference(key);
if (preference instanceof EditTextPreference){
EditTextPreference editTextPreference = (EditTextPreference)preference;
if (editTextPreference.getText().trim().length() > 0){
editTextPreference.setSummary("Entered Name is " + editTextPreference.getText());
}else{
editTextPreference.setSummary("Enter Your Name");
}
}
}
}
}
here is sample

loadPreference() for preferenceActivity method throws exception first time app is installed

I am a newbie to android, so please be patient.
I am trying to learn preferences. I have an app that has a mainActivity, when the menu icon it's pressed a MyPreferenceActivity is shown. It allows the user setting some preferences related to a subject.
In my mainActivity I have a loadPrefernces method that works fine when the app is installed, but the first time it throws an error: unable to start activity component info[..] java.lang.NullPointerException
Here is my code:
MainActivity
public class MainActivity extends Activity {
public static final String PREFERENCE_FILENAME = "com.id11298775.exercise6_preferences";
SharedPreferences mSharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadPreferences(); // this cause the error
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, MyPreferenceActivity.class);
startActivity(i);
break;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
loadPreferences();
}
private void loadPreferences() {
mSharedPreferences = getSharedPreferences(PREFERENCE_FILENAME,
MODE_PRIVATE);
// Setting the textView related to the subject
TextView subjectTv = (TextView) findViewById(R.id.activitymain_favouritesubjectresult_tv);
subjectTv.setText(mSharedPreferences.getString("list_subject_pref",
null));
// Setting the TextView related to the URL
TextView urlTv = (TextView) findViewById(R.id.activitymain_handbookurlresult_tv);
urlTv.setText(mSharedPreferences.getString("et_subject_pref", null));
// Setting the TextView related to the times selected
TextView labTimeTv = (TextView) findViewById(R.id.activitymain_labtimeresult_tv);
// #SuppressWarnings("unchecked")
Map<String, ?> map = mSharedPreferences.getAll();
Object cs = map.get("list_times_pref");
labTimeTv.setText(cs.toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
this is my MyPreferenceActivity
public class MyPreferenceActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("list_subject_pref")) {
ListPreference preference = (ListPreference) findPreference(key);
CharSequence currText = preference.getEntry();
preference.setSummary(currText);
} else if (key.equals("et_subject_pref")) {
EditTextPreference preference = (EditTextPreference) findPreference(key);
String newUrl = preference.getText().toString();
preference.setSummary(newUrl);
} else if (key.equals("list_times_pref")) {
Set<String> selections = sharedPreferences.getStringSet(
"list_times_pref", null);
String[] selected = selections.toArray(new String[] {});
String listSelection = "";
for (int i = 0; i < selected.length; i++) {
listSelection += selected[i] + " ";
}
MultiSelectListPreference multi = (MultiSelectListPreference) findPreference(key);
multi.setSummary(listSelection);
} else if (key.equals("ringtonePref")) {
RingtonePreference preference = (RingtonePreference) findPreference("ringtonePref");
String strRingtonePreference = ((SharedPreferences) preference).getString("ringtonePref", "none");
Uri ringtoneUri = Uri.parse(strRingtonePreference);
Ringtone ringtone = RingtoneManager.getRingtone(this, ringtoneUri);
String name = ringtone.getTitle(this);
preference.setSummary("select " + name);
}
}
}
here is logcat:
I think that the first time the app is installed there are no preference set, therefore the error, but I can't figure out a good way to prevent the exception.
Anybody can please help me?

listener sharedpreferences

I've a problem with this code. I want keep preferences values in my app but I've problem with the listener. Does not work, its does not save new values. Any idea about error(s)?
EDIT: onResume() works because when I open an activity on my app and close it, the value of sharepreferences is correct. Dialogs and activities does not keep values.
public void onCreate(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String listpref) {
if(!preferencesChanged)preferenze();
}
};
sp.registerOnSharedPreferenceChangeListener(listener);
There are some buttons and other info activities called by intents.
A TextView that show a value from array and nothing.
public void onPause() {
super.onPause();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.unregisterOnSharedPreferenceChangeListener(listener);
protected void onResume() {
super.onResume();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String listpref) {
preferencesChanged = true;
}
};
sp.registerOnSharedPreferenceChangeListener(listener);
protected void onStop(){
super.onStop();
if(preferencesChanged){
//Update the app
preferenze();
}
public void preferenze()
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
CheckboxPreference = prefs.getBoolean("checkboxPref", true);
ListPreference = prefs.getString("listpref", "");
Others variables and most if/else.
Preferences.xml:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String listpref) {
protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(this); sp.registerOnSharedPreferenceChangeListener(this); }
I think, you are missing registerOnSharedPreferenceChangeListener

Categories

Resources