5

i am trying to read data from a textfile "temp.txt" which is in my raw folder and displaying the contents of the file on the text view "text" whenever a button "button" is clicked, but my app crashes while doing so, there is quite a possibility that i am doing it in a wrong way because i am new to android and java programming. i am pasting the code here, any help will be appreciated

case R.id.b:

        InputStream is = getResources().openRawResource(R.raw.temp);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        try {
            string = br.readLine();
            while(string != null){
                st = string;
            }
            text.setText(st);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        break;

"st" and "string" are both string variables. i will be glad if anyone can point out at another simple method to do the same.

Asad
  • 49
  • 1
  • 5

1 Answers1

4

Change to the following:

InputStream is = getResources().openRawResource(R.raw.temp);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line; 
String entireFile = "";
try {
    while((line = br.readLine()) != null) { // <--------- place readLine() inside loop
        entireFile += (line + "\n"); // <---------- add each line to entireFile
    }
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
text.setText(entireFile); // <------- assign entireFile to TextView
break;
Gilad Haimov
  • 5,767
  • 2
  • 26
  • 30
  • thanks alot gilad, your code really worked, well, strange thing is, mine worked only by replacing these two lines of code " line = br.readline(); while(line != null ) " with " while((line = br.readLine()) != null)" i thought both codes meant the same meaning – Asad Aug 23 '14 at 20:21
  • Welcome. Your code only calls readLine() once. Mine calls it N times, N being the number of lines in the file. – Gilad Haimov Aug 23 '14 at 20:26
  • oh that totally makes sense now, that was the reason it was posting the same line(my text file is only one line long) in every new line with every click on the button, while my code only did that once, and the other clicks on the button were giving no response. – Asad Aug 23 '14 at 20:31
  • That is a infinite loop if string != null. – peacepassion Sep 04 '14 at 00:22
  • Please use a StringBuilder – Greg Ennis Jul 26 '16 at 18:24
  • Greg is correct. StringBuilder will result in better performance. – Gilad Haimov Aug 01 '16 at 08:23