Monika Verma Monika Verma - 3 months ago 19
JSON Question

how to parse JsonArray and set value on Textview in Android

Below is my Json response from getting when Hit on Url with parsing parameter strlogid=101

[

{

"earnpoints": 411,
"type": "C"
},

{

"earnpoints": 1600,
"type": "G"
},

{

"earnpoints": 13540,
"type": "I"
}

]


Below is my code-To show Points on 3 different textview

private class PointTask extends AsyncTask<String, Void, Boolean> {

protected Boolean doInBackground(final String... args) {

JSONParse jParser = new JSONParse();

HashMap<String, String> hMap = new HashMap<>();
hMap.put("strlogid", "101");
JSONArray jsonarray = jParser.getJSONFromUrl(url,hMap);

// get JSON data from URL
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject c = (JSONObject) jsonarray.get(i);
c_point=c.getString("points");
g_point=c.getString("points");
i_point=c.getString("points");
t_point = cpoint+gpoint+ipoint;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(final Boolean success) {
txtTotalPoints.setText(t_point);
txtOwnPoints.setText(g_point);
txtClubPoints.setText(c_point);
txtVoucherPoints.setText(i_point);

}
}


TotalPoints,OwnPoints,ClubPoints,VoucherPoints are show on Textview respectively

Answer

Try this

protected Boolean doInBackground(final String... args) {

        JSONParse jParser = new JSONParse();

        HashMap<String, String> hMap = new HashMap<>();
        hMap.put("strlogid", "101");
        JSONArray jsonarray = jParser.getJSONFromUrl(url,hMap);

        // get JSON data from URL
        for (int i = 0; i < jsonarray.length(); i++) {
                JSONObject c = (JSONObject) jsonarray.get(i);
                if (c.getString("type").toString().equalsIgnoreCase("C")) {
                    c_point = c.getInt("earnpoints");
                } else if (c.getString("type").toString().equalsIgnoreCase("G")) {
                    g_point = c.getInt("earnpoints");
                } else if (c.getString("type").toString().equalsIgnoreCase("I")) {
                    i_point = c.getInt("earnpoints");
                }
            }
            t_point = cpoint + gpoint + ipoint;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
        }
    @Override
    protected void onPostExecute(final Boolean success) {
        txtTotalPoints.setText(t_point);
        txtOwnPoints.setText(g_point);
        txtClubPoints.setText(c_point);
        txtVoucherPoints.setText(i_point);

    }
}
Comments