astric mobiles
astric mobiles

Reputation: 476

How to pass data from a JSON array to a list view Android

I'm trying to parse some JSON. I'm trying to iterate through the JSON array and get all the 'ids' from each object and populate a list view using them. I've tried numerous ways but getting nowhere with it. Please see code below.

String url = "https://api.tfl.gov.uk/line/mode/tube/status";
JsonArrayRequest jsArrayRequest = new JsonArrayRequest (Request.Method.GET, url, null, new Response.Listener<JSONArray>() {

    @Override
    public void onResponse(JSONArray response) {

        int data = 0;

        try {
            // Loop through the array elements
            for (int i = 0; i < response.length(); i++) {

                // Get current json object
                JSONObject line = response.getJSONObject(i);

                // Get the current line (json object) data
                String lineName = line.getString("id");

                // Display the formatted json data in text view
                // lineNameTextView.setText(lineName);
            }

        ListView myListView = (ListView)findViewById(R.id.myListView);
        ArrayList<String> tubeLines = new ArrayList<String>();

        tubeLines.add(lineName);

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tubeLines);
        myListView.setAdapter(arrayAdapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("TAG", "Error response:", error);
    }
});

//  tempTextView.setText("Response: " + response.toString());
// Log.v("status", "Response: " + tempTextView.toString());
// Access the RequestQueue through your singleton class.
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsArrayRequest);

Upvotes: 0

Views: 5178

Answers (2)

muazhud
muazhud

Reputation: 954

Here's the working code.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ListView listView = (ListView) findViewById(R.id.list_view);
    final ArrayList<String> tubeLines = new ArrayList<>();

    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tubeLines);
    listView.setAdapter(arrayAdapter);

    RequestQueue queue = Volley.newRequestQueue(this);
    String url ="https://api.tfl.gov.uk/line/mode/tube/status";

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray array = new JSONArray(response);
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.optJSONObject(i);
                            String line = object.optString("id");
                            if (line != null) {
                                tubeLines.add(line);
                            }
                        }
                        // Once we added the string to the array, we notify the arrayAdapter
                        arrayAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });
    queue.add(stringRequest);

}

The results is as below:

enter image description here

Upvotes: 2

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

  • Create the list before loop
  • Add elements in list in each iteration instead of adding the last element into the list

otherwise it will show only the last item that you are trying to add after the loop (with compile time error due to lineName local scope)

// initialize list
ArrayList<String> tubeLines = new ArrayList<String>();

for(int i=0;i<response.length();i++) {

    // Get current json object
    JSONObject line = response.getJSONObject(i);

    // Get the current line (json object) data
    // To avoid crash use optString 
    String lineName = line.optString("id","N/A");
    // add all items
    tubeLines.add(lineName);

}

ListView myListView = (ListView)findViewById(R.id.myListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tubeLines);
myListView.setAdapter(arrayAdapter);

Upvotes: 4

Related Questions