Tartar
Tartar

Reputation: 5452

Android Parse Json Response To Java ArrayList

I am trying to make a GET request to my WCF service via Volley and i want to parse its response to a Java ArrayList. Here is my method

    public ArrayList<Company> getCompanies(){

        String url = AUDITTRACKINGAPP_SERVICE_URI + "GetCompanies";
        String tagJsonReq = "companiesRequest";

        final ProgressDialog pDialog = new ProgressDialog(context);
        pDialog.setMessage("Please Wait...");
        pDialog.show();

        final ArrayList<Company> companies = new ArrayList<Company>();

        JsonObjectRequest companiesRequest = new JsonObjectRequest(  Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        Log.v(TAG, "COMPANIES RESPONSE:" + response.toString());

                        try {
                            JSONArray companiesJson = response.getJSONArray("GetCompaniesResult");

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

                                JSONObject jObject = (JSONObject)companiesJson.get(i);

                                Company company = new Company();
                                company.setCompanyId(Integer.parseInt(jObject.getString("CompanyId")));
                                Log.v(TAG, "COMPANIES setCompanyId:" + jObject.getString("CompanyId"));
                                company.setCompanyName(jObject.getString("CompanyName"));
                                Log.v(TAG, "COMPANIES setCompanyName:" + jObject.getString("CompanyName"));

                                companies.add(company);
                            }

                        } catch (JSONException e) {
                            Log.v(TAG, "COMPANIES RESPONSE ERROR ON PARSING JSON:" + e.getMessage());
                        }

                        pDialog.hide();
                    }
                },
                new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.v(TAG, "COMPANIES onErrorResponse:" + error.getMessage());
                    pDialog.hide();
                }
            });

    AppController.getInstance().addToRequestQueue(companiesRequest, tagJsonReq);

    return companies;
}

JSON RESPONSE:

 {"GetCompaniesResult":[{"CompanyId":1,"CompanyName":"CompanyName1"},{"CompanyId":2,"CompanyName":"CompanyName2"}]}

I am able to get JSON response but ArrayList<Company> returns null. I think thatonResponse is a calback method and runs in an another thread so i cant populate the list but since i am a Android newbie i dont know how to manage this issue. Any help would be appreciated.

Upvotes: 1

Views: 1904

Answers (6)

NandhaKumar Mani
NandhaKumar Mani

Reputation: 1

If You wanna json values for CompanyID and CompanyName try the below snippet. for (int i = 0; i < companiesJson.length(); i++) {

                        JSONObject jObject = companiesJson.getJSONObject(i);
                        Company company = new Company();
                        company.setCompanyId(Integer.parseInt(jObject.getString("CompanyId")));
                        Log.v(TAG, "COMPANIES setCompanyId:" + jObject.getString("CompanyId"));
                        company.setCompanyName(jObject.getString("CompanyName"));
                        Log.v(TAG, "COMPANIES setCompanyName:" + jObject.getString("CompanyName"));
                        companies.add(company);

Upvotes: 0

megha jagdale
megha jagdale

Reputation: 396

You need to create json object of each element of json array

try {
                            JSONArray companiesJson = response.getJSONArray("GetCompaniesResult");

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


                    JSONObject obj = Website.getJSONObject(i);


                                Company company = new Company();
                                company.setCompanyId(Integer.parseInt(obj.getString("CompanyId")));
                                Log.v(TAG, "COMPANIES setCompanyId:" + obj.getString("CompanyId"));
                                company.setCompanyName(obj.getString("CompanyName"));
                                Log.v(TAG, "COMPANIES setCompanyName:" + obj.getString("CompanyName"));

                                companies.add(company);
                            }

                        } catch (JSONException e) {
                            Log.v(TAG, "COMPANIES RESPONSE ERROR ON PARSING JSON:" + e.getMessage());
                        }

Upvotes: 5

Miguel Benitez
Miguel Benitez

Reputation: 2322

JsonObjectRequest works asynchronous because of that the main thread continue running and a new thread is created to run JsonObjectRequest and the result is that your returns is null. Call a method in your class to send the data back and call it when you finish managing the json data, for example:

