Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save SharedPreferences files into custom dir or get default SharedPreferences dir

Is it possible to save SharedPreferences files into custom dir? Let's say into /data/data/package.name/my_prefs/.

Or is it possible to retrieve the directory SharedPreferences are saved by default to?

P.S. Hardcoding the path /data/data/package.name/shared_prefs/ is not the solution.

like image 438
a.ch. Avatar asked Nov 19 '11 15:11

a.ch.


1 Answers

Or is it possible to retrieve the directory SharedPreferences are saved by default to?

Yes.

This is basically the dataDir /shared_prefs which you can get from the ApplicationInfo object (which in turn you can get from the PackageManager). (Also, it might be the same as the "getFilesDir" dir you can get easily from Context itself? Not sure, didn't check that.)

From the source, starting with Context.getSharedPreferences (ContextImpl source):

public SharedPreferences getSharedPreferences(String name, int mode) {
        SharedPreferencesImpl sp;
        File prefsFile;
        boolean needInitialLoad = false;
        synchronized (sSharedPrefs) {
            sp = sSharedPrefs.get(name);
            if (sp != null && !sp.hasFileChangedUnexpectedly()) {
                return sp;
            }
            prefsFile = getSharedPrefsFile(name);
...

public File getSharedPrefsFile(String name) {
        return makeFilename(getPreferencesDir(), name + ".xml");
    }

private File getPreferencesDir() {
        synchronized (mSync) {
            if (mPreferencesDir == null) {
                mPreferencesDir = new File(getDataDirFile(), "shared_prefs");
            }
            return mPreferencesDir;
        }
    }

private File getDataDirFile() {
        if (mPackageInfo != null) {
            return mPackageInfo.getDataDirFile();
        }
        throw new RuntimeException("Not supported in system context");
    }

And "mPackageInfo" is an instance of LoadedApk:

public File getDataDirFile() {
        return mDataDirFile;
    }

mDataDirFile = mDataDir != null ? new File(mDataDir) : null;

 mDataDir = aInfo.dataDir;

And that brings us back to ApplicationInfo.

I'd say if you don't want to rely on the convention /data/data/<package_name>/shared_prefs then it should be safe to get the "dataDir" and rely on "shared_prefs" from there?

like image 192
Charlie Collins Avatar answered Oct 23 '22 04:10

Charlie Collins