0

I am really new to coding and mobile development. I am writting a mobile app for to do list

For each to-do-item, I stored it as a Map, and put them into an Arraylist myItems.

Now I want to save/retrieve myItems, to a local storage, so every time I reopen the file the previous data are still retained. Someone told me can save to a JSON file,

How can I achieve that? Thanks in advance.

Below are methods for my 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) {

   ...
    }
...
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Efan Du
  • 123
  • 2
  • 4
  • 14
  • Does this answer your question? https://stackoverflow.com/questions/29648630/save-arraylistcustom-object-to-local-storage – Rahul Raj Aug 27 '17 at 09:26
  • Yes, the most easy and dirty-quick way to save complex objects to local storage is saving them in json format in `SharedPreferences`. You need to use [Gson](https://github.com/google/gson) library to convert objects to json string and vice versa. You can use [this](https://github.com/fsilvestremorais/android-complex-preferences) library to implement this quick way of saving objects. – Melika Barzegaran Aug 27 '17 at 09:53

1 Answers1

0

First, you need to serialize your ArrayList to JSON. You could do that using the GSON library.

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

Now that you have a JSON string, you can save it to internal storage:

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());
}

For deserializing the JSON string to an ArrayList, you can use several libraries, such as the org JSON library or GSON. Then parsing the string becomes easy:

JSONObject jsonObj = new JSONObject(stringBuilder.toString());
Melika Barzegaran
  • 429
  • 2
  • 9
  • 25
checkmate711
  • 3,301
  • 2
  • 35
  • 45