4

I've written an app that has several hard-coded settings such as fontSize or targetDirectory. I would like to be able to change those type of settings on an infrequent basis.

SharedPreferences seems to be one way to go about it but I want to share this application and settings, and my phone is not rooted.

My application is a personal tool, and does not have a UI. It opens, does it's job, and then closes. I could create the equivalent of a Windows .ini file and read/write to it, but that seems clunky. Having the SharePreferences file located on the sdcard where I can reach it, instead of device memory, where I can't, seems like that would work.

I do not want to backup these preferences, just be able to edit them, or copy them to a new device.

Jim_Joat
  • 71
  • 7
  • SharedPreference files are xml files in internal storage. Of course you can copy them to external or removable storage. – greenapps Apr 09 '17 at 22:39
  • 1
    Possible duplicate of [How can I backup SharedPreferences to SD card?](http://stackoverflow.com/questions/10864462/how-can-i-backup-sharedpreferences-to-sd-card) – trooper Apr 10 '17 at 02:52

1 Answers1

2

By default SharedPreferences files are stored in internal storage. You can make a backup of it to SD card programmatically.

    File ff = new File("/data/data/"
             + MainActivity.this.getPackageName()
             + "/shared_prefs/pref file name.xml");

    copyFile(ff.getPath().toString(), "your sdcard path/save file name.xml");



private void copyFile(String filepath, String storefilepath) {
    try {
        File f1 = new File(filepath);
        File f2 = new File(storefilepath);
        InputStream in = new FileInputStream(f1);

        OutputStream out = new FileOutputStream(f2);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        System.out.println("File copied.");
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

You may replace it back when first start and backup it when application closed.

References: here

Community
  • 1
  • 1
Zarul Izham
  • 569
  • 5
  • 17
  • 2
    Zarul--thanks for answer, but I want to actively use the file, not back it up. My understanding is that I wouldn't have the permission to write the file back into the /data directory. – Jim_Joat Apr 10 '17 at 13:40