I'm new to android programming so you'll need to bear with me.
I'm trying to retrieve a column from parse server and display it in a ListView. So far i have produced the following code however I've encountered an issue. In my for loop it should fetch each item from the "name" column from the "Absences" class and add it to the ArrayList called "teachers".
The issue is the app crashes because the array is null (after printing it in the logs) and it therefore can't assign it to the ArrayAdapter. I believe the reason for this is that the objects are fetched in the background some time after the arrayadapter code is executed meaning its trying to display an empty array.
I'm assuming i need to delay it somehow - any ideas on what i should do?
Affected code inside the onCreate() method:
final ArrayList<String> teachers = new ArrayList<String>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Absences");
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
for(ParseObject object : objects){
String name = String.valueOf(object.get("name"));
Log.i("teacherName", name);
teachers.add(name);
}
} else {
Log.i("Get data from parse", "There was an error getting data!");
e.printStackTrace();
}
}
});
Log.i("teacherOutput", teachers.toString());
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, teachers);
ListView lv = (ListView)findViewById(R.id.listView);
lv.setAdapter(arrayAdapter);
Many thanks in advance!
You need to learn what asynchronous means.
Your code should be something like:
final ListView lv = (ListView) findViewById(R.id.listView);
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
ArrayList<String> teachers = new ArrayList<String>();
for (ParseObject object : objects) {
String name = String.valueOf(object.get("name"));
Log.i("teacherName", name);
teachers.add(name);
}
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, teachers);
lv.setAdapter(arrayAdapter);
} else {
Log.i("Get data from parse", "There was an error getting data!");
e.printStackTrace();
}
}
});