Reputation: 5975
I have a few Activities implement an Interface ( called NetworkListener). When requesting information from a remote server, they spawn an instance of a class (called NetworkRequest). NetworkRequest is a threaded class that sends requests to the server, waits for the response and sends it back to the requesting NetworkListener object. It could take up to 10 seconds to return data back to the NetworkListener instance. During that time, it is quite possible that that Activity or Fragment no longer exists, and a lot of the actions based on the server call are no longer valid and will throw NPEs, such as:
((TextView) findViewById(R.id.server_status)).setText("Server response: " + response.getMsg());
What's the best way to ensure that the requesting class is still alive and able to update UI?
Currently at the top of every method that receives calls back from the server I have:
if (getWindow() == null) { // or getView()/getActivity() if Fragment
finish();
return;
}
This seems inefficient and redundant. Is there a better method to what I'm trying to accomplish?
Thanks!
Upvotes: 2
Views: 353
Reputation: 5798
You can move the logic checking state of activity / fragment to the NetworkRequest. Add isActive() method to NetworkListener interface. NetwrokRequest sends response to NetworkListener only if the latter is active.
You can set activity / fragment activeness in onCreate() -> active and onDestroy() -> inactive.
Just be wary of activity state changes like when rotating screen. Then, you get a new activity which doesn't get server's response, which might not be what you want.
Upvotes: 1
Reputation: 4389
You can use AsyncTask to do your network request. When the request is no longer needed the AsyncTask can be cancelled.
Upvotes: 0