简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM