Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading data from a textfile and displaying it on the textview

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.

like image 465
Asad Avatar asked Oct 01 '22 00:10

Asad


1 Answers

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;
like image 129
Gilad Haimov Avatar answered Nov 03 '22 07:11

Gilad Haimov