1

我在从单独的类中的 asyncTask 获取结果时遇到问题。我已经从一个类似的问题回答here,但我看不出我哪里出错了。

我的 AsyncTask 在一个单独的类中以便于调用,我需要能够注意到 asynctask 已经完成,然后开始下一个活动。

我欢迎任何帮助,因为我不确定我哪里出错了。

 public class StartScreen extends Activity{

ProgressDialog pd;
CountDownTimer waitTimer;
public static final String APP_PREFERENCES = "AppPrefs";
SharedPreferences settings; 
SharedPreferences.Editor prefEditor;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start_screen);

     settings = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE);

    // getPreferences();
     //    prefEditor = settings.edit();

     waitTimer = new CountDownTimer(2000, 300) {

       public void onTick(long millisUntilFinished) {
          //called every 300 milliseconds, which could be used to
          //send messages or some other action
       }
       public void onFinish() {
          //After 2000 milliseconds (2 sec) finish current 
          //if you would like to execute something when time finishes 
           pd = ProgressDialog.show(StartScreen.this,"Title","Detail text",true,false,null);
           getPreferences();
       }
     }.start(); 
}   

private void getPreferences() {

    String UserName = settings.getString("UserName", null);

    if (UserName != null) {
        // the key does not exist
                Intent intent=new Intent(StartScreen.this,InitialPreferences.class);
                startActivity(intent);

            } else{
    //if (UserName.equals(UserName)){
        // handle the value
                dataTask();                 
                //pd.dismiss(); 
     }       
}   
        private void dataTask() {
    // TODO Auto-generated method stub
            new DATATask(this).execute(new FragmentCallback(){

                 @Override
                    public void onTaskDone() {
                     startMainAct();

                    }
                });
            }
         private void startMainAct() {
             Intent intent=new Intent(StartScreen.this,MainActivity.class);
                startActivity(intent);
            }

         public interface FragmentCallback {
                public void onTaskDone();
            }           

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.start_screen, menu);
    return true;
}
}

异步任务:

 public class DATATask extends AsyncTask<Void, Void, ArrayList<String>> {

     private FragmentCallback mFragmentCallback;
           public void execute(FragmentCallback fragmentCallback) {
                mFragmentCallback = fragmentCallback;
            }

           ArrayList<String> arr_data=new ArrayList<String>();             

           private Context context;

           public DATATask(Context context) 
           {
               this.context = context;
           }
           @Override
           protected void onPreExecute() {
               super.onPreExecute();

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

                Document docVts, docTide;
                String shippingList, tideTimes;


                try {
                    docVts = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp").timeout(600000).get(); 
                    Elements tableRows = docVts.select("table.dynlist td:eq(0),td:eq(1),td:eq(3),td:eq(4),td:eq(7),td:eq(8)");
                    tableRows.size();
                        for(int i = 1; i < 80; i++){//only allows x results from vts list, from 1 not 0. 0 produces needless results
                          shippingList = tableRows.get(i).text().replaceAll("&nbsp;| ", "") +"\n";


                          arr_data.add(shippingList);// add value to ArrayList
                          System.out.println(shippingList);
                        };       

                         docTide = Jsoup.connect("http://www.mhpa.co.uk/search-tide-times/").timeout(600000).get();
                         Elements tideTimeOdd = docTide.select("div.tide_row.odd div:eq(0)");
                         Elements tideTimeEven = docTide.select("div.tide_row.even div:eq(0)");
                         Elements tideHightOdd = docTide.select("div.tide_row.odd div:eq(2)");
                         Elements tideHightEven = docTide.select("div.tide_row.even div:eq(2)");
                            Element firstTideTime = tideTimeOdd.first();
                            Element secondTideTime = tideTimeEven.first();
                            Element thirdTideTime = tideTimeOdd.get(1);
                            Element fourthTideTime = tideTimeEven.get(1);

                            Element firstTideHight = tideHightOdd.first();
                            Element secondTideHight = tideHightEven.first();
                            Element thirdTideHight = tideHightOdd.get(1);
                            Element fourthTideHight = tideHightEven.get(1);

                            System.out.println("first tide time: " + firstTideTime.text() + "   " + firstTideHight.text()); 
                            System.out.println("second tide time: " + secondTideTime.text() + "   " + secondTideHight.text() );
                            System.out.println("third tide time: " + thirdTideTime.text() + "   " + thirdTideHight.text());
                            System.out.println("fourth tide time: " + fourthTideTime.text() + "   " + fourthTideHight.text());

                            {
                                /*
                                                Work with data - all is OK
                                                 */
                        } 
                     } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }      

                return arr_data;//<< return ArrayList from here

            }
             @Override
             protected void onPostExecute(ArrayList<String> result) {
                 mFragmentCallback.onTaskDone();
        }
      }

谢谢你的帮助。

4

4 回答 4

2

您没有调用正确的 AsyncTask.execute()。正确的执行将调用 onPreExecute() 然后 doInBackground() 然后 onPostExecute()。

 new DATATask(this).execute(new FragmentCallback(){

                 @Override
                    public void onTaskDone() {
                     startMainAct();

                    }
                });
            } 

将调用此方法(错误的方法):

   public void execute(FragmentCallback fragmentCallback) {
            mFragmentCallback = fragmentCallback;
        }

您想要做的是将此方法更改为-setFragmentCallBack(FragmentCallback);

然后在 OnPostExecute() 中添加: startMainAct();

而不是这样做:

                @Override
                public void onTaskDone() {
                 startMainAct();

                }

完成后,调用 new DATATask(this).execute(); 将调用 preExecute()、doInbackground 和 PostExecute()

您正在做的是将 FragCallback 添加到 DataTask 而不是调用正确的执行函数。

我希望这有帮助。

于 2013-10-01T20:23:17.543 回答
0

你没有执行AsyncTask. 调用DATATask.execute(FragmentCallback)只会将回调分配给您的任务。您需要调用AsyncTask#execute(Runnable)或。此外,我将通过构造函数或设置器将回调传递给,而不是创建新的重载方法。它很容易让人们感到困惑。AsyncTask#execute(Params...)AsyncTask#executeOnExecutor(Executor exec, Params... params)DATATaskexecute(FragmentCallback)

于 2013-10-01T20:24:41.233 回答
0

实际上你没有执行你的 AsyncTask。你应该调用“super.execute(Params...params);” 在您重载的 execute(FragmentCallback) 方法中。

于 2013-10-01T20:22:34.567 回答
0

在您的活动中: DataTask dataTask = new DataTask(); dataTask.execute();

在你的 AsyncTask 类中: onPostExecute(){ //把你的意图开始活动或者当它完成时你想做的任何事情}

我认为它比您制作的要简单得多。希望有帮助。另请参阅AsyncTask Android 示例

于 2013-10-01T20:24:03.797 回答