Return of JSON array

Asked

Viewed 487 times

0

My JSON returns more than one number. How to receive all and not one?

I would like to set the return on one TextView. How to make it return all values and not only the first?

JSONObject json = new JSONObject(result);

JSONArray array = new JSONArray(json.getString("resource"));
for (int i = 0; i < array.length(); i++) {

    JSONObject jsonObj = array.getJSONObject(i);

    mId_user = jsonObj.getString("id_user");
    mValorAnuncioVenda = jsonObj.getString("vl_anuncio");
    mNegativo = jsonObj.getString("vl_pago");
    mIdComp = jsonObj.getString("id_user_comp");

    if ((mIdComp != null) & (mNegativo != null)) {
        mPositivo = mNegativo;
        negativo.setText(mPositivo);

    }
  • It wasn’t clear what you want. You just posted an excerpt of code that doesn’t finish. What would be the return value? That code there is inside some method?

1 answer

0


This way as you are doing, inserting the setText() inside the loop of repetition, every time the for give a complete cycle, it will override the previous value, causing it to show only the last value.

Use StringBuilder to store the values before using the method setText(). Behold:

StringBuilder str = new StringBuilder();  

Within your condition do so by concatenating the values within your for using the method append:

if ((mIdComp != null) & (mNegativo != null)) {
   mPositivo = mNegativo;
   // aqui você concatena os valores usando 
   str.append(mPositivo);
   str.append(" ");
}

Finally, after the loop, you use the method setText() to show the assigned values inside the for :

negativo.setText(str.toString());

See the complete code:

StringBuilder str = new StringBuilder();

JSONObject json = new JSONObject(result);
JSONArray array = null;
try {
    array = new JSONArray(json.getString("resource"));
    for (int i = 0; i < array.length(); i++) {

        JSONObject jsonObj = array.getJSONObject(i);

        mId_user = jsonObj.getString("id_user");
        mValorAnuncioVenda = jsonObj.getString("vl_anuncio");
        mNegativo = jsonObj.getString("vl_pago");
        mIdComp = jsonObj.getString("id_user_comp");

        if ((mIdComp != null) & (mNegativo != null)) {
            mPositivo = mNegativo;

            str.append(mPositivo);
            str.append(" ");
        }
    }
    negativo.setText(str.toString());

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.