Итак, моя проблема проста, но мне не удалось найти решение. У меня есть ArrayList, в котором хранятся uid (идентификатор пользователя) пользователей, которые нажали кнопку. Затем эти данные отправляются в Cloud Firestore firebase. Когда пользователь нажимает кнопку, пользовательский uid сохраняется в ArrayList. Но когда я вхожу в систему с другим пользователем и нажимаю кнопку, вместо добавления второго uid пользователя в ArrayList, uid второго пользователя перезаписывает весь ArrayList, и только uid второго пользователя сохраняется в Cloud Firestore.
collectionReference = FirebaseFirestore.getInstance().collection("Fields");
collectionReference.document(venueID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (!task.getResult().exists()){
//Here I declare the arrayList if the document doesn't exist
peopleHereThisUpdates = new ArrayList<>();
//The document that gets saved in Firestore,
// peopleHereThisUpdates is the main point in this question
Map<String, Object> field = new HashMap<>();
field.put(FIELD_NAME, venueName);
field.put(PEOPLE_HERE_KEY, peopleHere);
field.put(PEOPLE_HERE_BY_UID, peopleHereThisUpdates);
collectionReference.document(venueID).set(field);
Я думаю, что проблема заключается в следующем фрагменте кода. Поскольку я объявляю Arraylist как новый Arraylist в методе нажатия кнопки, новый список массивов создается при каждом нажатии кнопки. Как я могу предотвратить это?
public void onButtonPressImHere() { //This gets called when button is pressed
peopleHereThisUpdates = new ArrayList<>(); //This is the possible problem
peopleHereThisUpdates.add(uid);
collectionReference.document(venueID).update(PEOPLE_HERE_BY_UID, peopleHereThisUpdates);
Весь код активности,
public class DetailFieldActivity extends Activity{
public final String PEOPLE_HERE_KEY = "People Here";
public final String FIELD_NAME = "Field Name";
public final String CURRENT_FIELD = "Current Field";
public final String UID = "Uid";
public final String PEOPLE_HERE_BY_UID = "People here by uid";
ImageButton imTrainingHereButton;
int peopleHere;
//Get the size of this
FirebaseFirestore db = FirebaseFirestore.getInstance();
// The details of the venue that is being displayed.
String venueName;
private String venueID;
private CollectionReference collectionReference;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DocumentReference reference;
String uid = user.getUid();
ArrayList<String> peopleHereThisUpdates;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_field_detail);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
imTrainingHereButton = findViewById(R.id.imTrainingHereButton);
Bundle venue = getIntent().getExtras();
venueName = venue.getString("name");
venueID = venue.getString("ID");
setTitle(venueName);
TextView fieldName = findViewById(R.id.fieldName);
fieldName.setText(venueName);
collectionReference = FirebaseFirestore.getInstance().collection("Fields");
collectionReference.document(venueID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (!task.getResult().exists()){
//Here I declare the arrayList if the document doesn't exist
peopleHereThisUpdates = new ArrayList<>();
//The document that gets saved in Firestore,
// peopleHereThisUpdates is the main point in this question
Map<String, Object> field = new HashMap<>();
field.put(FIELD_NAME, venueName);
field.put(PEOPLE_HERE_KEY, peopleHere);
field.put(PEOPLE_HERE_BY_UID, peopleHereThisUpdates);
collectionReference.document(venueID).set(field);
}
}
});
}
@Override
protected void onStart() {
super.onStart();
imTrainingHereButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onButtonPressImHere();
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void onButtonPressImHere() {
reference =
FirebaseFirestore.getInstance().collection("Users").document(uid);
Map<String, Object> users = new HashMap<>();
users.put(CURRENT_FIELD, venueName);
users.put(UID, uid);
reference.set(users);
peopleHereThisUpdates = new ArrayList<>();
peopleHereThisUpdates.add(uid);
collectionReference.document(venueID).update(PEOPLE_HERE_BY_UID,
peopleHereThisUpdates);
}
}
2 ответа
Да ты прав. Вот в этой строке:
peopleHereThisUpdates = new ArrayList<>(); //This is the possible problem
Новый экземпляр ArrayList
будет создаваться каждый раз при срабатывании события. Так что удалите это и инициализируйте переменную peopleHereThisUpdates
в объявлении: ArrayList<String> peopleHereThisUpdates = new ArrayList<>();
или переместите ее из метода onButtonPressImHere
в какое-нибудь другое место, например, около начала метода onCreate
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
peopleHereThisUpdates = new ArrayList<>();
Просто создайте модель представления для своей деятельности и объявите там своего arraylist. когда активность уничтожается, значение arraylist в модели представления останется прежним.
Похожие вопросы
Связанные вопросы
Новые вопросы
java
Java - это язык программирования высокого уровня. Используйте этот тег, если у вас возникли проблемы с использованием или пониманием самого языка. Этот тег редко используется отдельно и чаще всего используется вместе с [spring], [spring-boot], [jakarta-ee], [android], [javafx], [hadoop], [gradle] и [maven].