Search code examples
javaandroidfileinputstreaminternal-storage

Saving to Android Internal Storage


At the moment i'm trying to save a response to the internal storage in the phone. Everything works fine up until i try and retrieve the data again. When i log out the retrieved data it only logs out one small section of the response and the rest isn't there. Ive tried deleting the file and calling it again just incase it was using an old one.

Saving Code

try {
     String response = apiResponse.getRawResponse();
     Log.e("Response", response);

     FileOutputStream userInfo = openFileOutput("personal_profile", MODE_PRIVATE);
     userInfo.write(response.getBytes());
     userInfo.close();

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

Retrieving Code

 String response = "";

    try {
        FileInputStream fis = getActivity().openFileInput("personal_profile");
        DataInputStream isr = new DataInputStream(fis);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        line = response;

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.e("Saved File", response);

Any kind of suggestions would be great!


Solution

  • REASON

    The problem was that the line variable is assigned again in every iteration

    Try this:

     String response = "";
    
    try {
        FileInputStream fis = getActivity().openFileInput("personal_profile");
        DataInputStream isr = new DataInputStream(fis);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        line = response;
    
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    CHANGE LAST LINE

    Log.e("Saved File", sb.toString());