Android : Network on main thread exception even when using AsyncTask

ぃ、小莉子 提交于 2019-12-25 18:17:59

问题


I am working on an Android project and for Login I am communicating with the server for authentication. Even though I am using AsyncTask, I am getting NetworkOnMain thread exception. Why is that. Here is my code :

public class Login extends Activity {

    public static RestTemplate rest = new RestTemplate();
    Button loginButton = (Button) findViewById(R.id.LoginButton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(v == null)) {
                    EditText userEmail = (EditText) findViewById(R.id.usernameText);
                    EditText userPassword = (EditText) findViewById(R.id.PasswordField);
                    if (!(userEmail.getText().toString().isEmpty())) {
                        if (!(userPassword.getText().toString().isEmpty())) {
                            loginUserViaRest(userEmail.getText().toString(), userPassword.getText().toString());
                            if (!(StaticRestTemplate.jsessionid == null)) {
                                if (!(StaticRestTemplate.jsessionid.isEmpty())) {

                                    executeRestLogin executeRestLogin = new executeRestLogin();
                                    executeRestLogin.doInBackground();

 private class executeRestLogin extends AsyncTask<Void,Void,Void>{

        @Override
        protected Void doInBackground(Void... params) {
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Cookie", "JSESSIONID=" + StaticRestTemplate.jsessionid);
            HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);

// Below line gives me an error
            HttpEntity<String> rssResponse = rest.exchange(
                    "http://192.168.178.60:8080/dashboard",
                    HttpMethod.GET,
                    requestEntity,
                    String.class);
            StaticRestTemplate.jsessionid = rssResponse.getBody();
            return null;
        }
    }

What am I doing wrong. Also, how can I get custom objects back as response from async task?

Update

To the next problem in question :

  ExecuteRestLogin executeRestLogin = new ExecuteRestLogin();
// The below execute method works, but I cannot get the result of postExecute in it, it shows me its not of the type Void, Void, String. 
 String result =  executeRestLogin.execute();

private class ExecuteRestLogin extends AsyncTask<Void,Void,String>{

        @Override
        protected String doInBackground(Void... params) {
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Cookie", "JSESSIONID=" + StaticRestTemplate.jsessionid);
            HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);

            HttpEntity<String> rssResponse = rest.exchange(
                    "http://192.168.178.60:8080/dashboard",
                    HttpMethod.GET,
                    requestEntity,
                    String.class);
            StaticRestTemplate.jsessionid = rssResponse.getBody();
            return StaticRestTemplate.jsessionid;
        }

        @Override
        protected void onPostExecute(String aVoid) {
            super.onPostExecute(aVoid);
        }
    }

回答1:


executeRestLogin.doInBackground();

Call execute() to execute an async task on a background thread. Calling doInBackground() directly just runs the method on your current thread.

how can I get custom objects back as response from async task

Put the code that deals with async task results in onPostExecute(). It gets run on the UI thread.




回答2:


You are calling doInBackground form the UI therad! In order to start an AsyncTask you need to call execute. executeRestLogin.execute()

Edit:

Dont forget conventions a class starts with an upper case.

Call execute on the AysnTask object will start the task. This tutorial will make it clearer.




回答3:


You should replace the doInBackground() by execute(). With that the code in doInBackground method will be executed in another thread.(you should not create a new thread, Android does it for you.)




回答4:


Change your code like:

private class ExecuteRestLogin extends AsyncTask<Void,Void,Boolean> {
 @Override
    protected Boolean doInBackground(Void... params) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Cookie", "JSESSIONID=" + StaticRestTemplate.jsessionid);
        HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);

        HttpEntity<String> rssResponse = rest.exchange(
                "http://192.168.178.60:8080/dashboard",
                HttpMethod.GET,
                requestEntity,
                String.class);
        StaticRestTemplate.jsessionid = rssResponse.getBody();
        result = StaticRestTemplate.jsessionid; // result is a global String.
        return true;
    }

 @Override
    protected void onPostExecute(final Boolean success) {
         if (success) {
            //You can use your result string now.
        }
    }
}


来源:https://stackoverflow.com/questions/31430570/android-network-on-main-thread-exception-even-when-using-asynctask

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