商店&a​​mp;检索HashMap / Map对象列表到Local Storage

时间:2017-08-27 09:12:25

标签: android json hashmap local-storage

我对编码和移动开发真的很陌生。我正在写一个移动应用程序来做列表

对于每个待办事项,我将其存储为地图,并将它们放入 Arraylist myItems。

现在我想将myItems保存/检索到本地存储,所以每次重新打开文件时,仍保留以前的数据。有人告诉我可以保存到 JSON 文件,

我怎样才能实现这一目标?提前致谢。

以下是我的MainActivity FYI的方法。

public class MainActivity extends AppCompatActivity {

//define variables
ListView listview;
ArrayList<Map<String,Object>> myItems=new   ArrayList<Map<String,Object>>();
SimpleAdapter adapter;
EditText addItemEditText;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //use "activity_main.xml" as the layout
    setContentView(R.layout.activity_main);

    listview = (ListView) findViewById(R.id.listview);

    //Create an adapter for the list view using Android's built-in item layout
     adapter = new SimpleAdapter(this,myItems,android.R.layout.simple_list_item_2,
            new String[]{"Name","Time"},new int[]{android.R.id.text1,android.R.id.text2});


    //connect the listview and the adapter
    listview.setAdapter(adapter);


    //Below two examples of how the item look like 
    Map<String,Object> item1 = new HashMap<String,Object>();
        item1.put("Name","Item1");
        item1.put("Time","Time1");
        myItems.add(item1);
        Map<String,Object> item2 = new HashMap<String,Object>();
        item2.put("Name","Item2");
        item2.put("Time",null);
        myItems.add(item2);

    //set up a list view listener
    setupListViewListener();

}

public void CreatNewActivity(View view) {

   ...
    }
...

1 个答案:

答案 0 :(得分:0)

首先,您需要将ArrayList序列化为JSON。您可以使用GSON库来执行此操作。

ArrayList<String> yourArrayList = new ArrayList<String>();
String jsonStr = new Gson().toJson(yourArrayList);

现在你有一个JSON字符串,你可以将它保存到内部存储:

FileOutputStream outputStream;
String fileName = "jsonStorage.txt";
try {
  outputStream = openFileOutput(fileName , Context.MODE_PRIVATE);
  outputStream.write(jsonStr.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}

In order to read the JSON and deserialize it, here are the steps:
Read the file:
        InputStream inputStream = context.openFileInput(fileName);

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String jsonString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (stringBuilder = bufferedReader.readLine()) != null ) {
                stringBuilder.append(stringBuilder );
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (Exception e) {
        Log.e(TAG, "File read error: " + e.toString());
}

要将JSON字符串反序列化为ArrayList,您可以使用多个库,例如org JSON libraryGSON。然后解析字符串变得容易:

JSONObject jsonObj = new JSONObject(stringBuilder.toString());