-1

I'm executing AsyncTask that fetch data from my web host. In order for me to retrieve data, I need to re-open my app. How can I fetch data every second? I know that AsyncTask could only be executed once, but I needed it not only for my app but also to learn about this problem. Hope to learn from you guys.

By the way this is my code:

class AsyncDataClass2 extends AsyncTask<String, Void, String>
{

    @Override
    protected String doInBackground(String... params) {
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);

        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost(params[0]);

        String jsonResult = "";
        try
        {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", params[1]));
            nameValuePairs.add(new BasicNameValuePair("password", params[2]));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpClient.execute(httpPost);
            jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

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

        catch (IOException e)
        {
            e.printStackTrace();
        }
        return jsonResult;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String result) {

        if (result.equals("") || result == null)
        {
            Toast msg = Toast.makeText(MapsActivity.this, "connection failed", Toast.LENGTH_LONG);
            msg.setGravity(Gravity.CENTER, 0, 0);
            msg.show();
        }

        else
        {
            Toast msg = Toast.makeText(MapsActivity.this, "connected", Toast.LENGTH_LONG);
            msg.setGravity(Gravity.CENTER,0,0);
            msg.show();
        }

        try {
            JSONArray json = new JSONArray(result);

            for (int i = 0; i < json.length(); i++) {
                JSONObject e = json.getJSONObject(i);
                String point = e.getString("Point");

                String[] point2 = point.split(",");

                String devStatus = e.getString("Status");   //now, let's process the Status...
                String strOwner = e.getString("Owner");     //now, let's process the owner...

                //==============================================================================


                if (devStatus.equals("fire")) {
                    IsThereFire=true;
                }

            } //---End of FOR LOOP---//


        }//---end of TRY---//

        catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    private StringBuilder inputStreamToString(InputStream is)
    {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        try
        {
            while ((rLine = br.readLine()) != null)
            {
                answer.append(rLine);
            }
        }

        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return answer;
    }
}

EDIT:

Sir, this is the timer I used..

///---CODE for the TIMER that ticks every second and synch to database to update status---///
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // HERE IS THE ACTUAL CODE WHERE I CALL THE ASYNCDATACLASS2
                            AsyncDataClass2 performBackgroundTask = new AsyncDataClass2();
                            // PerformBackgroundTask this class is the class that extends AsynchTask
                            performBackgroundTask.execute();
                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    t.start();
    //---------------------------------------------------------------//
Christina
  • 555
  • 1
  • 6
  • 15
  • *How can I fetch data every second?* that seems way too fast for asynctasks to follow up on eachother. What are you trying to achieve by doing this? – Tim Oct 02 '15 at 09:24
  • I'm trying to retrieve STATUS on my database, and that status is changing every X second. Now I want to know that changes without closing-reopening my app, how can I do that? – Christina Oct 02 '15 at 09:26
  • @Christina Have a look here http://stackoverflow.com/questions/6207362/how-to-run-an-async-task-for-every-x-mins-in-android – IntelliJ Amiya Oct 02 '15 at 09:32
  • What happens if you take out `runOnUiThread()` and the whole `Runnable` inside of it, leaving only the `AsyncTask` lines after `Thread.sleep()`? – Klotor Oct 02 '15 at 10:00

4 Answers4

1

if you need to execute a task at fixed interval of time you can use a Timer with a TimerTask. It runs on different thread than the UI thread, meaning that you can run your http call directly in it. You can find the documentation here

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
0

I do not think that's a really good idea to proceed like this but you can do it, of course with an simple TimerTask (tutorial there)

Basically, it would look like this:

public class MyTimerTask extends TimerTask {
    @Override
    public void run() {
        // Just start your AsyncTask and proceed, I didn't adapt the code to your task
        new AsyncDataClass2().execute()
    }
}

Your Logic calls it:

TimerTask timerTask = new MyTimerTask();
 // They're ms: 1000ms = 1s
 timer.scheduleAtFixedRate(timerTask, 0, 1000);
 timer.start();

You cancel it when you destroy your Fragment/Activity

timer.cancel();
Laurent Meyer
  • 2,766
  • 3
  • 33
  • 57
  • Sir, sorry to annoy you by this, but I have tried TimerTask and it says Fatal error, maybe I misplaced it or what.. – Christina Oct 02 '15 at 09:28
  • 1
    NEVER RUN NETWORK CALL ON UI THREAD! – Laurent Meyer Oct 02 '15 at 09:36
  • 1
    Sir, that sounds informative. (Just curious) What is the reason why I should never run network call on UI thread? Please don't get mad at me sir.. – Christina Oct 02 '15 at 09:40
  • 1
    @Christina, your app will stuck while and users wouldn't know what is going on, or press the button or ... – Movsar Bekaev Oct 02 '15 at 09:47
  • 1
    @Christina have a look at https://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask Newer Android versions crash your app and throw an error at you for networking on main thread – Klotor Oct 02 '15 at 09:53
  • 1
    @Klotor Exactly. I wrote it in BIG in order you remember it! – Laurent Meyer Oct 02 '15 at 10:03
0

I think you should try to use TimerTask or a job scheduler.

Lots of information about job schedulers can be found here and here.

Ivan V
  • 3,024
  • 4
  • 26
  • 36
0

Check this:

Timer timer;

private void startTimer() {
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
           new AsyncDataClass2  adc = new AsyncDataClass2("u","p");
           adc.execute();
        }
    }, 0, 1000);
}

Then in onCreate() you write:

startTimer();

Although, you should consider others comments, they're meaningful, requesting updates from web server every second in AsyncTask, it's not so good thing to do.

Movsar Bekaev
  • 888
  • 1
  • 12
  • 30
  • Yes, sir, I will try it. But what is the best time to refresh data? every what second or minute? – Christina Oct 02 '15 at 09:36
  • @Christina, you should determine what you want, what frequency you really need, the more intervals you have - then better for system/app/server, if you need continuous refreshes from server then you should establish some connection and keep it alive, but if you can have info once in a five or so, minutes, than you can do it with AsyncTask, in programming you always should think about not doing more than that you need, from this depends the app speed, stability, time to develop and cost of hosting, use KISS model, keep it simple)) – Movsar Bekaev Oct 02 '15 at 09:52