Nancy Khorevich
Nancy Khorevich

Reputation: 53

How to parse JSON with AsyncTask?

I tried to parse some strings from this JSON-site:

Image of JSON table

I wrote this code with asynctask:

package com.example.nortti.jsonexample;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends Activity {
    TextView txView;

//URL to get JSON Array
private static String url = "http://localhost:10101/api/stats/1";

//JSON Node Names
private static final String TAG_USER = "";
private static final String TAG_NAME = "PersonName";
private static final String TAG_EMAIL = "Rank";


JSONArray user;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    user = null;
            new JSONParse().execute();



}

private class JSONParse extends AsyncTask<String, String, JSONObject> {
    private ProgressDialog pDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        txView = (TextView)findViewById(R.id.txView);

        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Getting Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected JSONObject doInBackground(String... args) {
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        return json;
    }
    @Override
    protected void onPostExecute(JSONObject json) {
        pDialog.dismiss();
        try {
            // Getting JSON Array
            user = json.getJSONArray("ArrayOfCommonStatViewModel");
            Toast.makeText(getApplication(),user.toString(),Toast.LENGTH_SHORT).show();
            JSONObject c = user.getJSONObject(0);

            // Storing  JSON item in a Variable

            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);

            //Set JSON Data in TextView

            txView.setText(name+" " +email);


        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

}

And I have another class like:

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

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
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        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;

}
}

But it says that I have a NullPointerException

I want to get a JSONArray to get information and put it into a ListView.

UPD: Here is JSON screenshot JSON

UPD2: full log

12-17 14:17:03.712 20308-20308/com.example.nortti.politrange E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.nortti.politrange, PID: 20308
                                                                               android.os.NetworkOnMainThreadException
                                                                                   at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
                                                                                   at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
                                                                                   at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
                                                                                   at java.net.InetAddress.getAllByName(InetAddress.java:215)
                                                                                   at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:44)
                                                                                   at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:102)
                                                                                   at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318)
                                                                                   at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:373)
                                                                                   at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:225)
                                                                                   at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
                                                                                   at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
                                                                                   at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
                                                                                   at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:178)
                                                                                   at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
                                                                                   at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
                                                                                   at com.example.nortti.politrange.utils.WebApiAdapter.select(WebApiAdapter.java:33)
                                                                                   at com.example.nortti.politrange.intefaces.impls.PersonCatalog.populateData(PersonCatalog.java:37)
                                                                                   at com.example.nortti.politrange.views.GeneralFragment.listData(GeneralFragment.java:65)
                                                                                   at com.example.nortti.politrange.views.GeneralFragment.onClick(GeneralFragment.java:88)
                                                                                   at android.view.View.performClick(View.java:4756)
                                                                                   at android.view.View$PerformClick.run(View.java:19761)
                                                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                   at android.os.Looper.loop(Looper.java:135)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5253)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)

Upvotes: 0

Views: 6031

Answers (6)

Hardik Karkar
Hardik Karkar

Reputation: 11

enter code here

////In android studio add http client and http core libs/////

class mytask extends AsyncTask {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();


    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        String url = "http://192.168.1.13/mywebservice/getbook.php";
        json = getJSONFromUrl(url);

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        Toast.makeText(ctx, json, Toast.LENGTH_LONG).show();
        parser_01();
    }

}

// from url to json object starts.......................................
public String getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        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");
            sb.append(line);
        }
        is.close();
        json = sb.toString();

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    return json;

}

// from url to json object Ends.......................................

public void parser_01() {
    try {




        String jstring = json;



        JSONObject jobject = new JSONObject(jstring);

        JSONArray bookarray = jobject.getJSONArray("data");

        for (int i = 0; i < bookarray.length(); i++) {

            String isdn = bookarray.getJSONObject(i).getString("isdn") + "";
            String title = bookarray.getJSONObject(i).getString("title") + "";
            String author = bookarray.getJSONObject(i).getString("author") + "";
            String price = bookarray.getJSONObject(i).getString("price") + "";





        }



    } catch (Exception e) {
        // TODO: handle exception
    }

}

Upvotes: 0

Amit Tiwari
Amit Tiwari

Reputation: 3692

The content that you are trying to parse is actually xml not JSON. If you need to do network requests, parse the JSON, you can use Retrofit library. It is very simple and hassle-free. Here is a nice tutorial for the same. Hope it helps.

Upvotes: 1

Gex
Gex

Reputation: 2202

You are trying to parse an XML document with a JSON Parser, it won't work. Let's take a look on this link , it will show you how to parse an XML document (in Android environment) on a proper way:

Upvotes: 1

shresha
shresha

Reputation: 147

you are getting a NetworkOnMainThread exception because you are implementing a network operation in a UI thread so for loading the json data from your localhost you need to implement a seperate thread for it

Upvotes: 2

Hiren Patel
Hiren Patel

Reputation: 52810

You are getting NetworkOrMainThreadException.

Put below code on onCreate():

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 

Hope this will help you.

Upvotes: 1

Fakher
Fakher

Reputation: 2128

instead of developping the whole parsing code, try to use the Volley library of Google, it's an asynchrone library for parsing JSON. here is a good tutorial.

Upvotes: 0

Related Questions