Nirel Nirel - 1 year ago 75
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("").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) {


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

private Context context;

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

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

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


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");
jsonString = sb.toString();
return new JSONObject(jsonString);
} catch (JSONException | IOException e) {
return null;
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 Source

You are running your AsyncTask in a synchrounous state.

jsonObject = new getJSONObjectFromURL(LoginActivity.this).execute("").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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download