【问题标题】:method executing multiple times instead of just one方法执行多次而不是一次
【发布时间】:2018-11-21 17:57:29
【问题描述】:
Query ref = mDatabaseReference.child("Messages")
            .child(MessageRecieverId).child(MessageSenderId).orderByChild("Seen").equalTo(false);
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            long count = 0;
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                count = dataSnapshot.getChildrenCount();

                MainData helper = new MainData(getApplicationContext()); //Change the name to your Helper Class name
                SQLiteDatabase db = helper.getWritableDatabase();
                String newId = "MyData";
                Cursor data = helper.getData();
                long newDatar = 0;
                long newDatat = 0;
                while(data.moveToNext()){
                    newId = data.getString(data.getColumnIndex("Data"));
                    newDatar = data.getInt(data.getColumnIndex("TotalMessagesRecieved"));
                    newDatat = data.getInt(data.getColumnIndex("TotalMessages"));
                }
                ContentValues contentValues = new ContentValues();
                contentValues.put(KEY_DATA, newId);
                contentValues.put(KEY_TOTAL_MESSAGES_RECIEVED, (newDatar+count));
                contentValues.put(KEY_TOTAL_MESSAGES, (newDatat+count));//Change the value of newData(which is actually your old value) by incrementing
                long returnVariable = db.update(TABLE_MAIN_DATA, contentValues, null, null);

                if(returnVariable == -1){
                    Toast.makeText(getApplication(),"Nope", Toast.LENGTH_LONG).show();
                    //-1 means there was an error updating the values
                }
                else{
                    Toast.makeText(getApplication(),"r", Toast.LENGTH_SHORT).show();
                }
            }
            Log.d("CMONNN", String.valueOf(count)); //Will print the number of seen messages
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.d("CMONNN", databaseError.getMessage()); //Don't ignore errors!
        }
    });

这个问题是我第一次打开活动,如果有一个孩子要添加到 sqlite 中的表中,它通常会毫无问题地添加,然后我关闭活动并再次打开它并添加孩子两次,即使只有一个,如果我关闭并再次打开它,它会增加三次而不是一次,它会继续......那么为什么这是行为以及我如何将它更改为只执行一次,就像我第一次一样打开活动......我不能使用valueforsingleevent,因为当我每秒都在活动中时我需要听监听器......并且removelistener在关闭活动时也没有工作......所以请有人帮我

【问题讨论】:

  • 也请查看this

标签: java android database sqlite firebase


【解决方案1】:

活动结束时您可能从未移除过侦听器。您使用ref.addValueEventListener() 添加一个侦听器,但永远不要使用ref.removeEventListener() 删除它。如果您从不删除侦听器,它将继续触发新的更改。在 Android 上,您通常使这些调用对称,因此如果您在 onStart 期间添加一个侦听器,您将在 onStop 期间删除它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2017-07-07
    • 2018-09-26
    • 1970-01-01
    相关资源
    最近更新 更多