![](/img/trans.png)
[英]How to set a text from my AsyncTask to a textview in a fragment?
[英]Set TextView from AsyncTask
我有一个称为SpotDetails的Activity
,在onCreate
我在另一个活动中启动了AsyncTask
。 然后, AsyncTask
下载并解析一个xml
文件,结果应输出到SpotDetails Activity
的TextView
中。
我该如何完成? 主类的片段(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);
//
来自AsyncTask
(DomXMLParser.java)的代码段:
TextView tv;
@Override
protected void onPreExecute() {
super.onPreExecute();
tv = (TextView) spotDetails.findViewById(R.id.spot_overview_WindDegreesForeCastFromYRinfo);
// Create a progressbar
-----摘自onPostExecute
tv.setText(yrMeasurmentList.get(0).getWindDirection_degree());
例外: http : //pastebin.com/WEqSdc1t
(StackOwerflow可以将我的异常识别为代码。)
不要将您的AsyncTask
放在另一个活动中。 如果您有在不同地方使用的AsyncTask
,则可以将它们放在实用程序类中或在它们自己的文件中声明。 如果您有一个AsyncTask
只能修改一个活动的UI,则应在该活动中声明它。 如果AsyncTask
由多个活动使用,则可以在构造函数中传递Activity
,将其存储为私有字段,然后在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
}
}
}
注意:我在此处使用WeakReference,这将有助于缓解长期运行的AsyncTasks的大多数问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.