从URL读取文本文件并输出到TextView

时间:2017-05-03 19:19:42

标签: java android

我在这里问,因为所有其他解决方案都没有奏效。我想从网上读取一个文本文件,并将此字符串放入textview。我现在只是测试,文本文件中唯一的东西是值“223”。我的应用程序在启动时崩溃可以请任何人帮忙吗?

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);
        }
    }
}

堆栈跟踪:

https://pastebin.com/YSCB9RBg

2 个答案:

答案 0 :(得分:1)

可能是因为您使用的StringBuilder不是CharSequence。使用output.setText(text.toString());代替output.setText((CharSequence) text);

TextView.setText()期望CharSequence作为参数。 StringCharSequence,但StringBuilder不是。要获得String,请致电StringBuilder.toString()

你应该看看崩溃。下次你在stackoverflow上提问时发布它。

您提供的崩溃日志清楚地说明了崩溃的原因:android.os.NetworkOnMainThreadException。这意味着您正在尝试在主线程上执行网络操作,并且Android操作系统不允许您。这是Honeycomb之后的规则。解决方案是使用AsyncTask。这是an article about network ops and AsyncTask

答案 1 :(得分: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);


        }
    }
}