Oghenemaro Afenogho
Oghenemaro Afenogho

Reputation: 28

Android:How do I display data from multiple array of strings in a local JSON file?

I have been trying to populate my listView from a local JSON file. The JSON file has multiple arrays of strings so I had to use the for loop multiple times but the problem now is, when I run my app, it only repeats the details of the first JSON object(id1 i.e. i=1) leaving out the rest. Any help would be much appreciated.

Edit: I think the for loops are interfering with one another somehow. I just don't know how but I have tried so many different things and the result still has not changed. Without the third and second and third for loops, the code returns all objects (i.e. i=0,1,2,3,4) but adding those loops to access the other arrays only displays the element of i=0 for all cases of i. here's my JSON:

[{
    "id": 1,
    "start_year": 1990,
    "end_year": 2010,
    "gender": "male",
    "countries": ["China", "South Africa", "france", "Mexico", "Japan", "Estonia", "Colombia", "China"],
    "colors": ["Green", "Violet", "Yellow", "Blue", "Teal", "Maroon", "Red", "Aquamarine", "Orange", "Mauv"]
}, {
    "id": 2,
    "start_year": 1990,
    "end_year": 2010,
    "gender": "",
    "countries": ["China", "South Africa", "france", "Mexico", "Japan", "Estonia", "Colombia", "China"],
    "colors": ["Green", "Violet", "Yellow", "Blue", "Teal", "Maroon", "Red", "Aquamarine", "Orange", "Mauv"]
}, {
    "id": 3,
    "start_year": 1980,
    "end_year": 2002,
    "gender": "female",
    "countries": [],
    "colors": ["Green", "Violet", "Yellow", "Blue", "Teal", "Maroon", "Red", "Aquamarine", "Orange", "Mauv"]
}, {
    "id": 4,
    "start_year": 1990,
    "end_year": 2000,
    "gender": "",
    "countries": [],
    "colors": []
}, {
    "id": 5,
    "start_year": 1990,
    "end_year": 2009,
    "gender": "",
    "countries": ["China", "South Africa", "france", "Mexico", "Japan", "Estonia", "Colombia", "China"],
    "colors": []
}]

here's my MainActivity.java:

package com.android.oghenemaroafenogho;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<Filter> filtersList = new ArrayList<Filter>();
    private FiltersAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView filtersListView = findViewById(R.id.list);

        mAdapter = new FiltersAdapter(this, new ArrayList<Filter>());
        filtersListView.setAdapter(mAdapter);

        getJsonData();

    }

    // JSON method to get JSON locally
    public ArrayList<Filter> getJsonData() {
        String json;

        try {
            InputStream venten = getAssets().open("assessment.json");
            int size = venten.available();
            byte[] buffer = new byte[size];
            venten.read(buffer);
            venten.close();

            json = new String(buffer, "UTF-8");

            JSONArray jsonArray = new JSONArray(json);

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                int startYear = jsonObject.getInt("start_year");
                int endYear = jsonObject.getInt("end_year");
                String gender = jsonObject.getString("gender");
                if (gender.length() == 0) {
                    gender = "no gender";
                }

                JSONArray countryArray = jsonObject.getJSONArray("countries");
                for (int j = 0; j < countryArray.length(); j++) {
                    String country = countryArray.getString(j);

                    if (countryArray.length() == 0) {
                        country = "No country found";
                    }


                    JSONArray colorArray = jsonObject.getJSONArray("colors");
                    for (int n = 0; n < colorArray.length(); n++) {
                        String color = colorArray.getString(n);

                        if (colorArray.length() == 0) {
                            color = "No color found";
                        }

                        Filter carFilters = new Filter(startYear, endYear, gender, country, color);
                        filtersList.add(carFilters);

                        if (carFilters != null) {
                            mAdapter.addAll(carFilters);
                        }
                    }
                }
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return filtersList;
    }
}

FiltersAdapter:

package com.android.oghenemaroafenogho;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;

public class FiltersAdapter extends ArrayAdapter<Filter> {

    public FiltersAdapter(Context context, ArrayList<Filter> filters) {
        super(context, 0, filters);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        View listView = convertView;
        if (listView == null) {
            listView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);

            Filter currentFilter = getItem(position);

            TextView startYear = listView.findViewById(R.id.start_year);
            startYear.setText(Integer.toString(currentFilter.getYear()));

            TextView endYear = listView.findViewById(R.id.end_year);
            endYear.setText(Integer.toString(currentFilter.getEndYear()));

            TextView gender = listView.findViewById(R.id.gender);
            gender.setText(currentFilter.getGender());

            TextView country = listView.findViewById(R.id.country);
            country.setText(currentFilter.getCountry());

            TextView color = listView.findViewById(R.id.color);
            color.setText(currentFilter.getColor());

        }
        return  listView;
    }
}

Upvotes: 1

Views: 83

Answers (1)

mohamed morsi
mohamed morsi

Reputation: 58

try

mAdapter = new FiltersAdapter(this,  getJsonData());
filtersListView.setAdapter(mAdapter);

instead of

mAdapter = new FiltersAdapter(this, new ArrayList<Filter>());
filtersListView.setAdapter(mAdapter);
getJsonData();

and do not forget to remove this block

if (carFilters != null) {
    mAdapter.addAll(carFilters);
}

Upvotes: 2

Related Questions