Consider following code be the settings page of a live wallpaper in Android:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="#string/livewallpaper_settings"
android:key="livewallpaper_settings">
<ListPreference
android:key="livewallpaper_testpattern"
android:title="#string/livewallpaper_settings_title"
android:summary="#string/livewallpaper_settings_summary"
android:entries="#array/livewallpaper_testpattern_names"
android:entryValues="#array/livewallpaper_testpattern_prefix"/>
<CheckBoxPreference android:key="livewallpaper_movement"
android:summary="#string/livewallpaper_movement_summary"
android:title="#string/livewallpaper_movement_title"
android:summaryOn="Moving test pattern"
android:summaryOff="Still test pattern"/>
</PreferenceScreen>
It shows a setting page and everything about showing the settings is ok. How can I save this settings and use them while creating the live wallpaper?
Also, is it true to read the settings in onCreate method or not?
I found the answer :
package ca.jvsh.livewallpaper;
import ca.jvsh.livewallpaper.R;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class LiveWallpaperSettings extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener
{
#Override
protected void onCreate(Bundle icicle)
{
super.onCreate(icicle);
getPreferenceManager().setSharedPreferencesName(LiveWallpaper.SHARED_PREFS_NAME);
addPreferencesFromResource(R.xml.livewallpaper_settings);
getPreferenceManager().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onResume()
{
super.onResume();
}
#Override
protected void onDestroy()
{
getPreferenceManager().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key)
{
}
}
this was the java class for the setting page.
and this is for reading the settings :
TestPatternEngine()
{
...
mPreferences = LiveWallpaper.this.getSharedPreferences(SHARED_PREFS_NAME, 0);
mPreferences.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(mPreferences, null);
}
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key)
{
mShape = prefs.getString("livewallpaper_testpattern", "smpte");
mMotion = prefs.getBoolean("livewallpaper_movement", true);
readColors();
}
Related
I have 2 file:
control_preferences.xml:`
<PreferenceCategory
android:title="#string/control_category">
<CheckBoxPreference
android:title="Debug Information ON/OFF"
android:defaultValue="false"
android:summary="Show debug information when ON"
android:key="checkboxPref" />
</PreferenceCategory>
`
SettingsActivity.java:
package com.sample;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
public static final String KEY_PREF_DEBUG = "checkboxPref";
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(KEY_PREF_DEBUG)) {
Toast.makeText(getApplicationContext(), "CLICK",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.preference_headers, target);
}
public static class ControlPrefsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// load the preferences from an XML resource
addPreferencesFromResource(R.xml.fragmented_control_preferences);
}
}}
I have 2 questions:
Why when selecting or deselecting Checkbox Toast doesn't display?
How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity.
1) Why when selecting or deselecting Checkbox Toast doesn't display?
Add below lines in on resume of your activity
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(prefs);
2)How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity?
Use below code to get value
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.getBoolean("key_value_given_in_preference_xml_file")
Use this instead of implementing interface
checkboxPref = (CheckBoxPreference) getPreferenceScreen().findPreference(your_key);
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
#Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
YOUR CODE
return false;
}
});
#Jawegiel
I insert this to:
public static class ControlPrefsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// load the preferences from an XML resource
addPreferencesFromResource(R.xml.fragmented_control_preferences);
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
#Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
Toast.makeText(getActivity().getApplicationContext(), "CLICK",
Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
and it works :)
Thank you both :)
#Jawegiel
what if I would use Toast like "Debug: " + "boolean from this actually changed checkbox" In MainActivity i read this boolean through code:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplication‌​Context());
boolean check = prefs.getBoolean("checkboxPref",false);
How read this boolean in in SettingsActivity same like in MainActivity?
I try through this code:
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
#Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
boolean check = checkboxPref.getSharedPreferences().getBoolean("checkboxPref",false);
Toast.makeText(getActivity().getApplicationContext(), "Debug " + check,
Toast.LENGTH_SHORT).show();
return false;
}
});
But now I can't unclick Checkbox or click if false :d
http://i.stack.imgur.com/vnfQt.png
As shown above From settings when I change the value of temprature units from metric to imperial and press back button my app got crash and showing below error
http://i.stack.imgur.com/dBeHk.png
SettingsActivity
package com.example.poo.sunshine;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
public class SettingsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(R.id.container, new MyPreferenceFragment())
.commit();
}
public static class MyPreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
addPreferencesFromResource(R.xml.pref_general);
// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
PreferenceManager.getDefaultSharedPreferences(getActivity()).registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference locationPref = findPreference(getString(R.string.pref_location_key));
Preference unitsPref = findPreference(getString(R.string.pref_units_key));
prefChanged(sharedPreferences, locationPref, key);
prefChanged(sharedPreferences, unitsPref, key);
}
private void prefChanged(SharedPreferences sharedPreferences, Preference pref, String key) {
if (sharedPreferences instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list (since they have separate labels/values).
ListPreference listPreference = (ListPreference) sharedPreferences;
int prefIndex = listPreference.findIndexOfValue(key);
if (prefIndex >= 0) {
pref.setSummary(listPreference.getEntries()[prefIndex]);
} else {
pref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
}
}
The problem is cause from the view of your Fragment is not yet attached to your SettingActivity.
To avoid this error, you can check with isAdded() before access views in your Fragment.
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(isAdded()){
Preference locationPref = findPreference(getString(R.string.pref_location_key));
Preference unitsPref = findPreference(getString(R.string.pref_units_key));
prefChanged(sharedPreferences, locationPref, key);
prefChanged(sharedPreferences, unitsPref, key);
}
}
Another solution and I would like to suggest as well.
You should register the preference changed listener in onViewCreated() in your Fragment. So that mean your Fragment is fully attached.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
PreferenceManager.getDefaultSharedPreferences(getActivity())
.registerOnSharedPreferenceChangeListener(this);
}
Hope this will work!
I need to update my app's widget every time the settings are changed by the user.
I have a settings activity:
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
public class SettingsActivity extends Activity implements SharedPreferences.OnSharedPreferenceChangeListener {
public static final String customIntent = "CUSTOM_SETTINGS_CHANGED";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new MainActivity.SettingsFragment())
.commit();
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Intent intent = new Intent();
intent.setAction(customIntent);
this.sendBroadcast(intent);
}
}
I've added that custom intent to the manifest:
<action android:name="CUSTOM_SETTINGS_CHANGED" />
But the widget is not updated immediately after the settings are changed. So my custom broadcast either is not sent or not received. What's wrong with my code?
// this part important in manifest declaration
package com.xmpls.onetwothree.abc;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
public class SettingsActivity {
public class SettingsActivity extends Activity implements
SharedPreferences.OnSharedPreferenceChangeListener {
// Change like this
public static final String CUSTOM_SETTINGS_CHANGED = "com.xmpls.onetwothree.abc.custompls";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction();
/* More code here. . .*/
}
/* And some here. . .*/
}
================================================================================
and in manifest U must registred ACTION like this:
<action android:name="com.xmpls.onetwothree.abc.CUSTOM_SETTINGS_CHANGED" />
I've used a different approach.
In my main activity I've added this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
<...>
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
Intent intent = new Intent();
intent.setAction(customIntent);
sendBroadcast(intent);
}
};
<...>
}
It seems that onSharedPreferenceChanged was never called for some reason. I don't know why but at least I've found a way to make this work.
Can anyone tell me what is wrong with this code. For some reason the OnSharedPreferencesChanged is not being called when changing the value. I am trying to check if the PIN entered is equal to 2 digits or no. But for it just doesnt work..
can anyone help me out.
Thanks.!
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.widget.Toast;
public class PrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
EditTextPreference editPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
this.editPreference = ((EditTextPreference) getPreferenceScreen()
.findPreference("userPass"));
Log.d("TAG","before sharedPreferenceChanged");
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#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) {
Log.d("TAG","In SharedPreferences");
if (sharedPreferences.getString("userPass", null).length() != 2) {
Log.d("TAG","lenght is less than 1");
Toast.makeText(this, "Pin has to be 2 digits only",
Toast.LENGTH_LONG).show();
this.editPreference.setText(null);
return;
} else {
Toast.makeText(this, "Pin set", Toast.LENGTH_LONG).show();
}
// TODO Auto-generated method stub
}
Try setting the setOnPreferenceChangeListener for your editPreference in onCreate(), put your validation code inside this callback.
Reading the docs, they say OnSharedPreferenceChangeListener is called when the shared preference is changed(is already changed). In the other hand the setOnPreferenceChangeListener is triggered "when this Preference is changed by the user (but before the internal state has been updated)"
package com.example.activitylifecycle;
import android.app.Application;
import android.content.res.Configuration;
import android.util.Log;
public class MyApplication extends Application {
static final String TAG = "MyApplication";
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
}
#Override
public void onLowMemory() {
super.onLowMemory();
Log.d(TAG, "onLowMemory");
}
#Override
public void onTerminate() {
super.onTerminate();
Log.d(TAG, "onTerminate");
}
Help me to understand this concept by adding some keys (Codes).
I am new to android, What are the purpose of using Application objects?
If you want to learn Android i have to recommend the google documentation:
there is also a description of the lifecycle and the application itself
http://developer.android.com/training/index.html
and her is also a tutorial to extends Application
http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/