Return from JSON array

0

My JSON returns more than one number. How do you get everyone and not one?

I would like to set the return to TextView . How to make it return all the 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);

    }
    
asked by anonymous 30.07.2017 / 15:59

1 answer

0

In this way you are doing, inserting the setText() into the repeat loop, every time the for cycles, it will override the previous value, causing it to show only the last value. p>

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

StringBuilder str = new StringBuilder();  

In your condition do this by concatenating the values within your for using the append method:

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 setText() method to show the assigned values within 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();
}
    
30.07.2017 / 16:29