1

我是 Android 编程新手,我想知道是否可以毫无问题地使用以下代码片段,或者是否存在一些样式问题。该代码完全有效:

public class SelectTeamActivity extends Activity {

    private HashMap<String, String> keyValues;
    private MyXMLHandler xmlHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_team);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        xmlHandler = new MyXMLHandler(this);
        xmlHandler.execute(urlHandler.getUserDataURL());
    }
}

这是 asycncron 任务的自定义类:

public class MyXMLHandler extends AsyncTask<String, String, String> {

    private String pin;
    SAXParser sp;
    DefaultHandler userData;
    private SelectTeamActivity selectTeamActivity;

    public MyXMLHandler(SelectTeamActivity selectTeamActivity) {
      this.selectTeamActivity = selectTeamActivity;
    }

    public String getPin() {
    return pin;
    }

    @Override
    protected String doInBackground(String... address) {
    try {
        URL url= new URL(address[0]);
        URLConnection yc = url.openConnection();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        sp = spf.newSAXParser();
        userData = new DefaultHandler() {
        public void startElement(String uri, String localName, String qName, Attributes attributes)
            throws SAXException {
            if (localName.equals("entry")) {
            pin = attributes.getValue("pin");
            }
        }

        };
        sp.parse(yc.getInputStream(), userData);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return pin;
    }

    protected void onPostExecute(String result) {
        TextView text = (TextView) selectTeamActivity.findViewById(R.id.textView1);
        text.setText(result);
    }
}

我将活动类“SelectTeamActivity”的“this”引用传递给 MyXMLHandler 构造函数,以在运行任务的函数“doInBackground”完成后更新 UI。

这个可以吗?

我正在搜索与“在 AsynTask 类中更新 UI”相关的其他一些问题,但我只找到了扩展“AsyncTask”的类仅作为 UI Activity 类的内部类实现的解决方案。在那里访问 UI 完全没有问题。

问候

4

0 回答 0