Reputation: 25
I am making an app that can insert data's in the Firestore. Each data has different Document names, How to get the Document names to be inserted in an Array Adapter? Can you give me some examples? This is the picture of my simple Array Adapter code and my Fire Store.
Upvotes: 0
Views: 76
Reputation: 138944
The simplest solution to display the place names in a ListView using an ArrayAdapter would be to create a reference to "Marker PLaces":
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference placesRef = rootRef.collection("Marker PLaces");
Assuming you already have a "ListView" in your .XML file that looks like this:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/place_list"/>
Create a Place class:
class Place() {
private String latitude, longitude, placeName;
private Date timestamp;
public Place() {}
public Place(String latitude, String longitude, String placeName) {
this.latitude = latitude;
this.longitude = longitude;
this.placeName = placeName
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
public String getPlaceName() {
return placeName;
}
}
Then define the adapter class:
public class PlacesAdapter extends ArrayAdapter<Place> {
public PlacesAdapter(Context context, List<Place> 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);
}
Place place = getItem(position);
String placeName = place.getPlaceName();
((TextView) listItemView).setText(placeName);
return listItemView;
}
}
Then in your onCreate()
method use the following code:
List<Place> placeList = new ArrayList<>();
ListView mListView = (ListView) findViewById(R.id.place_list);
PlacesAdapter placesAdapter = new PlacesAdapter(getApplicationContext(), placeList);
mListView.setAdapter(placesAdapter);
And right after that, get the data and notify the adapter about the changes:
placesRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Place place = document.toObject(Place.class);
placeList.add(place);
}
placesAdapter.notifyDataSetChanged();
}
}
});
The result of this code will be ListView full of place names.
Upvotes: 1