试图从位于服务器上的文本文件中获取文本

Trying to get text from the text file located on sever

我正在尝试从服务器的文本文件中获取字符串并将其显示在 ListView 上。我通过覆盖方法 onRefersh() 从拉取到刷新调用 getTextListFromUrl()。但我被困在某个地方。这是我的代码

public class ScreenTwoActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    private static final String CLASS_TAG = ScreenTwoActivity.class.getSimpleName();

    private ListView mLvData;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private ArrayAdapter<String> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_2);

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_referesh_layout);
        mLvData = (ListView) findViewById(R.id.lv_screen_2);
        mSwipeRefreshLayout.setOnRefreshListener(this);
    }

    @Override
    public void onRefresh() {
        getRefreshContent();
    }

    /**
     * On swipe refresh new data will being fetched from list
     */
    private void getRefreshContent() {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mAdapter = new ArrayAdapter<String>(ScreenTwoActivity.this, android.R.layout.simple_list_item_1, getTextListFromUrl());
                mLvData.setAdapter(mAdapter);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        }, 1000);
    }

    private List<String> getTextListFromUrl() {

        List<String> listTextData = new ArrayList<>();
        try {
            URL textUrl = new URL("http://thehealthybillion.com/assignment/q3.txt");
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
            String stringBuffer;
            while ((stringBuffer = bufferReader.readLine()) != null) {
                Log.i(CLASS_TAG, stringBuffer);
                listTextData.add(stringBuffer);
            }
            bufferReader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  listTextData;
    }
}

这是我在日志中遇到的错误

android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
            at java.net.InetAddress.getAllByName(InetAddress.java:214)
            at com.android.okhttp.internal.Dns.getAllByName(Dns.java:28)
            at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
            at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
            at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
            at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
            at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
            at java.net.URL.openStream(URL.java:470)
            at com.thb.vidyanand.assignmentthb.ScreenTwoActivity.getTextListFromUrl(ScreenTwoActivity.java:86)
            at com.thb.vidyanand.assignmentthb.ScreenTwoActivity.access0(ScreenTwoActivity.java:22)
            at com.thb.vidyanand.assignmentthb.ScreenTwoActivity.run(ScreenTwoActivity.java:66)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:149)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
            at dalvik.system.NativeStart.main(Native Method)

谁能告诉我这是怎么回事?

您正在主线程(UI 线程)上执行与网络相关的任务,因此它抛出 NetworkOnMainThreadException。使用 AyncTaskHandler 将所有繁重的网络相关工作移至工作线程。

即使在使用 Handler 之后,如果您仍然遇到异常,请在 Activity 的 onCreate().

中添加以下代码
if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy); 
}

来源:Error StrictMode$AndroidBlockGuardPolicy.onNetwork

参考:StrictMode了解更多信息。

当您连接到互联网时,您需要使用 AsyncTask 并从 doInBackground 方法中调用它。

您的错误可以在您的 onCreate 中使用 StrictMode.enableDefaults() 解决,但仅用于调试。

使用异步任务从服务器获取数据,不要在主线程中做网络相关的事情。 请参考此链接:

How to fix android.os.NetworkOnMainThreadException?

android.os.NetworkOnMainThreadException with android 4.2