Issue
Here I've given a small example of the problem I'm facing with global variables and AsyncTasks. I've gone and read in data from a file and assigned that data to a string and in the onPostExecute() method I assigned that string to the global variable. However when I assign the TextView with the "aString" variable, the output is still "nothing".
I know that if you do the TextView assigning in the onPostExecute() method it works however what if I want to use the data in methods outside of the AsyncTask.
Can someone please help with this, I think I'm not getting something?
public class GoodAsync extends Activity{
TextView tv;
String aString = "nothing";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.asynctasks);
new AsyncTasker().execute();
tv = (TextView) findViewById(R.id.async_view);
tv.setText(aString);
}
private class AsyncTasker extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... arg0) {
AssetManager am = GoodAsync.this.getAssets();
String string = "";
try {
// Code that reads a file and stores it in the string variable
return string;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
aString = result;
}
}
}
Solution
Perhaps you want to do it like this:
public class GoodAsync extends Activity{
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.asynctasks);
tv = (TextView) findViewById(R.id.async_view);
new AsyncTasker().execute();
}
public void setTextView (String text) {
tv.setText(text);
}
private class AsyncTasker extends AsyncTask<String, Integer, String>{
....
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
setTextView(result);
}
}
}
Answered By - DieselPower
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.