-1

I want to call back same asynctask after its completion how do i do so. i want to sync my messages from server regularly. currently i am using timer to run this method regularly but its not worthy so i want to call back this method after its completion

here is my async task function

private class syncMessageFromServer extends AsyncTask<Void, Integer, String> {

        @Override
        protected void onPreExecute() {
            // setting progress bar to zero
            //progressBar.setProgress(0);
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {

        }

        @Override
        protected String doInBackground(Void... params) {
            return uploadFile();
        }

        @SuppressWarnings("deprecation")
        private String uploadFile() {
            String str = "";
            HttpResponse response;
            HttpClient myClient = new DefaultHttpClient();
            HttpPost myConnection = new HttpPost("http://192.168.1.2/AndroidApp/GetMessage?loginUserInfoId="+loginUserInfoId+"&recieverUserInfoId="+receiverUserInfoId+"&isPendingToSynce="+true);

            try {
                response = myClient.execute(myConnection);
                str = EntityUtils.toString(response.getEntity(), "UTF-8");

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try{
                JSONArray jArray = new JSONArray(str);
                for(int i = 0; i<=jArray.length()-1; i++)
                {
                    JSONObject row = jArray.getJSONObject(i);
                    ChatMessage cm = new ChatMessage();
                    String onlineFileURL = "";
                    String upFileURL = row.getString("FileAttachedURL").replace(" ", "%20");
                    String offlineFileURL = "";

                    if(!upFileURL.isEmpty()) {
                        onlineFileURL = "http://192.168.1.2" + row.getString("FileAttachedURL").replace(" ", "%20");
                        downloadBitmap(onlineFileURL);

                        String fileName = upFileURL.substring(upFileURL.lastIndexOf('/') + 1, upFileURL.length());
                        offlineFileURL = Environment.getExternalStorageDirectory() + File.separator + "/Planetskool/Media/Images/" + fileName;
                    }
                    else {
                        offlineFileURL = "";
                    }

                    /******* Firstly take data in model object ******/
                    cm.setOriginalMsgThreadId(row.getString("MessageThreadId"));
                    cm.setSenderUserInfoId(row.getString("SenderUserId"));
                    cm.setReceiverUserInfoId(row.getString("MultipleReceiversId"));
                    cm.setMessageStatus("SENT");
                    cm.setIsPending(0);
                    cm.setMessageText(row.getString("MessageText"));
                    cm.setMediaURL(offlineFileURL);
                    cm.setThumbImage(offlineFileURL);
                    cm.setMediaMIMEType("");
                    cm.setMediaSize(0);
                    cm.setMediaName("");
                    cm.setLatitude("");
                    cm.setLongitude("");
                    cm.setSendTimeStamp(row.getString("SendTime"));
                    cm.setReceiveTimeStamp(row.getString("ReadTime"));
                    long messageThreadId = db.SendMessage(cm);

                    confirmSyncedToServer(row.getString("MessageId"));

                    chatMessageAdapter.add(cm);
                }
            } catch ( JSONException e) {
                e.printStackTrace();
            }

            return str;

        }

        @Override
        protected void onPostExecute(String result) {

            new syncMessageFromServer.execute();
            super.onPostExecute(result);
        }

    }
Ameer
  • 2,709
  • 1
  • 28
  • 44
Neeraj Mehta
  • 1,675
  • 2
  • 22
  • 45

1 Answers1

0

One way to do it is to set an activity as a handler, so to speak, and then have that activity rerun your task whenever the complete is called. Create an interface and have your activity implement it like so:

public interface ResponseInterface {
    public void processResponse(String output);
}

Have your activity implement it:

public class Activity implements ResponseInterface {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyAsyncTask task = new MyAsyncTack(this);
        task.execute();
        //do other stuff here
    }

    @Override
    public void processResponse(String output) {
        MyAsyncTask task = new MyAsyncTask(this);
        task.execute();   
    }
}

and tweak your asynctask to contain a reference like so:

public class MyAsyncTask extends AsyncTask<Void, Integer, String> {

    public ResponseInterface response;

    public MyAsyncTask(ResponseInterface response) {
        this.response = response;
    }

    // return the results of the asynctask to the calling method
    @Override
    protected void onPostExecute(String result) {
         //returns null if no response or if error
         response.processResponse(result);
    }
}
Matter Cat
  • 1,538
  • 1
  • 14
  • 23
  • where i will right public interface ResponseInterface { public void processResponse(String output); }. – Neeraj Mehta Feb 11 '15 at 06:02
  • Add it as a separate class file is the way I usually do it. – Matter Cat Feb 11 '15 at 06:05
  • its not updating my messages – Neeraj Mehta Feb 11 '15 at 06:08
  • if u can then please tell my about background service. – Neeraj Mehta Feb 11 '15 at 06:11
  • Stick a couple breakpoints at processResponse to see if it's being called. The way it works is that you start the task in onCreate -> the task completes and calls onPostExecute -> the activity is called via processResponse -> the task executes again. Walk through the cycle to make sure that everything is getting called appropriately and that your asynctask is completing as it should. – Matter Cat Feb 11 '15 at 06:11
  • java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) – Neeraj Mehta Feb 11 '15 at 06:14
  • Hmm. Which line is it failing on? – Matter Cat Feb 11 '15 at 06:21
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/70678/discussion-between-user1447477-and-neeraj-mehta). – Matter Cat Feb 11 '15 at 06:27