This is my AsyncTask:
public class GetDataTask extends AsyncTask<Void, Void, JSONArray> {
@Override
protected void onPreExecute() {
// [...]
}
@Override
protected void onPostExecute(JSONArray result) {
int result_length = 0;
try {
result_length = result.length();
} catch (NullPointerException e) {
e.printStackTrace();
// Redirect the user back to the original activity
Intent intent = new Intent(ResultActivity.this, MainActivity.class);
startActivity(intent);
}
for (int i = 0; i < result_length; i++) {
// [...]
}
}
@Override
protected JSONArray doInBackground(Void... params) {
// [...]
}
}
When result
is null, .length() throws a NullPointerException. That's why I want to redirect the url back to MainActivity when this happen.
try {
result_length = result.length();
} catch (NullPointerException e) {
e.printStackTrace();
// Redirect the user back to the original activity
Intent intent = new Intent(ResultActivity.this, MainActivity.class);
startActivity(intent);
The problem is that it doesn't work. I get e.printStackTrace()
but the activity doesn't change. It's like Intent is not "fast" enough to change activity, and the code below (for (int i = 0; i < result_length; i++) {}
) still keeps running.
What can I do? Is my solution wrong? Thank you in advance.