Register
Login
How to use Json parser android?

Posted on Nov 14, 2013 10:08 AM, Android - Stack Overflow | stackoverflow.com

I used the parser given below with an example Android 2.2. My example is working and i have no problem. when tried to use the some example in a project using Android 4.3. but i have a problem with my parser line

HttpResponse httpResponse = httpClient.execute(httpPost);

I checked all the permission in my manifest, all of them are used.

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = '';

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            Log.d('test url' , 'le request est lancé') ;
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            Log.d('test url' , 'la connection etablie');
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e('Buffer Error', 'Error converting result ' + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e('JSON Parser', 'Error parsing data ' + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

the log is:

11-14 10:48:38.590: ERROR/AndroidRuntime(3801): FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.web.tab/fr.web.profilconfiguration.AndroidJSONParsingActivity}: android.os.NetworkOnMainThreadException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
        at android.app.ActivityThread.access$600(ActivityThread.java:123)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4424)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
        at java.net.InetAddress.getAllByName(InetAddress.java:220)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
        at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
        at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
        at fr.web.profilconfiguration.JSONParser.getJSONFromUrl(JSONParser.java:44)
        at fr.web.profilconfiguration.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:62)
        at android.app.Activity.performCreate(Activity.java:4465)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
Tagged android json

 
ask your own question if you didn't find an answer
Videos
Android Application Development Tutorial - 150 - Introduction to JSON parsingAndroid Application Development Tutorial - 150 - Introduction to JSON parsing
[9Android Media] Android JSON Parser Tutorial with sample source code[9Android Media] Android JSON Parser Tutorial with sample source code
Android Application Development Tutorial - 153 - Reading JSON informationAndroid Application Development Tutorial - 153 - Reading JSON information
Android Tutorial 21 - Our First JSON ResponseAndroid Tutorial 21 - Our First JSON Response
Related Messages

How to use jsonwebservices in Android

I want to implement jsonwebservices in my Android app with login page.I don't know how to do it.I have trying but at the run time i got exception RuntimeException and...

How to use MigLayout in Android

I am new To android and I want to use MigLayout in Android. 1.how to use the miglayout tag in xml layout. 2.can i use my existing layout with Miglayout. <miglayout> ...

How to use dagger Injection android

I am trying to build a simple hello world kind application using Dagger Injection library. So far reading dagger it seems that you can either inject a constructor or fields...

How to parse JSON in Android?

I am try to develop a sample application for YouTube to play video on my android device directly from YouTube. In this respect I have developed some code to parse...

How to use Renderscript in Android API 2.2 and higher?

Although I found a lot of instruction how to implement Renderscript via Support Library on API's lower than 3.0, there are also a lot of problems still. I followed a...

How to use progressbar on android as an hp bar

I am building some small project, it's about a game I managed to use progress bar as my hp bar in the game. It works, however, without any animation on it. Here 'damage'...

How to use or create android default fileopenpicker?

I have a list of different types of files such as pdf, audio(mp3), video etc. I want to open those file using onClick event of the list items with supported...

How to parse json into android to compare users location to nearest 10 locations?

Im getting the server response for store locations and its basically a master array with dictionaries: [ masterArray : {name = main, ...

Java: How to decode JSON within Android? What am I doing wrong?

I've got an Android app in which I get some JSON from an API, which I now need to decode. I'm pretty far, but I'm failing at getting the contents....

How to use asyncTask in android

I am new to android.. I was trying to solve an networkonmainthreadexception, so I used async task but am still getting the same exception.. what is wrong?? this is...

 
 
Email:

Username:

Password:


Register

Username:

Password:

Login