I try to connect my Firestore
to ListView
. With my Query
there are put 20 records and 3 random of it, put in ArrayList
(randomPlaceList
), then I logical try to include this ArrayList
to my custom adapter
. But I miss something..
EDITED with some change variables; Now I have this error:
Process: com.example.arara.myapplication, PID: 10283
java.lang.IndexOutOfBoundsException: Index: 4, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.arara.myapplication.MainActivity$1.onComplete(MainActivity.java:46)
In this line:
Peoples item = randomPlaceList.get(randomIndex);
ListViewPlaces class:
public class MainActivity extends AppCompatActivity {
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference placeRef = rootRef.collection("peoples");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
placeRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Peoples> peoplesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Peoples peoples = document.toObject(Peoples.class);
System.out.println(peoples);
peoplesList.add(peoples);
}
if (peoplesList.size() > 0) {
System.out.println(peoplesList);
int placeCount = peoplesList.size();
Random randomGenerator = new Random();
List<Peoples> randomPlaceList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
int randomIndex = randomGenerator.nextInt(placeCount);;
Peoples item = randomPlaceList.get(randomIndex);
randomPlaceList.add(item);
}
ListView mListView = findViewById(R.id.place_list);
PeoplesAdapter peoplesAdapter = new PeoplesAdapter(getBaseContext(), randomPlaceList);
mListView.setAdapter(peoplesAdapter);
}
}
}
});
}
}
Adapter class:
public class PeoplesAdapter extends ArrayAdapter<Peoples> {
public PeoplesAdapter(Context context, List<Peoples> list) {
super(context, 0, list);
}
@NonNull
@Override
public View getView(int position, View listItemView, @NonNull ViewGroup parent) {
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
}
Peoples peoples = getItem(position);
Log.d("TAG", peoples.getName());
String name = peoples.getName();
((TextView) listItemView).setText(name);
return listItemView;
}
}
And Model class:
class Peoples {
private String name, age;
public Peoples() {}
public Peoples(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
}
Firestore database:
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…