Json Object for ListView

1

Good afternoon everyone,

I have two classes, the bemVindo and the one that receives data in json and saves it in an object, and after the json data is received, the class sends the data to the bemVindo of the data received in String to a TextView. Any idea how I can display this data in a ListView in bemVindo ?

I think the correct thing is to use ArrayLists and Adapters, but I do not have a lot of experience and I've tried in several ways, can anyone help? Thanks!

Class that receives and saves json in String

 //DATA PARSED
        //ArrayList<String> items = new ArrayList<String>();
        JSONArray JA = new JSONArray(data);

        for(int i = 0;i<JA.length();i++){
            JSONObject JO = (JSONObject) JA.get(i);

            String id=JO.getString("id");
            String name=JO.getString("name");      

            singleParsed = "ID: "+JO.get("id")+"\n"+
                    "Name: "+JO.get("name")+"\n";

            dataParsed=dataParsed+singleParsed+"\n";
}

/*Aqui ele seta o texto recebido para a variavel public static da bemVindo activity*/

@Override
protected void onPostExecute(Void aVoid) {

    bemVindo.data.setText(this.dataParsed);
    super.onPostExecute(aVoid);
}
    
asked by anonymous 12.03.2018 / 16:49

1 answer

2

First change the class that receives and saves the JSON in String to create a String ArrayList:

ArrayList<String> items = new ArrayList<String>();

JSONArray JA = new JSONArray(data);

for(int i = 0;i<JA.length();i++){
    JSONObject JO = (JSONObject) JA.get(i);

    String id=JO.getString("id");
    String name=JO.getString("name");



    singleParsed = "ID: "+JO.get("id")+"\n"+
            "Name: "+JO.get("name")+"\n";

    items.add(singleParsed);
}

@Override
protected void onPostExecute(Void aVoid) {
    bemVindo.data.setText(this.items);
    super.onPostExecute(aVoid);
}

In the Activity XML, create a ListView:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

In Java's Activity do the following:

ListView listview = (ListView) findViewById(R.id.listview);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);

listview.setAdapter(adapter);

Source: link

Read also about GSON

    
12.03.2018 / 17:15