NetworkOnMainThreadException When reading from web

前端 未结 3 896
北荒
北荒 2020-12-19 22:35

When i try to read single line of text from website i get error (NetworkOnMainThreadException). I tryed few thing but nothing works so far. So here is code if anyone could h

相关标签:
3条回答
  • 2020-12-19 23:24

    You might want to do all your downloading using a AsyncTask, http://developer.android.com/reference/android/os/AsyncTask.html

    or if your on api 11+ a AsyncTaskLoader, http://developer.android.com/reference/android/content/AsyncTaskLoader.html

    0 讨论(0)
  • 2020-12-19 23:34

    don't use network activities in main thread.This exception only thrown for applications targeting the Honeycomb SDK or higher. perform all the network related task in separate thread ( either use handler looper or runOnUiThread) . your problem will get solved.

    0 讨论(0)
  • 2020-12-19 23:36

    Either you can move it to background thread or if you just want to eliminate this error just add this in your onCreate() :

     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    
        StrictMode.setThreadPolicy(policy); 
    

    Do not forget to add internet permission in manifest:

    <uses-permission android:name="android.permission.INTERNET"/>
    
    0 讨论(0)
提交回复
热议问题