从AsyncTask设置TextView

时间:2014-02-28 17:46:14

标签: java android android-asynctask

我有一个名为SpotDetails的Activity,在onCreate我在另一个活动中开始AsyncTaskAsyncTask然后下载并解析xml文件,结果应输出到SpotDetails TextView中的Activity

我如何做到这一点? 主类(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将我的异常识别为代码。)

1 个答案:

答案 0 :(得分:0)

不要将您的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的大多数问题。