public void manageCompaniesData(ArrayList<Company>){

    //YOUR CODE HERE.

}

Your code modified:

public ArrayList<Company> getCompanies(){

String url = AUDITTRACKINGAPP_SERVICE_URI + "GetCompanies";
        String tagJsonReq = "companiesRequest";

        final ProgressDialog pDialog = new ProgressDialog(context);
        pDialog.setMessage("Please Wait...");
        pDialog.show();

        final ArrayList<Company> companies = new ArrayList<Company>();

        JsonObjectRequest companiesRequest = new JsonObjectRequest(  Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        Log.v(TAG, "COMPANIES RESPONSE:" + response.toString());

                        try {
                            JSONArray companiesJson = response.getJSONArray("GetCompaniesResult");

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

                                JSONObject jObject = (JSONObject)companiesJson.get(i);

                                Company company = new Company();
                                company.setCompanyId(Integer.parseInt(jObject.getString("CompanyId")));
                                Log.v(TAG, "COMPANIES setCompanyId:" + jObject.getString("CompanyId"));
                                company.setCompanyName(jObject.getString("CompanyName"));
                                Log.v(TAG, "COMPANIES setCompanyName:" + jObject.getString("CompanyName"));

                                companies.add(company);
                            }

                        } catch (JSONException e) {
                            Log.v(TAG, "COMPANIES RESPONSE ERROR ON PARSING JSON:" + e.getMessage());
                        }
                        manageCompaniesData(companies);
                        pDialog.hide();
                    }
                },
                new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.v(TAG, "COMPANIES onErrorResponse:" + error.getMessage());
                    pDialog.hide();
                }
            });

    AppController.getInstance().addToRequestQueue(companiesRequest, tagJsonReq);

    }

Upvotes: 0

Ravi Theja
Ravi Theja

Reputation: 3401

Parse you json like this inside the for loop.Also Don't declare ArrayList companies as final.

Company company = new Company();
JSONObject jObject = (JSONObject)companiesJson.optJSONObject(i); 
if(jObject != null){ 
   company.setCompanyId(jObject.optInt("CompanyId")));
   company.setCompanyName(jObject.optString("CompanyName"));
}

Upvotes: 0

Rajesh Jadav
Rajesh Jadav

Reputation: 12861

JSONArray objects have a function getJSONObject(int index) so you have to use

JSONObject jObject = companiesJson.getJSONObject(i);

instead of

JSONObject jObject = (JSONObject)companiesJson.get(i);

Try this code.

for (int i = 0; i < companiesJson.length(); i++) {
  JSONObject jObject = companiesJson.getJSONObject(i);
  Company company = new Company();
  company.setCompanyId(jObject.getInt("CompanyId")));
  company.setCompanyName(jObject.getString("CompanyName"));
  companies.add(company);
 }

instead of

for (int i = 0; i < companiesJson.length(); i++) {
  JSONObject jObject = (JSONObject)companiesJson.get(i);
  Company company = new Company();
  company.setCompanyId(Integer.parseInt(jObject.getString("CompanyId")));
  Log.v(TAG, "COMPANIES setCompanyId:" + jObject.getString("CompanyId"));
  company.setCompanyName(jObject.getString("CompanyName"));
  Log.v(TAG, "COMPANIES setCompanyName:" + jObject.getString("CompanyName"));

  companies.add(company);
 }

Upvotes: 0

Bhunnu Baba
Bhunnu Baba

Reputation: 1802

if you get any JSON exception in logcat, try this once.

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

                            JSONObject jObject = companiesJson.getJSONObject(i);
                            Company company = new Company();
                            company.setCompanyId(Integer.parseInt(jObject.getString("CompanyId")));
                            Log.v(TAG, "COMPANIES setCompanyId:" + jObject.getString("CompanyId"));
                            company.setCompanyName(jObject.getString("CompanyName"));
                            Log.v(TAG, "COMPANIES setCompanyName:" + jObject.getString("CompanyName"));
                            companies.add(company);
 }

Upvotes: -1

Related Questions