Stevry Stevry - 1 month ago 9
Android Question

Get Specific Json Object based on textview

Hy Guys, I am newbie in android developers,
I need help to get Specific object based on text on textview and show it on another text view,

Here is my json data

{
"card_data": [{
"card_id": "123456",
"balance": "100000"
}, {
"card_id": "654321",
"balance": "50000"
}]
}


For example on my TextView1 I have "123456",
how can I display "100000" on TextView2.

Thanks in advanced, and sorry for my bad English.

Answer

First create setter and getter for your json. See below code.

private class CardInfo
{
    private String cardId;
    private String balance;

    public CardInfo(String cardId, String balance) {
        this.cardId = cardId;
        this.balance = balance;
    }

    public String getCardId() {
        return cardId;
    }

    public String getBalance() {
        return balance;
    }
}

Then create JsonParser for your Json Object and add json obj as a CardInfoObj in ArrayList.

private ArrayList<CardInfo> mList = new ArrayList<>();
private void jsonParser()
{

    try {
        JSONObject jsonObject = new JSONObject("{\n" +
                "\t\"card_data\": [{\n" +
                "\t\t\"card_id\": \"123456\",\n" +
                "\t\t\"balance\": \"100000\"\n" +
                "\t}, {\n" +
                "\t\t\"card_id\": \"654321\",\n" +
                "\t\t\"balance\": \"50000\"\n" +
                "\t}]\n" +
                "}");
        JSONArray jsonArray = jsonObject.getJSONArray("card_data");
        for(int i=0;i<jsonArray.length(); i++)
        {
            JSONObject user = jsonArray.getJSONObject(i);
            mList.add(new CardInfo(user.get("card_id").toString(), user.get("balance").toString()));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Now In mList having cardId and balance for each json obj. now get cardinfo obj from mList.

private void setText()
{
    CardInfo cardInfo = mList.get(0);// get specfice obj based on your requirement.
    mTvCard.setText(cardInfo.getCardId());
    mTvBalance.setText(cardInfo.getBalance());
}