2013-10-01 99 views
1

我在從一個單獨的類中的asyncTask獲取結果時遇到問題。我在這裏也回答了類似的問題的答案,但我不知道我錯在哪裏。AsyncTask callback not calling

我的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(); 
     } 
     } 

感謝您的幫助。

+0

使用回調方法定義您自己的「接口」。在兩個類中實現'Interface'。 – Simon

回答

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而不是調用正確的執行功能。

我希望這會有所幫助。

+0

嗨,謝謝你的出色答案,我應該在哪裏改變方法; setFragmentCallBack(FragmentCallback);謝謝 –

+0

在DataTask類中。替換:公共無效執行(FragmentCallback fragmentCallback) – wseme

+0

感謝您一直致力於這在今天得到它去,感謝您的幫助。 –

0

其實你沒有執行你的AsyncTask。你應該調用「super.execute(Params ... params);」在你重載execute(FragmentCallback)方法。

0

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

在你的AsyncTask類: onPostExecute(){// 把你的意圖開始任何你想要的,當它完成 做活動或}

我覺得它比你使它更簡單。希望有所幫助。另請參閱AsyncTask Android example

0

您沒有執行AsyncTask。調用DATATask.execute(FragmentCallback)只會將回調分配給您的任務。您需要撥打AsyncTask#execute(Runnable)AsyncTask#execute(Params...)AsyncTask#executeOnExecutor(Executor exec, Params... params)。 另外,我會通過構造函數或setter將回調傳遞給DATATask,而不是創建一個新的超載execute(FragmentCallback)方法。它可能容易混淆人。