Search code examples
androidbackupsharedpreferences

Get all SharedPreferences names and all their keys?


I'm making backup program, that saved the phone SharedPreferences data into a file of my own structure. But I don't know how to list them all, which I need:

For example, 2 program saved their SharedPreferences with names "Program A" and "Program B". I need to obtains thay String array contain these 2 names. Then, I use getSharedPreferences with "Program A", I need to get all keys that program has saved.

Is it really possible?

EDIT1: I DON'T know what programs/activities on the phone. I want to get ALL the keys that every programs saved. It just like you back up all your phone data, but only SharedPreferences values.

For example: Your phone has 10 programs, each creates a SharedPreferences named Program 1 to Program 10 (but of course, whatever name they want). And I would like to obtain all these Program 1 to Program 10 String. Then, if Program 1 has 5 keys called Key 1 to Key 5, I want to obtain these keys name.

EDIT2: According to NikolaMKD guide, this is what I've done so far, but the list return all programs, with "No Preferences" at all line, even at the first, I saved the SharedPreferences with my activity:

public class Test extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences preferences = getSharedPreferences("Test", 1);
        // No matter what name is: Test or the package name
        Editor editor = preferences.edit();
        editor.putInt("TestKey", 0);
        editor.commit();

        List<ResolveInfo> Temp = 
            getPackageManager().queryIntentActivities(
                    new Intent(Intent.ACTION_MAIN, null)
                    .addCategory(Intent.CATEGORY_LAUNCHER), 0);
        String[] App = new String[Temp.size()];
        for (int i = 0; i < Temp.size(); i++) {
            App[i] = Temp.get(i).activityInfo.name;
            FileReader reader = null;
            try {
                reader = new FileReader("/data/data/"
                        + App[i] + "/shared_prefs/" + App[i] + "_preferences.xml");
            } catch (FileNotFoundException e) {
                reader = null;
            }
            if (reader != null)
                App[i] += " (Have Prefereces)";
            else
                App[i] += " (No Prefereces)";
        }
        setListAdapter(new ArrayAdapter<String>(this, R.layout.main, App));
    }



}

Solution

  • Get all the _preferences.xml from

    /data/data/(package)/shared_prefs/(package)_preferences.xml

    Parse the XML, in the XML there is name for every key. I might misunderstood your question