0

I am using AsyncTask to fetch data from server, what if to check whether any new data available or to update changes in existing data in every 10 seconds

public class MainActivity extends Activity {

    CenterLockHorizontalScrollview centerLockHorizontalScrollview;
    ArrayList<Actors> actorsList;   
    ActorAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        actorsList = new ArrayList<Actors>();
        new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");

        centerLockHorizontalScrollview = (CenterLockHorizontalScrollview) findViewById(R.id.scrollView);                              
    }


    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading, please wait");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);
        }

        @Override
        protected Boolean doInBackground(String... urls) {
            try {

                //------------------>>
                HttpGet httppost = new HttpGet(urls[0]);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);

                // StatusLine stat = response.getStatusLine();
                int status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);


                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("actors");

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject object = jarray.getJSONObject(i);

                        Actors actor = new Actors();

                        actor.setName(object.getString("name"));
                        Log.d("Name:", object.getString("name"));
                        actor.setImage(object.getString("image"));
                        Log.d("Image:", object.getString("image"));

                        actorsList.add(actor);
                    }
                    return true;
                }

                //------------------>>

            } catch (ParseException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return false;
        }

        protected void onPostExecute(Boolean result) {
    dialog.cancel();           
    if(result == false)
        Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
    if(actorsList != null) {
        adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);      
        centerLockHorizontalScrollview.setAdapter(MainActivity.this, adapter); 
    }

    }

}
Sophie
  • 2,594
  • 10
  • 41
  • 75

2 Answers2

2

you can check by using refresh method.

 void refresh(boolean b){
    if(b){
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
            refresh(true);
        }
    }, 10*1000);
    }
}

call this method in your oncreate

 new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
 refresh(true);
Chowdary102
  • 106
  • 2
  • 12
2

There is several ways on going about this. The most suitable one will depends mostly on the specs, design & architecture decision for you're app.

1) Java's TimerTask.

import java.util.Timer;
Timer timer = new Timer(); 

timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
    // work
  }
}, 0, 10*1000); // 0 - time before first execution, 10*1000 - repeating of all subsequent executions

timer.cancel(); //cancels the timer and all schedules executions

2) Android's Handler. Powerful feature and commonly used for things like what you are asking. But, you must make sure you are not nesting handlers. More info here ; it describes more or less the solution for what you are looking for using Handlers.

3) Android's scheduled alarms. Even though this would work, if you really want to run something every 10 seconds, then, i will say this is probably not the best solution. But anyway, this allows you register for Android's alarms, which gives you a bit of time to run something in a BroadcastReceiver, which is triggered when the alarm is fired. There's a lot into this, but you can learn how to schedule an alarm here : https://developer.android.com/training/scheduling/alarms.html

Community
  • 1
  • 1
ehanoc
  • 2,187
  • 18
  • 23
  • @Sophie, you can use it like that sure. But, i would advice you to avoid adding too much business logic to your activities/fragments life-cycles. This is because Android can destroy, re-create, pause, resume, etc.., at will on situations outside the expected behaviour of your application. In some situations this is hard to accomplish, but if that's not an issue for you right now, this is perfectly fine and you can always refactor later. – ehanoc Oct 16 '14 at 12:16