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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With