JesperN
JesperN

Reputation: 77

How to saving a HashMap to a file in Android?

I'm trying to save user settings to a file, from where I can read the later. But I cant get it to work properly. I've tried reading up on this, but I'm still having problems.

Map<String, String> userSettings = new HashMap<>();

public void updateUserSettings(){

        userSettings.clear();

        userSettings.put("item0", item0);
        userSettings.put("item1", item1);
        userSettings.put("item2", item2);
        userSettings.put("item3", item3);
        userSettings.put("item4", item4);
        userSettings.put("item5", item5);
        userSettings.put("item6", item6);
        userSettings.put("item7", item7);


        userSettings.put("i0", Float.toString(i0));
        userSettings.put("i1", Float.toString(i1));
        userSettings.put("i2", Float.toString(i2));
        userSettings.put("i3", Float.toString(i3));
        userSettings.put("i4", Float.toString(i4));
        userSettings.put("i5", Float.toString(i5));
        userSettings.put("i6", Float.toString(i6));
        userSettings.put("i7", Float.toString(i7));

        userSettings.put("huvudMaskin", huvudMaskin);
        userSettings.put("minorMaskin1", minorMaskin1);
        userSettings.put("minorMaskin2", minorMaskin2);

        userSettings.put("maskinTid", Float.toString(maskinTid));
        writeSettings();
    }



public void writeSettings() {
    try
    {
        FileOutputStream fos = context.openFileOutput("test.ser", Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(userSettings);
        oos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


public void readSetttings() {
    try
    {
        FileInputStream fileInputStream = new FileInputStream(context.getFilesDir()+"test.ser");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        Map myHashMap = (Map)objectInputStream.readObject();
        userSettings = null;
        userSettings = myHashMap;
    }
    catch(ClassNotFoundException | IOException | ClassCastException e) {
        e.printStackTrace();
    }
    executeSettings();
}

I have both read and write rights to the app.

Im not getting anything out of this. I've checked the hashmap, and it works as intended. I have also tried a lot of different approaches, and the only thing I managed to get working was saving strings to a .txt file.

Upvotes: 5

Views: 3513

Answers (4)

Nitin Puri
Nitin Puri

Reputation: 1

If it is only primitives that you want to store then you should be using SharedPreferences which Android provides out of the box.

public static final String PREFS = "usersettings";

@Override
protected void onCreate(Bundle b){
   .....

   // read user settings on start
   SharedPreferences settings = getSharedPreferences(PREFS, 0);
   int someId = settings.getInteger("someId", 0);
   setSomeId(id);
}

@Override
protected void onStop(){

  .....

  SharedPreferences settings = getSharedPreferences(PREFS, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putInteger("someId", mSomeId);

  // commit changes on exit
  editor.commit();
}

Upvotes: 0

Praveen
Praveen

Reputation: 737

 private String subFolder = "/userdata";
private String file = "test.ser";

public void writeSettings() {
    File cacheDir = null;
    File appDirectory = null;

    if (android.os.Environment.getExternalStorageState().
            equals(android.os.Environment.MEDIA_MOUNTED)) {
        cacheDir = getApplicationContext().getExternalCacheDir();
        appDirectory = new File(cacheDir + subFolder);

    } else {
        cacheDir = getApplicationContext().getCacheDir();
        String BaseFolder = cacheDir.getAbsolutePath();
        appDirectory = new File(BaseFolder + subFolder);

    }

    if (appDirectory != null && !appDirectory.exists()) {
        appDirectory.mkdirs();
    }

    File fileName = new File(appDirectory, file);

    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    try {
        fos = new FileOutputStream(fileName);
        out = new ObjectOutputStream(fos);
        out.writeObject(userSettings);
    } catch (IOException ex) {
        ex.printStackTrace();
    }  catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (fos != null)
                fos.flush();
            fos.close();
            if (out != null)
                out.flush();
            out.close();
        } catch (Exception e) {

        }
    }
}


public void readSetttings() {
    File cacheDir = null;
    File appDirectory = null;
    if (android.os.Environment.getExternalStorageState().
            equals(android.os.Environment.MEDIA_MOUNTED)) {
        cacheDir = getApplicationContext().getExternalCacheDir();
        appDirectory = new File(cacheDir + subFolder);
    } else {
        cacheDir = getApplicationContext().getCacheDir();
        String BaseFolder = cacheDir.getAbsolutePath();
        appDirectory = new File(BaseFolder + subFolder);
    }

    if (appDirectory != null && !appDirectory.exists()) return; // File does not exist

    File fileName = new File(appDirectory, file);

    FileInputStream fis = null;
    ObjectInputStream in = null;
    try {
        fis = new FileInputStream(fileName);
        in = new ObjectInputStream(fis);
        Map<String, String> myHashMap = (Map<String, String> ) in.readObject();
        userSettings = myHashMap;
        System.out.println("count of hash map::"+userSettings.size() + " " + userSettings);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (StreamCorruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }finally {

        try {
            if(fis != null) {
                fis.close();
            }
            if(in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 8

Nadimibox
Nadimibox

Reputation: 1444

Change these lines :

public void  readSetttings(){
    String path=context.getFilesDir() + File.seprator + "test.ser";
    if(! new File(path).exists() ){

        //throw NullPointerException ;
        //return;
        /*
        *you can choose one of these
        *pay attention : when choose NullPointerException you shold add throws Exceptions on your method
        */
    }
    try{
        FileInputStream fileInputStream =context.openFileInput("test.ser");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        Map myHashMap = (Map)objectInputStream.readObject();

        userSettings = myHashMap;
   }catch(ClassNotFoundException | IOException | ClassCastException e) {
       e.printStackTrace();
   }
   executeSettings();
}

Upvotes: 0

GhostCat
GhostCat

Reputation: 140427

Your problem is very simple: you are using two different file names when writing the data resp. reading it.

FileOutputStream fos = context.openFileOutput("test.ser", Context.MODE_PRIVATE);

vs.

FileInputStream fileInputStream = new FileInputStream(context.getFilesDir()+"test.ser");

And, most likely, your reading code did throw an IOException at you, telling you something about trying to open a file that doesn't exist.

Thus, the real take-away/answer here: read those exception messages very carefully. Typically, they tell you exactly what the problem is!

Upvotes: 0

Related Questions