Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 650
JesperN Avatar asked Dec 30 '16 07:12

JesperN


People also ask

Can we store HashMap in file?

The HashMap class in Java implements the Serializable interface so that its objects can be written or serialized to a file using the ObjectOutputStream. However, the output file it produces is not in the human-readable format and may contain junk characters.

What is a HashMap in Android?

A HashMap is a structure allowing one to store (key,value) items. A hash function pairs each key to an array index where the value will be stored.


1 Answers

 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();
        }
    }
}
like image 57
Praveen Avatar answered Oct 18 '22 10:10

Praveen