android.os.NetworkOnMainThreadException. How to solve it?

前端 未结 3 848
醉话见心
醉话见心 2021-01-29 11:22

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

3条回答
  •  一生所求
    2021-01-29 11:45

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

提交回复
热议问题