Search code examples
javaandroidfilefileinputstream

TextView only views the last line when I try to create a new line in a file


I created a file which prints a certain line of data and I need it to do it repetitively in new lines. Then I want to put it in a textview. However, when I try to print it in a new line with "\n \r" or print ln, it only views one line of data instead of all of them.

I tried everything and I know it's not a problem with overwriting of data because it does work if I don't create a new line. It just has no spaces which makes no sense for me.

This is the file creation code

PrintWriter output = null;
    File file = new File(getApplicationContext().getFilesDir(), "past.txt");
    output = new PrintWriter(new FileWriter(file, true));
    output.print(format_1 + " Overall positivity was " + sprog + "\n");
    output.close();

And the read/setText part.

try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(getApplicationContext().getFilesDir(),"past.txt")),StandardCharsets.UTF_8))){

        String line;

        while ((line=br.readLine()) != null){
            results.setText(line);
        }

Could it be something with TextView itself that causes the problem? Or is it something within the code?

XML of the textView

<TextView
    android:id="@+id/pastresults"
    android:layout_width="349dp"
    android:layout_height="402dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="@string/textview"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.526"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.913"
    android:textSize="25sp"/> 

Many many thanks for help.


Solution

  • First you need to build a StringBuffer, append each line

    StringBuffer text= new StringBuffer();
    String line="";
    while ((line=br.readLine()) != null){
              text.append(line);
            }
    

    And finally set the variable

    results.setText(text);