android.os.NetworkOnMainThreadException. How to solve it?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-11 14:43:33

问题


I am trying to get my current location and get the driving directions to some destination. I am able to get my location and when I execute the code for the driving directions I get android.os.NetworkOnMainThreadException in the following line

        HttpResponse response = httpClient.execute(httpPost, localContext);

Response is NULL. What do i do ?

public Document getDocument(LatLng start, LatLng end, String mode) {
    String url = "http://maps.googleapis.com/maps/api/directions/xml?" 
            + "origin=" + start.latitude + "," + start.longitude  
            + "&destination=" + end.latitude + "," + end.longitude 
            + "&sensor=false&units=metric&mode="+mode;

    try {
         new DownloadWebpageTask().execute(url);


        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = httpClient.execute(httpPost, localContext);
        InputStream in = response.getEntity().getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(in);
        return doc;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

回答1:


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

}



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/23305588/android-os-networkonmainthreadexception-how-to-solve-it

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