单独创建一个AsyncTask类

时间:2012-02-29 15:22:46

标签: android android-asynctask

更新2

logcat的:

03-02 19:03:47.616: E/AndroidRuntime(881): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{TheTask}: java.lang.InstantiationException:  .TheTask
03-02 19:03:47.616: E/AndroidRuntime(881):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
03-02 19:03:47.616: E/AndroidRuntime(881):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-02 19:03:47.616: E/AndroidRuntime(881):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-02 19:03:47.616: E/AndroidRuntime(881):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-02 19:03:47.616: E/AndroidRuntime(881):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-02 19:03:47.616: E/AndroidRuntime(881):  at android.os.Looper.loop(Looper.java:123)
03-02 19:03:47.616: E/AndroidRuntime(881):  at android.app.ActivityThread.main(ActivityThread.java:3683)
03-02 19:03:47.616: E/AndroidRuntime(881):  at java.lang.reflect.Method.invokeNative(Native Method)
03-02 19:03:47.616: E/AndroidRuntime(881):  at java.lang.reflect.Method.invoke(Method.java:507)
03-02 19:03:47.616: E/AndroidRuntime(881):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-02 19:03:47.616: E/AndroidRuntime(881):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-02 19:03:47.616: E/AndroidRuntime(881):  at dalvik.system.NativeStart.main(Native Method)
03-02 19:03:47.616: E/AndroidRuntime(881): Caused by: java.lang.InstantiationException: TheTask
03-02 19:03:47.616: E/AndroidRuntime(881):  at java.lang.Class.newInstanceImpl(Native Method)
03-02 19:03:47.616: E/AndroidRuntime(881):  at java.lang.Class.newInstance(Class.java:1409)
03-02 19:03:47.616: E/AndroidRuntime(881):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-02 19:03:47.616: E/AndroidRuntime(881):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ProgressBar
        android:id="@+id/the_progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 <ListView
     android:id="@+id/android:list"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_weight="0.63" />
</LinearLayout>

TestingAsyncTask

//The class that starts the task
public class TestingAsyncTask extends ListActivity {

    private ProgressBar bar = null; 
    private ArrayList<String> data = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thetask);
        bar = (ProgressBar) findViewById(R.id.the_progress);
        data.add("1");
        data.add("2");
        data.add("3");

        Log.d("create", ""+ data.size());

        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data));
        new TheTask(this).execute((Void) null);     
    }

    public ArrayList<String> getData() {
        return data;
    } 
}

thetask.java异步文件

//The AsyncTask class
public class TheTask extends AsyncTask<Void, Void, List<String>> {

    Context c;

    public TheTask(Context c) {
        this.c = c;
    }   

    @Override
    protected void onPreExecute() {
        ((TestingAsyncTask) c).findViewById(R.id.the_progress).setVisibility(View.VISIBLE);
    }



    @Override
    protected List<String> doInBackground(Void... params) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ArrayList<String> res= new ArrayList<String>();
        res.add("a");
        res.add("b");
        res.add("c");
        Log.d("doinbacground", ""+ res.size());
        return res;
    }

    @Override
    protected void onPostExecute(List<String> result) {
        TestingAsyncTask activity = ((TestingAsyncTask) c);
        activity.getData().clear();
        activity.getData().addAll(result);
        ((ArrayAdapter)activity.getListAdapter()).notifyDataSetChanged();
        ((TestingAsyncTask) c).findViewById(R.id.the_progress).setVisibility(View.GONE);
    }

}

结束更新2

UPDATE1:

Description Resource    Path    Location    Type
m_ProgressDialog cannot be resolved GrabUrlAsyncTask.java   
line 81 Java Problem
The field Main.m_orders is not visible   GrabUrlAsyncTask.javaline 79   
Java Problem
The field Main.m_ProgressDialogis not visible   GrabUrlAsyncTask.javaline 
80  Java Problem
The method notifyDataSetChanged() is undefined for the type ListAdapter GrabUrlAsyncTask.java   
line 82 Java Problem

