android.os.NetworkOnMainThreadException. How to solve it?

做~自己de王妃 提交于 2019-12-02 13:22:47

You can't do network operations on the main UI thread. What you will have to do is create a new Thread and do the network stuff there. If you need to, you can then you can post updates back to the main UI thread using a Handler. If you need a code sample, I can post a minimal one that should work.

It's important when you do this NOT to maintain a strong reference back to the Activity or you can leak the whole activity on a device rotate or other onDestroy() event. Because you're passing the Context out to a different thread, you'll want to test this to make sure you're not leaking. I wrote a blog post about this on my Tumblr:

http://tmblr.co/ZSJA4p13azutu


Edit 1

Here's some code that should help:

static final class ProgressMessages extends Handler
{
    private WeakReference<MyAndroidClass> weakAndroidClassRef;

    public ProgressMessages (MyAndroidClass myContext)
    {
        weakWritingPadRef = new WeakReference<MyAndroidClass>( myContext);

    }

    public void handleMessage(Message msg)
    {
        String s = "Uploading page " + msg.arg1 + ".";
        Toast t = Toast.makeText(weakAndroidClassRef.get(), s, Toast.LENGTH_LONG);
        t.show();   

    }


};

ProgressMessages pm;



public void doNetworkStuff()
{

    t = new Thread()
    {
        public void run()
        {

             Looper.prepare();
             try
             {
                  pm.sendMessage(Message.obtain(pm, 0, i + 1, 0));


             }
             catch(IOException ioe)
             {
                 ioe.printStackTrace();

             }
             pm.post(update);
        }


    };
    t.start();

}

As NetworkOnMainThreadException states , network request should be executed only in background thread. Your cannot execute in main thread.

Create an AsycTask and execute your code on doInBackground() method. Once the background operation is completed, You can update the UI in onPostExecute

 new AsyncTask<Void, Integer, Document>(){
        @Override
        protected Document doInBackground(Void... params) {
            try {

                // call you method here
                return getDocument();

            } catch (Exception ex) {
                // handle the exception here
            }
            return null;
        }

        @Override
        protected void onPostExecute(Document result){
            // update the UI with your data
        }
    }.execute();

This is cause when you are trying to do networking on the main thread.. it should be done on the background thread..

solution: AsyncTask

Click here to learn about AsyncTask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!