I have a Activity
which is called SpotDetails, in the onCreate
i starts a AsyncTask
in another activity. The AsyncTask
then downloads and parses an xml
file and the result should be outputted into a TextView
in the SpotDetails Activity
.
How do i accomplish this ? Snippet from main class (SpotDetails) :
public TextView TextView_WindStrenghFromVindsiden, spoTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spot_overview);
//Recive intent
Intent intent = getIntent();
//Set strings to information from the intent
//Create a intance of Place with information
place = vindsiden.createSted(intent.getStringExtra("StedsNavn"));
// TextView spoTextView = (TextView)findViewById(R.id.spot_overview_WindDegreesForeCastFromYRinfo);
spoTextView = (TextView)findViewById(R.id.spot_overview_WindDegreesForeCastFromYRinfo);
String URL = place.getNB_url();
DomXMLParser domXMLParser = new DomXMLParser();
//domXMLParser.DownloadXML(URL);
domXMLParser.DownloadXML(URL, this);
//
Snippet from AsyncTask
(DomXMLParser.java) :
TextView tv;
@Override
protected void onPreExecute() {
super.onPreExecute();
tv = (TextView) spotDetails.findViewById(R.id.spot_overview_WindDegreesForeCastFromYRinfo);
// Create a progressbar
-----Snippet from onPostExecute
tv.setText(yrMeasurmentList.get(0).getWindDirection_degree());
Exception : http://pastebin.com/WEqSdc1t
(StackOwerflow woth recognize my Exception as code. )
Don't put your AsyncTask
in another activity. If you have AsyncTask
s you are using in various places, you can either put them in a utility class or declare them in their own files. If you have an AsyncTask
which modifies the UI of only one activity, it should be declared in that activity. If the AsyncTask
is used by multiple activities, then you could pass the Activity
in the constructor, store it as a private field, and resolve the views in onPostExecute()
:
class MyAsyncTask extends AsyncTask... {
WeakReference<Activity> mActivity;
public MyAsyncTask( Activity activity ) {
super();
mActivity = new WeakReference<Activity>( activity );
}
...
public void onPostExecute(...) {
Activity act = mActivity.get();
if( act != null ) {
TextView tv = act.findViewById( ...id... );
tv.setText( "Hello World" );
} else {
// the Activity was destroyed
}
}
}
Note: I'm using a WeakReference there which will help alleviate most issues with long running AsyncTasks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.