I am new to Android and I am trying to handle the settings according to the instructions in
http://developer.android.com/guide/topics/ui/settings.html
I used the fragment based solution as the one directly in the activity was deprecated:
public class SettingFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingFragment())
.commit();
}
}
The settings are correctly displayed in the app, yet when I try to retrieve their values with:
sharedPref= PreferenceManager.getDefaultSharedPreferences(Dashboard.dashboard);
startDayTime=sharedPref.getString(SettingsActivity.day_switch_start, "");
startNightTime=sharedPref.getString(SettingsActivity.night_switch_start, "");
it complaints that values day_switch_start and night_switch_start might not be resolved. In fact, when I explode the values recognized by SettingActivity, I get a long list of capitalized strings part of the standard settings, but not my own strings.
Those were in fact just entered in the xml file and linked from the SettingFragment, so I doubt context Dashboard.dashboard I passed has any reference to it. Yet there are no instructions on how to pass the settings references to a specific context and moreover they say that the settings should be available from anywhere. I am stuck, any solution?
Thanks,
Please check the reference you linked again, especially the Reading Preferences section. When you set the preference key to, e.g., day_switch_start then you must use the same String when reading the preference, e.g.,
startDayTime=sharedPref.getString("day_switch_start", "");
You can also store the preference key to a constant like in the linked example:
public class SettingsActivity extends PreferenceActivity {
public static final String KEY_PREF_DAY_SWITCH_START = "day_switch_start";
// ...
and then access it when reading the preference:
startDayTime=sharedPref.getString(SettingsActivity.KEY_PREF_DAY_SWITCH_START, "");
Edit: I'm not sure what Dashboard.dashboard should represent but this should work:
sharedPref= PreferenceManager.getDefaultSharedPreferences(this);
Related
If I have a Preference-Activity or -Fragment I can provide a preference.xml file to build my PreferenceScreen and show it via addPreferenceFromResource(R.xml.preference)
Changed values can then be retrieved by PreferenceManager.getDefaultSharedPreferences(Context)
I'm just wondering if it is possible to take other than the default Preferences for my Fragment.
I want to have a PreferenceFragment that is able to store its Preferences (provided via xml) in Preferences I can retrieve via context.getSharedPreferences("customPrefName", Context.MODE_PRIVATE)
but I couldn't find something in the xml like
<PreferenceScreen android:prefName="customPrefName">...
If you want to have a custom preference xml file, you need to set preference name before adding it to screen from xml in your PreferenceFragment class.
public class CustomNamePreferenceFragment extends PreferenceFragment {
private static final String PREF_FILE_NAME = "custom_name_xml";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager preferenceManager = getPreferenceManager();
preferenceManager.setSharedPreferencesName(PREF_FILE_NAME);
addPreferencesFromResource(R.xml.prefs);
... //rest of the code
}
}
Note : You need to set shared preference name just after the super call of onCreate() and before calling addPreferencesFromResource() method.
I'm getting a compiler error cannot resolve method findPreference when I try to intialize an OnSharedPreferencesChanged listener in my MainActivity. According to the answer here:
findPreference() should be called from a class implementing PreferenceActivity interface
but I don't understand what the code to do this would be. How can I get rid of the compiler error and successfully set listeners for preference changes?
MainActivity.java
public class MainActivity extends FragmentActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
//Test preference menu
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("pref_wood")) {
Preference woodPref = findPreference(key); //COMPILER ERROR HERE
MainActivity.getGLSurfaceView().setTexture("");
// Set summary to be the user-description for the selected value
woodPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
}
}
findPreference is a method which is part of both PreferenceFragment and PreferenceActivity - these are the Fragments/Activities that actually show your Preference screen (the activity is deprecated and you should be using the PreferenceFragment).
You're trying to use it in your MainActivity. This doesn't work because the Preference objects don't actually exist on this screen (they exist in another activity that usually have a PreferenceFragment as part of it). If you need to get access to a preference value of a preference in an activity that is not your preference screen, use SharedPreferences, something like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getBoolean(R.bool.saved_high_score_default);
boolean wood = sharedPref.getBoolean(pref_wood, defaultValue);
You can check out the documentation for further examples.
If your MainActivity is supposed to be a screen that shows settings, then you should probably rename it and include a preference fragment inside of it.
I believe you're also going to run into trouble with setSummary because the Preference is not part of this activity, it's part of the activity where you actually modify the preferences. setSummary is used to update the actual UI of the Preference so that if you, for example, select one of three values when using a list preference, it shows the value you just selected on the screen.
Because I want an AppCompat Action Bar on all of my settings submenus, I had to implement a workaround and my Settings Activity extends AppCompatActivity, not PreferenceActivity. I'm using a PreferenceFragment in the activity to handle the preferences, and each PreferenceScreen has its own xml file, which the PreferenceFragment switches out for each submenu in the settings. All of this was necessary to get the Action Bar to stay put through all of my submenus.
I'm trying to read a string value from the shared preferences file from within my MainActivity, and I've tried three different methods for getting that information, none of which have worked:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String btSelectPref = sharedPref.getString(getString(R.string.bt_select_key), "");
,
SharedPreferences sharedPref = getSharedPreferences(name, MODE_PRIVATE);
String btSelectPref = sharedPref.getString(getString(R.string.bt_select_key), "");
and
SharedPreferences sharedPref = getPreferences(MODE_PRIVATE);
String btSelectPref = sharedPref.getString(getString(R.string.bt_select_key), "");
Here is the relevant section of my preferences.xml:
<PreferenceCategory
android:title="Bluetooth"
android:key="pref_bt">
<Preference
android:title="Select Bluetooth Device"
android:key="#string/bt_select_key"
android:defaultValue="0">
</Preference>
</PreferenceCategory>
This should fill the btSelectPref string with a "0", but it's always empty when I test it. I have included PreferenceManager.setDefaultValues(this, R.xml.preferences, false); in onCreate in my MainActivity, so the default values should be set.
I'm not sure which of these methods I should be using since I have multiple resource files for my settings, but none of them seem to be working for me. In the case of getSharedPreferences(name, MODE_PRIVATE), I have no idea what the name parameter should be referencing, since I've never named my shared preferences file.
EDIT: It turns out my issue was not related to getting values from the shared preferences file. I just had the wrong xml tag on the preference I was trying to check the value of. I changed it from a generic <Preference> tag to a <ListPreference> and my code started working with PreferenceManager.getDefaultSharedPreferences().
What you want to do and what you are doing differs. If you just want to put default shared preference for a key then consider this example. If your whole activity has just one shared pref file then you need not specify any name. It will automatically get it.
public MainActivity extends AppCompatActivity {
SharedPreferences mPrefs;
int test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter);
mPrefs = this.getPreferences(Context.MODE_PRIVATE);
test = mPrefs.getInt("pref_bt_select", 0);}
}
For the above example you can define the key and default value in your strings.xml and then you can refer to it while looking for the prefs you want.
Hey I have used AppCompat for my preference screen too.I did this because I wanted to use Vintage Chroma and this was the only way. But I am able to use PreferenceManager.getDefaultSharedPreference() without any errors.
Also if you want to use default shared preferences in the Fragment you can use :
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
Here is my full code :
public class PreferencesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager()
.beginTransaction()
.replace(android.R.id.content, new PreferencesScreen())
.commit();
ActionBar toolbar = getSupportActionBar();
if (toolbar != null) {
toolbar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public static class PreferencesScreen extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_xml);
}
}
}
Here is my code snippet for MAinActivity
Just the initial part where I set the default text theme.
`public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
AutoCompleteTextView mytextview;
public static String[] list;
ArrayList<String> recent = new ArrayList<String>();
public int recent_index = 0;
Menu mMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
/*Setting default theme.*/
SharedPreferences Sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int firstRun=Sp.getInt("firstRun",0);
if(firstRun==0)
{
SharedPreferences.Editor editor=Sp.edit();
editor.putInt("paragraphFontColor", Color.parseColor("#ffffff"));
editor.putInt("headingFontColor",Color.parseColor("#DE5246"));
editor.putInt("subheadingFontColor",Color.parseColor("#597d5e"));
editor.putInt("hyperlinksFontColor",Color.parseColor("#A5D8F5"));
editor.putInt("bodyColor",Color.parseColor("#2b2b2b"));
editor.putString("paragraphFont","PrintClearly.otf");
editor.putString("headingFont","PrintBold.otf");
editor.putString("subheadingFont","PrintBold.otf");
editor.putString("hyperlinkFont","PrintBold.otf");
editor.putString("paragraphFontStyle","normal");
editor.putString("headingFontStyle","normal");
editor.putString("subheadingFontStyle","normal");
editor.putString("hyperlinkFontStyle","normal");
editor.putString("actionBarColor","#597d5e");
editor.putString("paragraphFontSize","20px");
editor.putString("headingFontSize","30px");
editor.putString("subheadingFontSize","20px");
editor.putString("hyperlinkFontSize","20px");
editor.putString("firstRun",0);
editor.commit();
}
`
I have an app which uses preferenceScreen (checkboxes) for the user to turn on and off certain options. The preferences fragment which inflates the xml file looks like this:
public class BrandsFragment : PreferenceFragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
AddPreferencesFromResource (Resource.Menu.brandPrefs);
var prefs = PreferenceManager.GetDefaultSharedPreferences(this.Activity);
}
}
This works fine and i can successfully change the preferences.
However, what i need to do is get the preferences from the OnCreate method in my Main activity (not fragment).
This is what i have tried:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var prefs = PreferenceManager.GetDefaultSharedPreferences(this);
wantGeneral = prefs.GetBoolean ("checkbox_preference_general", true);
Console.WriteLine ("Pref is " + wantGeneral);
SetContentView(Resource.Layout.NavigationDrawer);
.......
}
But the 'wantGeneral' preference always comes back true, regardless of the checkbox being checked. It's clear that from my Activity, it's not successfully grabbing the preferences.
What do i need to do in order to get the preferences from the Activity?
It appears that it was me not thinking it through properly. I needed to move the code into OnResume() or somewhere else that gets called after i make change to the preferences in my settings page. That way it pulls in the latest settings.
Users can add projects in my app and I have a PreferenceFragment for settings of the projects.
This is my Fragment:
public class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.project_settings);
}
}
And my Activity:
public class Settings extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}
The availabal settings for each project are identical but the data should be saved per project (e.g. the project name). So how can I save the preferences to my sqlite database?
Putting this here as none of the other questions/answers on this topic were satisfactory, and I just finished precisely this functionality (connect Preferences in a PreferenceFragment to the database).
Basically, you should set android:persistent="false" for each Preference in the XML. You should then load values into the Preferences manually on onCreate(), and use setOnPreferenceChangeListener() to do database value-updating and Preference summary field updating. You may also have to extend some existing Preferences to allow them to be set with values manually, as some of them (e.g. the RingtonePreference) do not have methods to set their values -- they just get them internally from SharedPreferences.
The answer is a Preference.OnPreferenceChangeListener and some magic inside the onPreferenceChange method.