Я пытался иметь в своей модели id
документа, но когда я обращаюсь к нему, значение идентификатора равно null
.
Во фрагменте / активности:
public class MyEventsFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private FirestorePagingAdapter mAdapter;
private FirebaseFirestore mFirebaseFirestore;
public MyEventsFragment() {
// Required empty public constructor
}
public static MyEventsFragment newInstance() {
return new MyEventsFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseFirestore = FirebaseFirestore.getInstance();
Query query = mFirebaseFirestore.collection("events");
PagedList.Config config = new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPrefetchDistance(10)
.setPageSize(20)
.build();
FirestorePagingOptions<Event> options = new FirestorePagingOptions.Builder<Event>()
.setLifecycleOwner(this)
.setQuery(query, config, new SnapshotParser<Event>() {
@NonNull
@Override
public Event parseSnapshot(@NonNull DocumentSnapshot snapshot) {
Event evt = new Event(
snapshot.getId(),
snapshot.getString("titre"),
snapshot.getString("sport"),
snapshot.getString("lieu"),
snapshot.get("date", Timestamp.class),
snapshot.get("dateLimit", Timestamp.class));
Log.i("TEST", evt.toString());
return evt;
}
})
.build();
mAdapter = new EventFirestorePagingAdapter(options, getContext());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_events, container, false);
RecyclerView mRecyclerView = view.findViewById(R.id.recyclerViewListEvent);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onStart() {
super.onStart();
mAdapter.startListening();
}
@Override
public void onStop() {
super.onStop();
mAdapter.stopListening();
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
EventFirestorePagingAdapter (расширяет FirestorePagingAdapter):
public class EventFirestorePagingAdapter extends FirestorePagingAdapter<Event, EventFirestorePagingAdapter.EventViewHolder> {
private Context mContext;
public EventFirestorePagingAdapter(@NonNull FirestorePagingOptions<Event> options, Context context) {
super(options);
this.mContext = context;
}
public class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView titre, sport, lieu, date;
public EventViewHolder(@NonNull View itemView) {
super(itemView);
titre = itemView.findViewById(R.id.titreRecyclerView);
sport = itemView.findViewById(R.id.sportRecyclerView);
lieu = itemView.findViewById(R.id.lieuRecyclerView);
date = itemView.findViewById(R.id.dateRecyclerView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
/*for(Map.Entry<String, Object> map: getItem(getAdapterPosition()).getData().entrySet()){
Log.i("TEST", map.getKey());
}*/
Event event = getItem(getAdapterPosition()).toObject(Event.class);
Log.i("TEST", "id = " + event.getId());
Toast.makeText(mContext, "OnClick on position : " + getAdapterPosition() + " \nTest : " + event.getTitre() + "\nId : " + event.getId(), Toast.LENGTH_LONG).show();
}
}
@Override
protected void onBindViewHolder(@NonNull EventViewHolder holder, int position, @NonNull Event model) {
holder.titre.setText(model.getTitre());
holder.sport.setText(model.getSport());
holder.lieu.setText(model.getLieu());
holder.date.setText(model.getDate().toDate().toString());
}
@NonNull
@Override
public EventViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recyclerview_card_row, viewGroup, false);
return new EventViewHolder(view);
}
}
Класс события:
public class Event {
private String id;
private String titre;
private String sport;
private String lieu;
private Timestamp date;
private Timestamp dateLimit;
public Event(){ } // Needed for Firebase
public Event(String id, String titre, String sport, String lieu, Timestamp date, Timestamp dateLimit) {
this.id = id;
this.titre = titre;
this.sport = sport;
this.lieu = lieu;
this.date = date;
this.dateLimit = dateLimit;
}
// ... getters & setters
}
Отладка:
1) TEST: Event {id = 'c5jUGQc4c7SHzbpT6N01', titre= 'Финальный PSG / MARSEILLE', спорт = 'Футбол', lieu = 'Берси', дата = метка времени (секунды = 1550844000, наносекунды = 0), dateLimit = метка времени (секунды = 1551009600, наносекунды = 0)}
2) TEST: id = null
База данных Firestore:
База данных Firestore
Суть с той же проблемой
Ответ:
SnapshotParser не сработал, как я ожидал, но я узнаю, как получить доступ к идентификатору документа в onClick ().Я заменил эту строку на следующий код:
DocumentSnapshot documentSnapshot = getCurrentList().get(getAdapterPosition());
Chat chat = documentSnapshot.toObject(Chat.class);
chat.setId(documentSnapshot.getId());