Android: how to get list of all preference xml's for my app and read them?

前端 未结 3 396
挽巷
挽巷 2020-12-16 04:16

how to get list of all application preferences for application,

1. I am saving shared preference in this manner

相关标签:
3条回答
  • 2020-12-16 04:52
    public class Preferences extends PreferenceActivity {
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // load the XML preferences file
            addPreferencesFromResource(R.xml.preferences);
        }
    }
    

    Then in your main class, you can refer to the preferences

    public class DrinkingBuddy extends Activity 
                               implements OnSharedPreferenceChangeListener {
    
        private int weight;
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    
            // register preference change listener
            prefs.registerOnSharedPreferenceChangeListener(this);
    
            // and set remembered preferences
            weight = Integer.parseInt((prefs.getString("weightPref", "120");
            // etc
        }
    
        // handle updates to preferences
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            if (key.equals("weightValues")) {
                weight = Integer.parseInt((prefs.getString("weightPref", "120");
            }
            // etc
        }
    }
    

    The saving of preference updates is handled for you.

    (Not too sure about public/private declarations!).

    0 讨论(0)
  • 2020-12-16 05:05

    Try this

        File prefsdir = new File(getApplicationInfo().dataDir,"shared_prefs");
    
        if(prefsdir.exists() && prefsdir.isDirectory()){
            String[] list = prefsdir.list();
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, android.R.id.text1,list);
            Spinner sp = (Spinner) findViewById(R.id.spinner1);
            sp.setAdapter(adapter);
    
        }
    

    //To get the selected item

    String item = (String) sp.getSelectedItem();
        //remove .xml from the file name
        String preffile = item.substring(0, item.length()-4);
    
        SharedPreferences sp2 = getSharedPreferences(preffile, MODE_PRIVATE);
        Map<String, ?> map = sp2.getAll();          
    
        for (Entry<String, ?> entry : map.entrySet()){
            System.out.println("key is "+ entry.getKey() + " and value is " + entry.getValue());
        }
    
    0 讨论(0)
  • 2020-12-16 05:09

    If you want to use reflection, there is an @hide function Context#getSharedPrefsFile(String name)

    So you would call

    Context#getSharedPrefsFile(String name).getParentFile() to get a reference to the shared_prefs dir

    0 讨论(0)
提交回复
热议问题