简体   繁体   中英

Return ArrayList from async task

1) I already read all questions about that here, so please tell me more, than just url from SO...

2) I want to return only ONE variable from asynctask, but it can be message error or user details. So I decided to return ArrayList with indexes 0 (for error messages) and 1 (for success).

AsyncTask

public class LoginGet extends AsyncTask<String, ProgressBar, ArrayList<String>> {
...
public ArrayList<String> result = new ArrayList<String>();

public LoginGet(Context mContext, String loginText, String passwordText) {
    //Get values form LoginActivity
}

protected void onPreExecute(){
    super.onPreExecute();
    // progressDialog
}

@Override
protected ArrayList doInBackground(String... arg0){
    try {
        // Making HTTP Request
        try {
            // Creating HTTP client
            ...
            ...
            JSONObject jObject = new JSONObject(json);
            success = jObject.getString("success");
            result.add(0, "");
            result.add(1, "");
            if (success != null) {
                if (success == "1") {
                    result.add(1, jObject.getString("hash"));
                    return result;
                } else if (success == "0") {
                    result.add(0, jObject.getString("error"));
                    return result;
                }
            } else {
                result.add(0, "Error while logging.");
                return result;
            }

           // writing response to log
            Log.d("Http Response:", response.toString());
        }  catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }catch (Exception e) {

    }

    return result;
}

@Override
protected void onPostExecute(ArrayList<String> result) {
    ((LoginActivity)context).getResult(result);
    progressDialog.dismiss();
}
}

LoginActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ...
            if (loginText.compareTo("") == 0 || passwordText.compareTo("") == 0) {
                ...
            }else{
                LoginGet loginPost = new LoginGet(LoginActivity.this,loginText,passwordText);
                loginPost.execute();
            }
        }
    });

}

// Get result from asynctask LoginGet
public void getResult(ArrayList<String> result){
    if (result.get(0) != "") {
        loginButton.setEnabled(true);
        Toast.makeText(LoginActivity.this, result.get(0), Toast.LENGTH_SHORT).show();
    } else if (result.get(1) != "") {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("Login", result.get(1));
        editor.commit();

        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
    }

}

Error:

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at cz.jacon.smsapp.LoginActivity.getResult(LoginActivity.java:57)
at cz.jacon.smsapp.background.LoginGet.onPostExecute(LoginGet.java:121)
at cz.jacon.smsapp.background.LoginGet.onPostExecute(LoginGet.java:30)

3) In my AsyncTask I have result.add(0, ""); and result.add(1, ""); , so why is the ArrayList size 0?

In my opinion result.add(0, ""); isn't even reached, since the try block might be failing.

And sadly you have an empty catch block, just waiting to skip them errors:

catch (Exception e) {

}

Your solution would be to add these

result.add(0, "");
result.add(1, "");

to the very beginning of the doInBackground or even to the constructor and you should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM