From Json Object to Listview

Asked

Viewed 418 times

1

Good afternoon to all,

I have two classes, the bemVindo and the one that receives data in json and stores in an object and after the json data is received the class sends to the bemVindothe data received in String for a Textview. Any idea how I can display this data in a Listview at bemVindo?

I believe that the correct thing will be to use Arraylists and Adapters, but I don’t have much experience and I have tried several ways, can anyone help? Thank you!

Class that receives and stores 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);
}

1 answer

2


First change the class that receives and stores 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 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 the Java of 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: https://www.androidpro.com.br/listviews/

Read also about GSON

Browser other questions tagged

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