Prevent Activity from starting the old Instance

Issue

I’m trying to display the contacts to be saved in an user group in the FirebaseDatabase.

The app works fine for the first time, but when I do the path again, after a button is pressed, the app don’t repeat the first result.

Here is an example:
MainActivity calls GroupActivity;
GroupActivity calls NewUserActivity and
NewUserActivity goes back to MainActivity after a button is pressed.

Inside NewUserActivity there are codes related to FirebaseDatabase in which contacts are loaded and added in different paths.

Here is the Logcat and summarized explanation:
First Round.
The app starts normally
In the first screen are shown the names of the groups

debinf mainpage: onStart
debinf mainpage: onResume
debinf mainpage: onPause
debinf mainpage: onResume

Here comes the first click on a item in the RecyclerView.
Here is shown the users in the group.
At the bottom of the screen there is a floatActionButton

debinf mainpage: onPause
debinf groupactivity: onStart
debinf groupactivity: onResume
debinf mainpage: onStop

Here I clicked on floatActionButton to go to the NewUserActivity.
Here I copy the users already in the group
to a temporary path in the FirebaseDatabase
and also load my contact list in my device
in the RecyclerView.

debinf groupactivity: onPause
debinf newuser: onCreate
debinf groupact: passed intentextrasA
debinf groupact: passed intentextrasB
debinf newuser: onStart
debinf newuser: onResume
debinf newuser: Load peopleA to ContactAdded
debinf newuser: Load peopleB to ContactAdded
debinf newuser: Load peopleC to ContactAdded
debinf groupactivity: onStop
debinf groupactivity: onDestroy

Here are shown the loaded contacts in the upper RecyclerView
and the contact list of my device in the lower RecyclerView.
The action of adding and removing contacts
to the temporary path is not shown here
to simplify the example.
After choosing who is in and who is out of the group,
I press the button to finalize and save the contacts
in the group path in the FirebaseDatabase.

debinf newuser: button pressed
debinf newuser: Added peopleA inside button
debinf newuser: Added peopleB inside button
debinf newuser: Finish inside the button
debinf newuser: onPause
debinf mainpage: onRestart
debinf mainpage: onStart
debinf mainpage: onResume
debinf newuser: onStop
debinf newuser: onDestroy

As expected, the MainActivity is called
after I press the button in the NewUserActivity.
So far so good

Second Round.
Now let’s do the same process again.
I clicked on the group name to go to GroupActivity.

debinf mainpage: onPause
debinf groupactivity: onStart
debinf groupactivity: onResume
debinf mainpage: onStop

Now I clicked on the floatActionButton.

debinf groupactivity: onPause
debinf newuser: onCreate
debinf groupact: passed by intentextrasA
debinf groupact: passed by intentextrasB
debinf newuser: onStart
debinf newuser: onResume
debinf newuser: Load peopleA to ContactAdded
debinf newuser: Load peopleB to ContactAdded
debinf newuser: button pressed
debinf newuser: Added peopleA inside button
debinf newuser: Added peopleB inside button
debinf newuser: Finish inside the button
debinf groupactivity: onStop
debinf groupactivity: onDestroy

As can be seen, the button was pressed by itself.

And I was hoping to go up to load people to new path
and choose again who is in and who is out.

I think this have to do with saved instance.

What do I have to do to prevent the NewUserActivity to go by itself?
because this causes a mess with the process of adding and removing
contacts. Besides that, I end up removing all of my contacts from the group.

Thanks in advance!

MORE INFO: Click listener for the adapter of MainActivity

holder.mLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent groupActivity = new  Intent(mContext,GroupActivity.class);
        groupActivity.putExtra("groupName",groupList.get(position).getGroupId());
        groupActivity.putExtra("groupPushKey",groupList.get(position).getGroupKey());
        // Because we are in Adapter, the Adapter does not know what context is
        // so the activity is started from the mContext
        mContext.startActivity(groupActivity);

    }
});

FloatActionButton in the GroupActivity

AddContact = (FloatingActionButton) findViewById(R.id.addContactInGroup);
AddContact.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        Intent newUserToGroup = new Intent(getApplicationContext(),NewUserToGroupActivity.class);
        newUserToGroup.putExtra("groupName",groupNameIntent);
        newUserToGroup.putExtra("groupPushKey",groupKeyIntent);
        startActivity(newUserToGroup);
        finish();

    }
});

Click listener for the button in the NewUserActivity

mUpdateGroupBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        updateGroupUsers();
    }
});

Where:

private void updateGroupUsers() {

    RootRef.child("ContactAdded").child(currentUser).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                Log.i("debinf newuser", "button pressed");

                Map<String, Object> updateGroupUsersMap = new HashMap<>();

                for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {

                    Log.i("debinf newuser", "Added people inside button : " + childSnapshot.getKey());
                    updateGroupUsersMap.put(childSnapshot.getKey(),"");

                }

                FirebaseDatabase.getInstance().getReference().child("Group").child(currentUser).child(groupKeyIntent).child(groupNameIntent).setValue(updateGroupUsersMap);

                FirebaseDatabase.getInstance().getReference().child("ContactAdded").child(currentUser).removeValue();

                Log.i("debinf newuser","Finish inside the button");
                finish();

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

Solution

There’s something wrong in what you do in updateGroupUsers.

This is called when a user presses a button, so you need to perform some task immediately, instead you register a ValueEventListener and wait for onDataChange to occur, and only then you perform this action.

Obviously, since you never remove that added listener, the listener is still listening for data changes, and whenever a new data change is detected it performs the action again, falsely printing “button pressed” to the log, even though the button wasn’t pressed.

I would recommend either cleaning up after yourself, and once you do not need a listener, remove it.
or preferably, try performing the action you intend to perform without putting it in some listener, as this might introduce some race condition between the data-change you’re expecting at that moment, and the action you want performed.

Answered By – marmor

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published