1

I have this code which returns Json object from url. It works fine in froyo but the same code is not working in Jelly Beans.

Is something wrong with my code ?

Please help me, here is my code

    public static JSONObject getJSONfromURL(String url) {

    // initialize
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}

Here is my log error

11-01 11:01:48.437: E/log_tag(1044): Error in http connection android.os.NetworkOnMainThreadException 11-01 11:01:48.437: E/log_tag(1044): Error converting result java.lang.NullPointerException 11-01 11:01:48.437: E/log_tag(1044): Error parsing data org.json.JSONException: End of input at character 0 of

Antarix
  • 665
  • 1
  • 10
  • 29
  • is there any error? if yes then please post it. And yes you are doing network related task so make sure you are not doing this in main thread see [this](http://android-developers.blogspot.in/2009/05/painless-threading.html) – Juned Nov 01 '12 at 05:29
  • what do you mean by "not working"? – Andro Selva Nov 01 '12 at 05:29
  • what is the problem exactly just see logcat whether any error is there or not?? – Ravi Nov 01 '12 at 05:31
  • it shows me this error first `android.os.NetworkOnMainThreadException` but i have checked the internet connection in emulator as well as in manifest. The code is working fine in `froyo` but the same code is not working in `Jelly Beans` . I am trying to read `Json` from `Json object` – Antarix Nov 01 '12 at 05:51

4 Answers4

1

You are trying to establish network connection on the main thread. Instead use AsyncTask. Because network tasks are long tasks . In froyo you can establish network on main thread but in Later versions of android you will have to use Async Task.

Ashwani
  • 1,574
  • 14
  • 28
1

Make Server call in background thread.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new AsyncTask<Void,Void,Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            JSONObject jObject = getJSONfromURL("http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%2248907%22&format=json");
            return null;
        }
    }.execute();
}
public JSONObject getJSONfromURL(String url) {

    // initialize
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}
Kavin Varnan
  • 1,989
  • 18
  • 23
1

From Android API v15, it requires no heavy process working on main thread. So you should move your logic to another thread like bellow source code:

new Thread(new Runnable() {
   public void run() {
        // your logic
   }                        
}).start();

More information please refer http://developer.android.com/guide/practices/responsiveness.html

ckpatel
  • 1,926
  • 4
  • 18
  • 34
1

Yeah its error about android.os.NetworkOnMainThreadException Use AsyncTask to do network related task.

In another way you can disable this by using this code on your onCreate()

if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = 
        new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

But see disabling StrictMode policy is not a good idea, so you better to go with AsyncTask

Juned
  • 6,290
  • 7
  • 45
  • 93