AsyncTask回调没有调用

时间:2013-10-01 20:08:49

标签: java android callback android-asynctask

我遇到了在单独的类中从asyncTask获取结果的问题。我在这里听到了类似的问题答案,但我不知道我哪里出错了。

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

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

 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;
}
}

的AsyncTask:

 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 个答案:

答案 0 :(得分: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而不是调用正确的执行函数。

我希望这会有所帮助。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

在AsyncTask类中: onPostExecute(){     //表达你的意图,开始活动或完成后你想做的任何事情 }

我认为这比制作它简单得多。希望有所帮助。另请参阅AsyncTask Android example

答案 3 :(得分:0)

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