Android - android.os.NetworkOnMainThreadException

后端 未结 8 1192
迷失自我
迷失自我 2020-11-22 08:15

I have this exception and I was reading a thread on this, and it seemed confusing:

How to fix android.os.NetworkOnMainThreadException?

I already added this l

8条回答
  •  情歌与酒
    2020-11-22 08:37

    NetworkOnMainThreadException is thrown when your app tries networking operation in main thread.

    To fix that you can use a private inner class within your Activity that extends android.os.AsyncTask which will do the server call stuffs.

    Something as,

    private class SendfeedbackJob extends AsyncTask {
    
        @Override
        protected String doInBackground(String[] params) {
            // do above Server call here
            return "some message";
        }
    
        @Override
        protected void onPostExecute(String message) {
            //process message
        }
    }
    

    And then invoke above class from submit.setOnClickListener as below,

    SendfeedbackJob job = new SendfeedbackJob();
    job.execute(pass, email);
    

    AsyncTask

    References

    AsyncTask doc

    AsyncTask Android example

提交回复
热议问题