0

I am asking here as all other solutions have not worked. I want to read a text file from the web and have this string put into a textview. I am just testing at the moment and the only thing in the text file is the value "223". My app is crashing on start can anyone please help?

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.StringBuilderPrinter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private StringBuilder text = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BufferedReader reader = null;

        try {

            URL url = new URL("http://something.uk/pmt/status.txt");


            reader = new BufferedReader(
                    new InputStreamReader(url.openStream()));


            String str;


            while ((str = reader.readLine()) != null) {
                text.append(str);
                text.append('\n');
            }

        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "Error reading file.", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (MalformedURLException e) {

                }

                catch (IOException e) {

                }
            }

            TextView output = (TextView) findViewById(R.id.textView);
            output.setText((CharSequence) text);
        }
    }
}

STACKTRACE:

https://pastebin.com/YSCB9RBg

3
  • 1
    Please, post your errors from logcat Commented May 3, 2017 at 19:31
  • How do I use logcat? I tried adb logcat in the terminal but it didn't work. Commented May 3, 2017 at 19:57
  • The error is pretty clear ...NetworkOnMainThread....that means You have to execute the code from try catch in another thread . Commented May 3, 2017 at 20:11

2 Answers 2

1

Probably because you are using StringBuilder which is not a CharSequence. Use output.setText(text.toString()); instead of output.setText((CharSequence) text);

TextView.setText() expects a CharSequence as an argument. String is a CharSequence, but StringBuilder is not. To get a String you gave to call StringBuilder.toString()

You should look at the crash though. And post it next time you ask a question on stackoverflow.

The crash log you provided clearly states the reason for crash: android.os.NetworkOnMainThreadException. It means that you are trying to do a network operation on the main thread and the Android OS does not let you. It is a rule since Honeycomb. The solution is to use AsyncTask, for example. Here is an article about network ops and AsyncTask.

Sign up to request clarification or add additional context in comments.

6 Comments

what you mean by stringbuilder is not a charsequence?
@Remario extended the answer.
Thank you for your answer, I have done what you suggested but the app still crashes.
Post the stacktrace
Added the stracktrace
|
1
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.StringBuilderPrinter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private StringBuilder text = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BufferedReader reader = null;

       new AsyncTask<Void,Void,Void>(){


            @Override
            protected Void doInBackground(Void... params) {
 try {

            URL url = new URL("http://something.uk/pmt/status.txt");


            reader = new BufferedReader(
                    new InputStreamReader(url.openStream()));


            String str;


            while ((str = reader.readLine()) != null) {
                text.append(str);
                text.append('\n');
            }

        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "Error reading file.", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (MalformedURLException e) {

                }

                catch (IOException e) {

                }
            }
                return null;
            }

   @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
            TextView output = (TextView) findViewById(R.id.textView);
            output.setText(text.toString());
            }
        }.execute(null,null,null);


        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.