更新

@Override 
        protected void onPostExecute(List<Employee> result) 
        {            
            //showToast("You have to be connected to the internet for this application to work");   
            m_orders.clear();     
            m_orders.addAll(result);   
            progress.dismiss();
            mContext.m_adapter.notifyDataSetChanged();   
        } 

我一直在研究一个应用程序而且我已经设法让AsyncTask在内部类时工作正常,这意味着在同一个main.java class中,当我查看代码时它看起来如此很难进入,我打算重构代码,以便AsyncTask将其onw单独的类。

我开始这样做了,但后来提出了一些问题,比如,我将如何显示ProgressDialog box or toastText

请问安博迪可以给我一些方向吗?

这是我的代码:

public class Main extends ListActivity{

     @Override
     public void onCreate(Bundle savedInstanceState) 
     {
           ............
           .............
           new taskDoSomething().execute();


     } //

     private class taskDoSomething extends AsyncTask<Void, Void, List<Employee>> 
     {
           @Override 
      protected List<Surah> doInBackground(Void... params) 
      {
                //do some stuffs...
                try {
                     ///
                catch (Exception e)
                {
                   //
                }

            } 

            protected void onProgressUpdate(Void... values)
      {
              super.onProgressUpdate(values);         
         m_ProgressDialog.dismiss();  
            } 

            protected void onPostExecute(List<Employee> result)
      {
              m_orders.clear();     
        m_orders.addAll(result);   
        m_ProgressDialog.dismiss();
        m_adapter.notifyDataSetChanged();             
           }  
     } 
}

2 个答案:

答案 0 :(得分:5)

AsyncTask中创建一个类似Context的构造函数:

private Context context; //field in your AsyncTask

public taskDoSomething(Context context) {
    this.context = context;
}

然后在您创建任务的活动中:

new taskDoSomething(this).execute();

现在,在您的AsyncTask中,您有一个Context(可以转回到您的活动中),您可以使用此上下文显示您想要的内容。

修改Context参数强制转换为您的类,然后您可以访问该类的所有字段。例如,如果您的m_orders是您班级中的公共字段,则可以像下面那样访问它,或者您可以为m_orders制作getter / setter方法:

protected void onPostExecute(List<Employee> result) {
         Main activity = (Main) context;
         activity.m_orders.clear();     
         activity.m_orders.addAll(result);   
         m_ProgressDialog.dismiss();
         activity.getListAdapter().notifyDataSetChanged();             
}

答案 1 :(得分:0)

我已在我的项目中的单独类中实现了异步。我已经传递了上下文和一个界面。 Context用于启动ProgressBar,Interface用于执行原始类中的代码。以下是代码。

public class EventAsync {


    public EventAsync(Context ct,EVRequestCallback gt)
    {

    }

      public static abstract class EVRequestCallback {
            public abstract void requestDidFail(ArrayList<EventItem> ei);
            public abstract void requestDidLoad(ArrayList<EventItem> ei);
      }
      public static class RetrieveEventFeeds extends AsyncTask<Void, Void, ArrayList<EventItem>>
    {
          Context mContext;
          private EVRequestCallback mCallback;
        public RetrieveEventFeeds(Context ct,EVRequestCallback gt)
        {
            mContext= ct;
            mCallback=gt;
        }
        private ProgressDialog progress = null;

        @Override
        protected ArrayList<EventItem> doInBackground(Void... params) {

            return retrieveRSSFeed("url",this.mContext);


        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPreExecute() {
            progress = ProgressDialog.show(
                    mContext, null, "Loading ...",true,true);

            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(ArrayList<EventItem> result) {
        //setListAdapter();
            mCallback.requestDidLoad(result);
            progress.dismiss();
            //Toast.makeText(this.mContext, "current done", Toast.LENGTH_SHORT).show();
            super.onPostExecute(result);
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }
    }