0

I am making a quiz app. And I want that if the user kills the app their performance be uploaded on the firestore. When he clicks submit Button everything works fine but when I call submitbutton.callOnClick(); in onDestroy() some code is executed but the data is not uploaded.

this is my onDestroy() code

 protected void onDestroy() {

    Log.d(TAG, "onDestroy: ------");
    if (clicked) { } 
    else
        {
        clicked = false;
        submitButton.callOnClick();
    }


    Log.d(TAG, "onDestroy: done");

    super.onDestroy();

And this is some code of submitButton 's onClickListener

 Log.d(TAG, "onClick: ----------------------");
            Result result=new Result(new String(ansString),new String(officialAnsString),correct,incorrect,not_attempted,marks);


            FireBase_Variables.db.collection(tName+"_result").document(currentUser.getUid()).set(result);

            Log.d(TAG, "onClick: ----------------------");

I can see the upper log in the logcat but not the lower one. Which means the line for uploading data is not executed.

What should I do?

Aamir
  • 11

1 Answers1

0

You'll want to wait until the write operation is completed, before calling super.onDestroy().

If we unroll the code into a single block, that'd be something like:

protected void onDestroy() {

    Log.d(TAG, "onDestroy: ------");
    if (clicked) { } 
    else
        {
        clicked = false;
        Log.d(TAG, "onClick: ----------------------");
        Result result=new Result(new String(ansString),new String(officialAnsString),correct,incorrect,not_attempted,marks);

        FireBase_Variables.db.collection(tName+"_result").document(currentUser.getUid()).set(result).addOnCompleteListener(new new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Void aVoid) {
                Log.d(TAG, "onDestroy: done");

                super.onDestroy();
            }
        });
    }

Also see: How to check a certain data already exists in firestore or not

Note: I didn't compile/run this code, so there may be syntactic problems with it. If you encounter such problems, please try to solve them for yourself and use the edit link under the answer to fix them for folks who come here after you.

In general you'll want to do the above somewhere else than in an onDestroy handler though, as that method is fairly unlikely to be called.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807