user3549666 user3549666 - 2 months ago 9
Android Question

Confused on Reading SharedPreferences Without a PreferenceActivity

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()
.

Answer

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();
  }

`