Malfunction
Malfunction

Reputation: 1334

Saving String Input on Android

Right, I've been trying to find a solution to this for a good while, but it's just not working for some reason.

In short, what I want to do is save every input String the user inputs into a file. Every time the activity is created again, I want to re-input these strings into a new instance of an object.

This code is what I use to create the file and read info from it, used in the onCreate() method of activity

    try {

        String brain = "brain";
        File file = new File(this.getFilesDir(), brain);
        if (!file.exists()) {
            file.createNewFile();
        }      

        BufferedReader in = new BufferedReader(new FileReader(file));
        String s; // This feeds the object MegaAndroid with the strings, sequentially 
        while ((s = in.readLine()) != null) {
            MegaAndroid.add(s);
        }
        in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

After that, every time the user inputs some text, the strings are saved onto the file:

    try {

        String brain = "brain";
        File file = new File(this.getFilesDir(), brain);
        if (!file.exists()) {
            file.createNewFile();
        }

    BufferedWriter out = new BufferedWriter(new FileWriter(file));
    out.write(message); // message is a string that holds the user input
    out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

For some reason, however, every time the application is killed, the data is lost. What am I doing wrong?

EDIT: Also, if I were to access this file from another class, how can I?

Upvotes: 0

Views: 207

Answers (2)

Grambot
Grambot

Reputation: 4514

As we discussed in the commend section the chief problem with the code is that your execution of FileWriter occurred prior to your FileReader operation while truncating the file. For you to maintain the file contents you want to set the write operation to an append:

BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
out.write(message);
out.newLine();
out.close();

However, if every entry on the EditText is received then shipped into the file you'll just be writing data byte after byte beside it. It is easy to get contents similar to

This is line #1This is line #2

Instead of the desired

This is line #1
This is line #2

which would be corrected by having the BufferedWriter pass a newline after each write to the file.

Upvotes: 1

draksia
draksia

Reputation: 2371

This is what I do for file reading.

try{

        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
        dir.mkdirs();

        Log.d(TAG,"path: "+dir.getAbsolutePath());
        File file = new File(dir, "VERSION_FILENAME");

        FileInputStream f = new FileInputStream(file);

        //FileInputStream fis = context.openFileInput(VERSION_FILENAME);
        BufferedReader reader = new BufferedReader(new InputStreamReader(f));

        String line = reader.readLine();
        Log.d(TAG,"first line versions: "+line);
        while(line != null){
            Log.d(TAG,"line: "+line);
            //Process line how you need 
            line = reader.readLine();
        }

        reader.close();
        f.close();
    }
    catch(Exception e){
        Log.e(TAG,"Error retrieving cached data.");

    }

And the following for writing

try{

        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
        dir.mkdirs();
        File file = new File(dir, "CONTENT_FILENAME");

        FileOutputStream f = new FileOutputStream(file);

        //FileOutputStream fos = context.openFileOutput(CONTENT_FILENAME, Context.MODE_PRIVATE);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(f));

        Set<String> keys = Content.keySet();

        for(String key : keys){

            String data = Content.get(key);
            Log.d(TAG,"Writing: "+key+","+data);

            writer.write(data);
            writer.newLine();
        }

        writer.close();
        f.close();

    }
    catch(Exception e){
        e.printStackTrace();
        Log.e(TAG,"Error writing cached data.");

    }

You can use the private mode if you don't want the rest of the world to be able to see your files, but it is often useful to see them when debugging.

Upvotes: 1

Related Questions