'how to use simple getter and setter with android

I have a class country with an arraylist that stores countries. I have created a get and set to add and get items from specified indexes from the array list but i wont work. Whenever i call an index from the arraylist i get an out of bounds exception because the array is empty or at least seems to be.

public class country extends Application {

    public ArrayList<country> countryList = new ArrayList<country>();
    public String Name;
    public String Code;
    public String  ID;

    public country()
    {

    }

    public country(String name, String id, String code)
    {
        this.Name = name;
        this.ID = id;
        this.Code = code;
    }

    public void setCountry(country c)
    {
        countryList.add(c);
    }

    public country getCountry(int index)
    {   
        country aCountry = countryList.get(index);
        return aCountry;
    }

to call the setter i use. i do this inside a for loop so it adds 200+ elements

country ref = new country();

ref.setCountry(new country (sName, ID, Code));

then when i want to get an index

String name = ref.countryList.get(2).Name;

i have done the same thing but used a local arraylist and it populated fine and i was able to display the names so the datasource isnt the problem its whatever im doing wrong setting and getting the data inside the arraylist in the country class



Solution 1:[1]

You access a non-existing index. You only add one country ergo you can only access:

String name = ref.countryList.get(0).Name;

And you should really rethink your design. public attributes are not the best-practice way. This is the reason why you should write getter and setter methods in the first place.

You should do something like this instead:

public Country getCountry(int index)
{
    if(index < countryList.size())
    {
        return countryList.get(index);
    }
    return null;
}

Solution 2:[2]

in String name = ref.countryList.get(2).Name; you are trying to get the third element in the list while you added only one...
it should be String name = ref.countryList.get(0).Name; and you need to check before for not receiving null pointer exception

Solution 3:[3]

Do ref.countryList.get(0).Name as you have added only 1 item into the list.

I would suggest more of it like

 ref.countryList.get(0).getName()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Lerps
Solution 2 Nermeen
Solution 3 Vineet Singla