method executing multiple times instead of just one











up vote
0
down vote

favorite












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


The problem with this is the first time i open the activity and if there is one child to be added to the table in sqlite it adds normally without any problem and then i close the activity and i open it again and it adds the child twice even if there is just one and if i close and open it again it adds thrice instead of one and it just goes on... So why is this behavious and how can i change it to executing just once like the first time i open the activity... And i cannot use valueforsingleevent as i need to listen to listener when im inside the activity every second... and the removelistener too didnt work while closing the activity... So someone please help me out










share|improve this question






















  • Check also this out.
    – Alex Mamo
    yesterday















up vote
0
down vote

favorite












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


The problem with this is the first time i open the activity and if there is one child to be added to the table in sqlite it adds normally without any problem and then i close the activity and i open it again and it adds the child twice even if there is just one and if i close and open it again it adds thrice instead of one and it just goes on... So why is this behavious and how can i change it to executing just once like the first time i open the activity... And i cannot use valueforsingleevent as i need to listen to listener when im inside the activity every second... and the removelistener too didnt work while closing the activity... So someone please help me out










share|improve this question






















  • Check also this out.
    – Alex Mamo
    yesterday













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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


The problem with this is the first time i open the activity and if there is one child to be added to the table in sqlite it adds normally without any problem and then i close the activity and i open it again and it adds the child twice even if there is just one and if i close and open it again it adds thrice instead of one and it just goes on... So why is this behavious and how can i change it to executing just once like the first time i open the activity... And i cannot use valueforsingleevent as i need to listen to listener when im inside the activity every second... and the removelistener too didnt work while closing the activity... So someone please help me out










share|improve this question













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


The problem with this is the first time i open the activity and if there is one child to be added to the table in sqlite it adds normally without any problem and then i close the activity and i open it again and it adds the child twice even if there is just one and if i close and open it again it adds thrice instead of one and it just goes on... So why is this behavious and how can i change it to executing just once like the first time i open the activity... And i cannot use valueforsingleevent as i need to listen to listener when im inside the activity every second... and the removelistener too didnt work while closing the activity... So someone please help me out







java android database sqlite firebase






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 days ago









Nikki Zepher

686




686












  • Check also this out.
    – Alex Mamo
    yesterday


















  • Check also this out.
    – Alex Mamo
    yesterday
















Check also this out.
– Alex Mamo
yesterday




Check also this out.
– Alex Mamo
yesterday












1 Answer
1






active

oldest

votes

















up vote
1
down vote













It's probable that you never removed the listener when the activity finished. You add a listener with ref.addValueEventListener(), but never remove it with ref.removeEventListener(). If you never remove a listener, it will continue to trigger with new changes. On Android, you typically make those call symmetrical, so if you add a listener during onStart, you would remove it during onStop.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418007%2fmethod-executing-multiple-times-instead-of-just-one%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote













    It's probable that you never removed the listener when the activity finished. You add a listener with ref.addValueEventListener(), but never remove it with ref.removeEventListener(). If you never remove a listener, it will continue to trigger with new changes. On Android, you typically make those call symmetrical, so if you add a listener during onStart, you would remove it during onStop.






    share|improve this answer

























      up vote
      1
      down vote













      It's probable that you never removed the listener when the activity finished. You add a listener with ref.addValueEventListener(), but never remove it with ref.removeEventListener(). If you never remove a listener, it will continue to trigger with new changes. On Android, you typically make those call symmetrical, so if you add a listener during onStart, you would remove it during onStop.






      share|improve this answer























        up vote
        1
        down vote










        up vote
        1
        down vote









        It's probable that you never removed the listener when the activity finished. You add a listener with ref.addValueEventListener(), but never remove it with ref.removeEventListener(). If you never remove a listener, it will continue to trigger with new changes. On Android, you typically make those call symmetrical, so if you add a listener during onStart, you would remove it during onStop.






        share|improve this answer












        It's probable that you never removed the listener when the activity finished. You add a listener with ref.addValueEventListener(), but never remove it with ref.removeEventListener(). If you never remove a listener, it will continue to trigger with new changes. On Android, you typically make those call symmetrical, so if you add a listener during onStart, you would remove it during onStop.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 2 days ago









        Doug Stevenson

        65.3k77997




        65.3k77997






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418007%2fmethod-executing-multiple-times-instead-of-just-one%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            What visual should I use to simply compare current year value vs last year in Power BI desktop

            Alexandru Averescu

            Trompette piccolo