Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

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

how to get list of all application preferences for application,

1. I am saving shared preference in this mannerActivity to save key value pair in desired preference xml

2. I know that they are in data/data/app_packagename/shared_prefs Preference Xml's shared_pref folder


3. THE PROBLEM: But how to get list of all preference xml files in a spinner enter image description here

and read each preference, i searched in SO, but i did not found any help regarding this, how to do read all preference xml files in my application directory and access the preferences?

P.S: I am aware of SharedPreference.getAll();, will be enough to read once i get the file?

I have wrote in bits(Rough Code), it give error when tried to run, here is the implemented method

void getList()
{
  //will be invoked from onCreate to populate spinner,yes spinner is already binded
   PackageManager m = getPackageManager();
        String s = getPackageName();
        try {
            PackageInfo p = m.getPackageInfo(s, 0);
            s = p.applicationInfo.dataDir;
        } catch (NameNotFoundException e) {
            Log.w("yourtag", "Error Package name not found ", e);
        }
        Log.i("dir", s=s+"/shared_prefs");
     //is this write way, how to proceed from here
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...