java - 在android中添加新数据时ArrayList数据被清除

标签 java android firebase google-cloud-firestore

所以我的问题很简单,但我还没有找到解决方案。我有一个 ArrayList,用于存储单击按钮的用户的 uid(用户 ID)。然后,该数据会发送到 firebase 的 Cloud Firestore。当用户单击按钮时,用户 uid 会保存在 ArrayList 中。但是,当我使用其他用户登录并单击按钮时,第二个用户的 uid 不会将第二个用户的 uid 添加到 ArrayList,而是会覆盖整个 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);

下一个代码 fragment 是我认为问题所在的地方。当我在按钮按下方法中将 Arraylist 声明为 new 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);

整个 Activity 代码,

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);
    }
}

最佳答案

是的,你是对的。在这一行:

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<>();

关于java - 在android中添加新数据时ArrayList数据被清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49245270/

相关文章:

java - Java 和 Python 运算符优先级的不同结果

java.lang.NoSuchMethodError : com. 更快的xml.jackson.databind.JavaType.isReferenceType()Z

android - 在 VideoView 中打开 RTSP 视频

firebase - 谷歌预定函数 : There was an error deploying functions?

android - 由于 firebase-auth 依赖性,Gradle 构建失败

java - 我如何暂停扫描仪阅读以广播消息?

Android - 小部件点击监听器不起作用

android - 之前未打开应用程序时,广播接收器在重启后抛出错误

java - 如何在 firebase 数据库中一次性修改所有经过身份验证的用户的数据

java - 容器和元素之间触发事件的解决方案?