0

I am trying to save each visited URL in a .txt file. It works fine, however, every new URL replaces the older one.

1) How do i add URL's (on top, Not bottom) ?

2) How do i add a one line space between each URL?

MainActivity.java

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
    super.onPageStarted(view, url, favicon);
    // don't hide URLBar on welcome screen

    // save to history.txt
    HistoryHelper file = new HistoryHelper(view.getContext());
    file.writeToSD(url.toString());
}

HistoryHelper.java

public class HistoryHelper {

    String TAG = "MyFile";
    Context context;

    public HistoryHelper(Context context) {
        this.context = context;
    }

    public Boolean writeToSD(String text) {
        Boolean write_successful = false;
        File root = null;
        try {
            // check for SDcard
            root = Environment.getExternalStorageDirectory();
            Log.i(TAG, "path.." + root.getAbsolutePath());

            // check sdcard permission
            if (root.canWrite()) {
                File fileDir = new File(
                        Environment.getExternalStorageDirectory() + "/AVD/");
                fileDir.mkdirs();

                File file = new File(fileDir, "History.txt");
                FileWriter filewriter = new FileWriter(file);
                BufferedWriter out = new BufferedWriter(filewriter);
                out.write(text);
                out.close();
                write_successful = true;
                Toast.makeText(context, "success!", Toast.LENGTH_LONG).show();
            }
        } catch (IOException e) {
            Log.e("ERROR:---",
                    "Could not write file to SDCard" + e.getMessage());
            write_successful = false;
            Toast.makeText(context, "operation failed!", Toast.LENGTH_LONG)
                    .show();
        }
        return write_successful;
    }
}
0

1 Answer 1

1

Open file in append mode

FileWriter fileWriter = new FileWriter (file,  true) ;

Use BufferedWriter, you are opening file each time when URL get accessed. Try to minimise disk i/O overhead.

Sign up to request clarification or add additional context in comments.

3 Comments

what is "disk i/O overhead"?
For every URL accessed you are creating a new object of historyHelper and opens file each time, so try to use one object and use that reference only
Like pointed out you could e.g. make the method writeToSD static and the Toast you could also create in the onPageStarted method depending on the return value of the writeToSD method. So it is easier reuse, maintain and you don't need to create a HistoryHelper object each time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.