0

I have a class which has function of getJSON from an url. There is no problem with the code, I think. But it gives me android.os.NetworkOnMainThreadException . I should use AsyncTask but I can not do that with myself. Can we add AsyncTask to any class like my JsonCreator class? My class definition is;

public class JsonCreator{
private String Url = Constants.url;
JSONObject result = null;
JSONArray json = null;
Connect connect = new Connect();

public JSONArray getJson(String command, String[] parameter, int connectionMode){
    String urlParameter = null;

    //Creating parameter which will be added to the end of the URL
    for(int i=0 ; i<parameter.length-1 ; i=i+2){
        if(i == 0)
            urlParameter = "?" + parameter[i] + "=" + parameter[i+1];
        else
            urlParameter = urlParameter + "&" + parameter[i] + "=" + parameter[i+1];
    }

    //First Scenario
    if(connectionMode == 1){

        //Control host availability and take Json Array
        try {
            result = connect.connect(Url+command+urlParameter);
            Constants.hostReachability = Constants.isHostRechable(Url+command+urlParameter);
            json = result.getJSONArray("d");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Save JsonArray to SharedPrefs
        Constants.saveJSONArray(Constants.context, "Json", command, json);
    }

    //Second Scenario
    else if(connectionMode == 2){

        //Control host availability and take Json Array
        try {
            result = connect.connect(Url+command+urlParameter);
            Constants.hostReachability = Constants.isHostRechable(Url+command+urlParameter);
            json = result.getJSONArray("d");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //If json can not be taken from URL, Search for data from SharedPrefs
        if(json == null || !Constants.hostReachability){
            try {
                json = Constants.loadJSONArray(Constants.context, "Json", command);
            } catch (JSONException e) {
                Constants.connectionProblem = "No Data";
                e.printStackTrace();
            }
        }
    }
    //Third Scenario
    else if(connectionMode == 3){

        //Take data from SharedPrefs
        try {
            json = Constants.loadJSONArray(Constants.context, "Json", command);
        } catch (JSONException e) {
            Constants.connectionProblem = "No Data";
            e.printStackTrace();
        }

        //If the data from SharedPref can not be found, Take json from URL
        if(json == null){
            //Control host availability and take Json Array
            try {
                result = connect.connect(Url+command+urlParameter);
                Constants.hostReachability = Constants.isHostRechable(Url+command+urlParameter);
                json = result.getJSONArray("d");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    return json;
}

public JSONArray getJson(String command, String[] parameter){
    String urlParameter = null;
    //Creating parameter which will be added to the end of the URL
    for(int i=0 ; i<parameter.length ; i=i+2){
        if(i == 0)
            urlParameter = "?" + parameter[i] + "=" + parameter[i+1];
        else
            urlParameter = urlParameter + "&" + parameter[i] + "=" + parameter[i+1]; 
    }
    //Take json from server
    try {
        result = connect.connect(Url+command+urlParameter);
        Constants.hostReachability = Constants.isHostRechable(Url+command+urlParameter);
        json = result.getJSONArray("d");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return json;
}

}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Batuhan Coşkun
  • 2,961
  • 2
  • 31
  • 48
  • asynctask is invoked on the ui thread. So if you want to parse json or get json use asynctask and do the computation in `doInbackground` – Raghunandan Sep 13 '13 at 13:50

2 Answers2

2

You getandroid.os.NetworkOnMainThreadException because you are running network related operation on the ui thread. Use AsyncTask or Thread.

http://developer.android.com/reference/android/os/AsyncTask.html

Check the topic under threading rules in the above link

Invoke asynctask like

  new TheTask().execute(); // you can pass values to asynctask doinbackground

Then

public class TheTask extends AsyncTask <Void,Void,Void>
{

@Override
protected void onPreExecute() {
    super.onPreExecute();
            // display progress dialog

}
@Override
protected Void doInBackground(Void... params) {
        // your background computation. do not update ui here
        // your getjson method code here
    return null; //return result of doinbackground computation 
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
         //dismiss progress dialog
         // recieve result and update ui
    }
}

As codemagic suggested your class can extend asynctask and call appropriate methods in doInbackground.

To return result back to the activity use a interface. Check the example below

Can't post response from AsyncTask to MainActivity

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • 2
    No need for me to answer now but I was going to suggest that the current class could `extends AsyncTask` and the code put in `doInBackground()` or call the current functions from `doInBackground()` if wanting to keep the functions intact. Then return result with `interface` in `onPostExecute()` if needed – codeMagic Sep 13 '13 at 13:59
0

This is thrown when you execute a network operation in UI thread. This is illegal since HoneyComb. All you've to do is do the network operations in doInBackground method of AsyncTask.

Also be sure that you've permissions for internet in manifest.

Reinherd
  • 5,476
  • 7
  • 51
  • 88