1

I am having a problem with getting the result from an asyncTask in a separate class. I have followed from a similar questions answer on here but I cant see where I have gone wrong.

My AsyncTask is in a separate class for easy calling, I needed to be able to have the notice that the asyntask had completed and then start the next activity.

I would welcome any help as I am not sure quite where I have gone wrong.

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

Thanks for any help.

J4C3N-14
  • 686
  • 1
  • 13
  • 32
  • Define your own `Interface` with a call back method. `implement` the `Interface` in both classes. – Simon Oct 01 '13 at 20:22

4 Answers4

2

You are not calling the correct AsyncTask.execute(). The correct execute will invoke the onPreExecute() then doInBackground() then onPostExecute().

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

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

                    }
                });
            } 

will call this method (the wrong one):

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

What you want to do is change this method to - setFragmentCallBack(FragmentCallback);

Then in the OnPostExecute() add this: startMainAct();

instead of doing this:

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

                }

After this is done, then call the new DATATask(this).execute(); which will invoke the preExecute(), doInbackground, and PostExecute()

What you are doing is adding the FragCallback to the DataTask and not invoking the correct execute function.

I hope this helps.

wseme
  • 805
  • 6
  • 14
0

Actually you did not execute your AsyncTask. You should call "super.execute(Params... params);" in you overloaded execute(FragmentCallback) method.

armansimonyan13
  • 956
  • 9
  • 15
0

In your Activity: DataTask dataTask = new DataTask(); dataTask.execute();

In your AsyncTask class: onPostExecute(){ //put your intent to start the activity or whatever you want to do when it finishes }

I think it is much simpler than you are making it. Hope that helps. Also, see AsyncTask Android example

Community
  • 1
  • 1
Eric Cochran
  • 8,414
  • 5
  • 50
  • 91
0

You didn't execute the AsyncTask. Calling DATATask.execute(FragmentCallback) will just assign the callback to your task. You need to call either AsyncTask#execute(Runnable), AsyncTask#execute(Params...) or AsyncTask#executeOnExecutor(Executor exec, Params... params). Also, I would pass the callback to DATATask via the constructor or a setter, instead of creating a new overloaded execute(FragmentCallback) method. It can easily confuse people.

huy.nguyen
  • 454
  • 2
  • 9