0

I have a .txt file in ExternalStorageDirectory() in Android. This file contains 10 sentence line by line. I want to read each sentence one by one. And then show it on EditText when every button click. I found only all file reading codes. I don't want this. How can I do that? Here is my little code:

enter cod private String Load() {
    String result = null;;
    String FILE_NAME = "counter.txt";
    //if (isExternalStorageAvailable() && isExternalStorageReadOnly()) {
        String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "Records";
        File file = new File(baseDir, FILE_NAME);

        String line = "";
        StringBuilder text = new StringBuilder();

        try {
            FileReader fReader = new FileReader(file);
            BufferedReader bReader = new BufferedReader(fReader);

            while( (line = bReader.readLine()) != null  ){
                text.append(line+"\n");
            }
            result = String.valueOf(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
    //}
    return result;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Gianna
  • 11
  • 6

1 Answers1

0

All Load() does is reads the file and returns it as a String. From here, you have a few options.

1). Convert the result to an array of Strings using String.split('\n'), and grab the next value when you click the button. Here's a quick example:

int counter = 0;
String file = Load();
String[] lines = file.split("\n");

button.onClicked() {
    editText.setText(lines[counter++]);
}

2). Declare the buffered reader as a class member, so you can call readLine() inside the button's onClicked() method. This way, it will only read one line of the file when someone clicks the button, instead of reading the whole file in Load().

JTG
  • 8,587
  • 6
  • 31
  • 38