Nirel Nirel - 6 days ago 7
JSON Question

Run code in AsyncTask stucking UI

I'm trying a copule of days to figure it out, without success,

Target: get use country by IP using asyncTask without stucking UI, and save it into string parm.

Problem: The UI doen't move until the asyncTask finish it job :/

MainActivity ,onCreate method:

.......
JSONObject jsonObject;
try {
jsonObject = new getJSONObjectFromURL(LoginActivity.this).execute("http://ip-api.com/json").get();
if (jsonObject != null) {
if (!jsonObject.getString("status").equals("success"))
throw new InterruptedException();
Log.d(TAG, "onCreate: jsonObject.tostring:" + jsonObject.toString());
countryLocation = jsonObject.getString("country");
Log.d(TAG, "onCreate: countryByIP " + countryLocation);
}
if (!isNetworkAvailable()/* || countryLocation == null*/)
Toast.makeText(MainActivity.this, "Please enable data.", Toast.LENGTH_SHORT).show();
//in button click redo all that code for no internet connection,.
} catch (InterruptedException | ExecutionException | JSONException e) {
e.printStackTrace();
}


asyncTask:

public class getJSONObjectFromURL extends AsyncTask<Object, Object, JSONObject> {

private Context context;

public getJSONObjectFromURL(Context context) {
this.context = context;
}

@Override
protected JSONObject doInBackground(Object... params) {
HttpURLConnection urlConnection = null;

URL url = null;
try {
url = new URL((String) params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);

urlConnection.setDoOutput(true);

urlConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String jsonString;
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
jsonString = sb.toString();
return new JSONObject(jsonString);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(JSONObject result) {
//Update the String..
}
}


Everything works perfect, i get the Json, able to read the Country from it, but MainActivity waiting for the onPostExecute to continue.

Answer

You are running your AsyncTask in a synchrounous state.

jsonObject = new getJSONObjectFromURL(LoginActivity.this).execute("http://ip-api.com/json").get();

By calling get() you are waiting until the Task has finished it's job. Do not use get() if you want to have a truly asynchronous process. You can use a callback to get notified.

Comments