Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finish activity when a response is returned from the server, but wait for animation to end

I send a request to server via Volley; And after send, increase a variable that show number of requests.

VolleyGeneral.getInstance().addToRequestQueue(jsonObj,TAG);
numberOfReq++;

Then when I get the response, decrease that variable.

@Override
public void onResponse(JSONObject response){
    numberOfReq--;
}

On another side, i'm showing an image, using fade in animation for 2 seconds then I finish the activity and go to the next activity.

But i want to wait for all the server responses before finishing the activity. So i write this part like it:

@Override
public void onAnimationEnd(Animation anim){
    while(numberOfReq == 0){
        numberOfReq = -1;
        startActivity(intent);
        finish();
        break;
    }
}

If server send the responses before 2 second, everything is Okey.

But if response is received after 2 second, the activity doesn't finish.

like image 220
Dr.jacky Avatar asked Jun 29 '14 14:06

Dr.jacky


1 Answers

Maybe I'm not understanding the question, because the answer seems incredibly simple. Just set a flag whenever the activity is "ready to finish", and then check for this condition in onResponse() too.

Either onAnimationEnd() or the last onResponse() will run first, and the second one should start the second activity. For example:

private boolean mReadyToProceed;

@Override
public void onAnimationEnd(Animation anim)
{
    if (numberOfReq == 0)
        startOtherActivityAndFinish();
    else
       mReadyToProceed = true;
}

@Override
public void onResponse(JSONObject response)
{
    numberOfReq--;
    if (mReadyToProceed && numberOfReq == 0)
        startOtherActivityAndFinish();
}

(Note: make sure that the decrement and comparison is not affected by other request threads finishing, possibly with locks or by using AtomicInteger).

like image 166
matiash Avatar answered Sep 22 '22 02:09

matiash