How to write an ArrayList into a text file in Android App

So I have an ArrayList of some data which is needed for the app, and I don’t have any problem to load the data from a text file named MyData.txt and store it in an ArrayList. But the problem is, after some changes in the data which is stored in loaded ArrayList by the user I want the data that stored into the MyData.txt get updated with the new ArrayList. I write some codes for that but it doesn’t seem to work and my txt file is not getting updated after I press the save button, it just jumped out of the app.

 public void SaveData(List<Four> list) throws IOException {
    FileOutputStream file = openFileOutput("MyData.txt", MODE_PRIVATE);
    OutputStreamWriter outputFile = new OutputStreamWriter(file);
    for(int i=0 ; i<list.size() ; i++){
        outputFile.write(list.get(i).first+";"+list.get(i).second+";"+list.get(i).second+";"+list.get(i).fourth+"n");
    }
    outputFile.flush();
    outputFile.close();
}

I have an ArrayList with the data type of Four ( Four is a class which includes “String(showed as first), String(showed as second, int (showed as third), int (showed as fourth)) the output of the code should be stored in a text file, for example, if My list just had one index like “John Brown 1938494 0” my text file should look like “John;Brown;1938494;0”.

if you need to know anything else about the code just tell me. thanks for your time.

Answer

You can use google gson.

    class Four {
    String first,second;
    int third,fourth;
    public Four()
    {

    }
}
 //save_array(your_context,"MyData.txt",your_array)
void save_array(Context contxt,String file_name,ArrayList<Four> testes)
{
    Gson gson = new Gson();
    String json = gson.toJson(testes);
    String root = contxt.getExternalFilesDir(null).getAbsolutePath() + "/arrays";


    File file = new File(root);
    file.mkdirs();
    try {
        File out_file = new File(file, file_name);
        if(out_file.exists()){
            out_file.delete();
        }
        FileWriter writer = new FileWriter(out_file,true);
        writer.append(json);
        writer.flush();
        writer.close();
    }catch (Exception ex)
    {

    }
}
ArrayList<Four> saved_array(Context contxt, String file_name) throws IOException {
    String path = contxt.getExternalFilesDir(null).getAbsolutePath() + "/arrays/"+file_name;


    Gson gson = new Gson();
    BufferedReader br = new BufferedReader(new FileReader(path));
    return gson.fromJson(br, new TypeToken<List<Four>>(){}.getType());


} 

you can call as Remember to request for storage permissions

Leave a Reply

Your email address will not be published. Required fields are marked *