1

我有一个从本地主机加载文本文件的代码,我正在使用 xampp,我将文件放在 htdocs 下的 xampp 文件夹中。这是我的代码:

public class MainActivity extends Activity {

TextView httpStuff;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    httpStuff = (TextView)findViewById(R.id.tvHttp);        
    try {
        URL url = new URL("http://10.0.2.2/name.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));           
        String str = in.readLine();
        in.close();
        httpStuff.setText(str);
        } catch (MalformedURLException e) {  
        e.printStackTrace();
    }catch (IOException e) {
        // TODO: handle exception
    }

}}

我得到了这个错误。我不知道怎么了。我还在我的 androidmanifest.xml 文件中添加了权限 internet。

   10-24 17:17:45.024: E/AndroidRuntime(7544): FATAL EXCEPTION: main
10-24 17:17:45.024: E/AndroidRuntime(7544): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.name.in.a.textfile/com.example.name.in.a.textfile.MainActivity}: android.os.NetworkOnMainThreadException
10-24 17:17:45.024: E/AndroidRuntime(7544):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at android.os.Looper.loop(Looper.java:137)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at android.app.ActivityThread.main(ActivityThread.java:4745)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at java.lang.reflect.Method.invokeNative(Native Method)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at java.lang.reflect.Method.invoke(Method.java:511)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at dalvik.system.NativeStart.main(Native Method)
10-24 17:17:45.024: E/AndroidRuntime(7544): Caused by: android.os.NetworkOnMainThreadException
10-24 17:17:45.024: E/AndroidRuntime(7544):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.io.IoBridge.connect(IoBridge.java:112)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at java.net.Socket.connect(Socket.java:842)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:76)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at java.net.URL.openStream(URL.java:462)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at com.example.name.in.a.textfile.MainActivity.onCreate(MainActivity.java:27)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at android.app.Activity.performCreate(Activity.java:5008)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-24 17:17:45.024: E/AndroidRuntime(7544):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-24 17:17:45.024: E/AndroidRuntime(7544):     ... 11 more
4

2 回答 2

3

您的问题显示在这一行 android.os.NetworkOnMainThreadException 10-24 17:07:44.745: E/AndroidRuntime(7143)

在 android 中,您不能在主线程中执行网络操作,因为它可能会阻止 UI 更新超过 5 秒,导致应用程序无响应。

你应该做这样的事情(未经测试)该try块应该是:

Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        URL url = new URL("http://10.0.2.2/name.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));           
        String str = in.readLine();
        in.close();
        runOnUIThread(new Runnable() {
           @Override
           public void run() { 
               httpStuff.setText(str);
           }
        });

    });
t.start();

这种方式你在不同的线程上执行网络,但是由于一旦网络完成你需要更新 UI,你需要使用runOnUIThread,因为在 UI 线程可以更新 UI 组件。

另一个可能更好的选择是AsyncTask 你把你的网络任务放在它的doInBackground方法中,并在方法中更新 UI onPostExecute,这样你就不需要搞乱线程了。基本上AsyncTask做我上面描述的。您应该对此进行研究,因为所有网络都应该在与 UI 不同的线程中完成,这AsyncTask是一个很好且简单的选择。

于 2012-10-24T08:14:22.120 回答
0

七点,我在这里有一个改进的答案,因为我也经历过这个问题

private class myStreamReader extends AsyncTask<String, Void, String> {
    String str = "";
    @Override
    protected String doInBackground(String... params) {
        try {
            URL url = new URL(""http://10.0.2.2/name.txt"");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            str = in.readLine();
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }

        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {
        //do something here
         httpStuff.setText(str);
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}

在使用时只需调用这个

new.myStreamReader().execute();
于 2019-03-26T07:03:11.707 回答