如何将AsyncTask与Activity分开?

时间:2012-09-04 09:05:33

标签: android

我想将ClassAsyncTask用于一个单独的类,我试图但没有成功。我需要一个明确的信息如何做这个或一个想法我该怎么做。在此先感谢。

public class XMLParser extends Activity {

    String targetURL = "http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml";
    TextView name[], website[], category[];
    LinearLayout linearLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /* layout to display the view */
        linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(1);

        /* Set the ContentView to layout for display */
        this.setContentView(linearLayout);

        ClassAsyncTask asyncTask = new GBAsyncTask();
        asyncTask.execute(targetURL);

    }

    //
    public class ClassAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {

            try {

                /* Handling XML */
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();

                /* Send URL to parse XML Tags */
                URL sourceUrl = new URL(targetURL);

                /* Create handler to handle XML Tags ( extends DefaultHandler ) */
                MyXMLHandler myXMLHandler = new MyXMLHandler();
                xr.setContentHandler(myXMLHandler);
                xr.parse(new InputSource(sourceUrl.openStream()));

            } catch (Exception e) {
                System.out.println("XML Pasing Excpetion = " + e);
            }
            return null;
        }

        /* Return-value from doInBackground */
        protected void onPostExecute(String result) {

            /* Get result from MyXMLHandler SitlesList Object */
            SiteList sitesList = MyXMLHandler.sitesList;

            /* Assign TextView array length by arrayList size */
            name = new TextView[sitesList.getName().size()];
            website = new TextView[sitesList.getName().size()];
            category = new TextView[sitesList.getName().size()];

            int h = sitesList.getName().size();
            /* Set the result text in TextView and add it to layout */
            for (int i = 0; i < h; i++) {
                name[i] = new TextView(getApplicationContext());
                name[i].setText("Name = " + sitesList.getName().get(i));
                website[i] = new TextView(getApplicationContext());
                website[i]
                        .setText("Website = " + sitesList.getWebsite().get(i));
                category[i] = new TextView(getApplicationContext());
                category[i].setText("Website Category = "
                        + sitesList.getCategory().get(i));
                linearLayout.addView(name[i]);
                linearLayout.addView(website[i]);
                linearLayout.addView(category[i]);
            }
        }
    }
}

感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用ClassAsyncTask从其他班级访问XMLParser.ClassAsyncTask

如果要使子类独立于父类(以扩大其用法),则应确保删除对父类的类变量的任何引用。在您的情况下,这是targetURL。 您可以通过创建存储目标URL的类构造函数来完成此操作。

答案 1 :(得分:0)

您可以将它分开并移交当前上下文和构造函数中回调方法的接口实现,例如:

public class JSONLoader extends AsyncTask<String, Void, String> {
    private AsyncTaskCompleteListener<String> callback;
    private Context context;
    ..

    public JSONLoader(Context context, AsyncTaskCompleteListener<String> cb) {
        this.context = context;
        this.callback = cb;
    }

    ..
    // callback method implemented by calling activity:
    protected void onPostExecute(String result) {
        // call callback method
        callback.onTaskComplete(result);
    }
}

任务以这种方式从活动开始(请注意,它不需要扩展FragmentActivity。它可以扩展Activity或其任何子类:

public class MainActivity extends FragmentActivity 
    implements AsyncTaskCompleteListener<String> {

    public void onCreate(Bundle savedInstanceState) {
        ..
        JSONLoader jsonLoader = new JSONLoader(this, this);
        jsonLoader.execute(getString(R.string.datasource_url_list));
    }

    // from AsyncTaskCompleteListener interface
    public void onTaskComplete(String result) {
        // your callback method implementation
    }
    ..
}

这是您的活动可用于定义不同回调方法的接口:

public interface AsyncTaskCompleteListener<T> {
    public void onTaskComplete(T result);

}