Android儲存HashMap到File裡

儲存

   private void saveData() {
    FileOutputStream outputStream;
    try {
        HashMap map = new HashMap<>();
        map.put(NAME, edtName.getText().toString());
        map.put(AGE , edtAge.getText().toString());

        outputStream = getActivity().openFileOutput(filename , Context.MODE_PRIVATE); 
        ObjectOutput out = new ObjectOutputStream(outputStream);
        out.writeObject(map);
        outputStream.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

讀資料

 private void loadData(){
    try {
        FileInputStream fileIn = getActivity().openFileInput(filename);

        if(fileIn != null){

        ObjectInputStream in  = new ObjectInputStream(fileIn);
        HashMap map = (HashMap) in.readObject();

        edtName.setText(map.get(NAME));
        edtAge.setText(map.get(AGE));

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

你可能感兴趣的:(Android儲存HashMap到File裡)