Reputation: 1599
I have a server, from which i get the values that i need(name, date, city, picture_url). To get them are in getValues class. I'm using Json. All the values are saved in an ArrayList called array. I would use them in multiple classes. I would like to call the array in FragmentB. This is the code for the ArrayList
private ArrayList<String> array;
`array = new ArrayList<String>();
array.add(finalresult.getString("picture"));
array.add(finalresult.getString("name"));
array.add(finalresult.getString("date"));
array.add(finalresult.getString("city"));`
Then i thought i needed some kind of function, so it can be called, from other classes. I wanted to name the function, then arguments are numbers, so you can select which element you want, then you just return the object you wanted.
public ArrayList<String> getEvent(int pos)
{
return array.get(pos);
}
But here i get an error:
Required: java.util.ArrayList <java.lang.String>
Found: java.lang.String
In Fragment, i want the specific element of the array, and save it in one string, so i can call it later.
Something like this:
public class FragmentB extends android.support.v4.app.ListFragment{
private GetEvents getEvents = new GetEvents();
private String picture1, name1, city1, date1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
picture1 = getEvents.getArray(0);
name1 = getEvents.getArray(1);
city1 = getEvents.getArray(2);
date1 = getEvents.getArray(3);
}
}
I know that this is wrong. What is the correct way to pass the elements, and then call them in the fragment?
Upvotes: 0
Views: 736
Reputation: 6033
For the error, it is just that getEvent(int pos)
should return a String
and not a List<String>
.
If (name, city, date, picture) is an object of your application model (I understand that these are used in several places), you may take advantage to create a simple pojo class to hold these infos, e.g.
public class Event {
String name, city, url;
Date date;
// +constructor
// +getters
}
Then you can store, pass as parameter, filter, sort Event
s and access properties with specific methods without ambiguity.
Actually storing values with different meaning in an array is bad practice: an array should contain objects of the same nature, e.g. a list of Event
, a list of city
, etc. Think of what will happen if the order in the array changes. Does it make sense to have city
at position 0
and name
at 1
?
Upvotes: 0