How can I ensure that the values remain updated?
They will be updated since they are member variables. However, since AsyncTask
is asynchrounous, they might not be updated yet when you check them. You can use an interface
to create a callback when these values are updated. This SO answer covers how to do this
Does that mean that any values updated in the new thread will be lost once that thread returns?
No they shouldn't be "lost". They probably just haven't been changed in the AsyncTask
when you check them.
Since this isn't your actual code I can't see when you are trying to access them but you can use the interface
method or call the functions that need these values in onPostExecute()
. You also can do a null
check before trying to access them. It just depends on the functionality and flow that you need as to which is the best way. Hope that helps.
Edit
In the answer I linked to, you tell the Activity
that you will use that interface
and override its method(s) with implements AsyncResponse
in your Activity
declaration after creating the separate interface class
public class MainActivity implements AsyncResponse{
then, in your Activity
still, you override the method you declared in that class (void processFinish(String output);
)
@Override
void processFinish(String output){ // using same params as onPostExecute()
//this you will received result fired from async class of onPostExecute(result) method.
}
then this is called in onPostExecute()
when the listener sees that it is done with delegate.processFinish(result);
delegate
is an instance of AsyncResponse
(your interface class)
public class AasyncTask extends AsyncTask{
public AsyncResponse delegate=null;
@Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
Interface
example taken from linked answer above and adjusted/commented for clarity. So be sure to upvote that answer if it helps anyone.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…