Reading data from a text file and displaying it in text form

I try to read data from the text file temp.txt, which is in my raw folder and displays the contents of the file in the text form β€œtext” whenever the β€œbutton” button is pressed, but my application crashes doing this, there is a good chance that I I'm doing it wrong because I'm new to Android and Java programming. I am inserting the code here, any help would 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 another easy way to do the same.

+5
source share
1 answer

Change 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; 
+4
source

Source: https://habr.com/ru/post/1200989/


All Articles