I have the following type of application
Pull data prices down from feed
Process them and put them into my custom adapter
Display the prices in a ListView (so I call setAdapter).
Now the final stage is to repeat this infinitely perhaps at 5 second intervals.
So I have AsyncTask for handling the datadownload and on onPostExecute I update the adapter and it displays.
But how can I loop this whole activity with intervals of 5 seconds ?
Do I need to create a thread that calls this asynctask and in the thread use a loop with 5 second sleep ?
Thanks !!
You could use the TimerTask class and its scheduleAtFixedRate() method that download the data and after that update your interface using the post() method of a view so to avoid the AsyncTask at all. There are more way to do this, I should know because you want to download all every 5 seconds
The problem could be what to do when the datadownload fails or when it hangs for more than 5 seconds.
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 10000);
}
private void TimerMethod()
{
getActivity().runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
new AsyncTask().execute();
}
};
Related
Is there any function in Android that can use to make the activity wait for an interval and continue working?
I mean , for example, I use setContentView() to set a layout , and after 3 seconds it will load another layout, and continue to do another job, I don't need to repeat doing same thing after an interval, just continue do another thing.
Thanks in advanced.
You can Use Following Method to Set Interval
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Do your code here
}
}, 3000);
Here, 1000 = 1 Second
But Before running this code make sure that you are not in BACKGROUND PROCESS THREAD...otherwise this may cause an error..
Do it at Android Style:
Handler mHandler = new Handler();
mHandler.postDelayed(runnableHandler, 3000);
private Runnable runnableHandler = new Runnable() {
#Override
public void run() {
doSomething()
}
};
private void doSomething() {
// Before do something remove all callbacks from Handler
mHandler.removeCallbacks(runnableHandler);
andFinallyDoWhatYouNeed();
}
i tried both the links : Starting AsyncTask recursively after a gap of 5 minutes and Need advice new AsyncTask recursive calling
but they didnt solve my problem.
i want to use asynctask recursively after every 10sec of gap.
iam creating an app in which a dialog box shows with some content whenever some condition full fill and i need to change that content for that i am trying to call asynctask with a combination of thread and handler.
Thanks in advance!!!!
This repeats every 1000ms:
handler must be final as it is accessed within inner class
final Handler handler = new Handler();
Thread threadObj = new Thread() {
public void run() {
// Asynctask
// delay
handler.postDelayed(this, 1000);
}
};
//to start thread
threadObj.start();
//to stop thread
handler.removeCallbacks(threadObj);
Create a runnable where you start the asynctask again and again and the start the task for the first time by calling handler.postDelayed(repeatingTask , 1000);
private Runnable repeatingTask = new Runnable() {
public void run() {
new MyAsyncTask().execute("my String");
handler.postDelayed(this, 1000);
}
};
This way the runnable will be repeated again and again.Hope this helps you.
public void recur()
{
private Runnable repeat = new Runnable() {
public void run() {
new AsycnCaller().execute();
handler.postDelayed(this, 10000);
}
};
}
call this function where you want Start
and also call this in postexecution of asyntask
I am using the JSON parser to parse some pages but I would like to recall the parsing function every 30 seconds. How can i do that ?
One of the method to call a method every 30 seconds is by using postDelay of Handler see below code.
Handler handler;
handler=new Handler();
handler.removeCallbacks(run);
handler.post(run);
Runnable run=new Runnable()
{
public void run()
{
parsing();
handler.postDelayed(run,30000);
}
};
Another approach is by using "AlarmManager"
That is a weird need, only parsing when necessary would probably be a lot better.
Anyway, you should have a look at Timers and background services but be sure of what you are doing : if you create a background service that make a network call twice every minute, if that call is costly, you could cost a lot of data and/or battery to your users which is not a good idea.
You can do it using a timer.
Timer myTimer = new Timer();
After that you can call use the schedule method to call your json parser method.
myTimer.schedule(new TimerTask()
{
public void run() {
timerMethod();
}
}, 0, 1000);
private void timerMethod()
{
this.runOnUiThread(doSomething);
}
private Runnable doSomething = new Runnable() {
public void run() {
// Your code for doing something
}
I am getting data from a url for the monitoring window which show the list of visitors visiting the site,along with their ip,session id,time to live to site,no. of visit and their status from that url.i have to show data in a listview and after each 5 seconds getting new data.how can i make the listview that set data getting from url and after each 5 seconds update the data getting from server(means each after 5 seconds add new data to list).
can anyone help me?
I am using the update method like following.
Handler handler = new Handler();
Runnable updater = new Runnable() {
public void run() {
/*
* Update the list
*/
getVisitorDetailFromServer();
try {
Log.i("UPDATE", "Handler called");
// searchAdapter = getFeed(URL);
handler.postDelayed(this, 3000);
} catch(Exception e) {
Log.e("UPDATE ERROR", e.getMessage());
}
}
};
updater.run();
i am getting data correctly now using this method but problem is that after some time app is being crashed java.lang.indexoutofboundsexception occurs.
just try notifydatasetchange on list view. Run a thread and in that just do adater.notifydatasetchange.
To use scheduled timer , you can use this code:
private Timer myTimer;
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 10000);
}
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
}
};
try method below:
1 put your data in array or database or anyelse, which related to listview's adapter
2 create a Handler and use sendMessageDelaed(Message,5000) or postDelayed(Runnable,5000) to compose a loop.
3 call adapter.notifyDatasetChange(); in Runnable or handleMessage
in all, what you should do is update the dataset and call notifydatasetchange every 5 seconds.(Also can use TimerTask or other method)
See, if the datastructure (arraylist or other) containig your data is changing, ie. you are doing "Your_ARRAY_LIST" = new ArrayList();every time you get new data from the server, "notifyDataSetChanged()" wont work, as what it does is that it notifies the adapter that the arraylist containg data has been updated and the adapter then tries to refresh the data from the same address.But in your case the address of the data structure would have been changed.So if you are doing this, you need to set the adapter again in the "update()" method of your timertask.
Every 5 seconds, I want to call my webservice and get text (not images), then display it in my ImageAdapter. What would be the best way to accomplish this?
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
callWebservice();
}
};
handler.postDelayed(r, 5000);
It depends if you want to use a different thread or not. Do you want the user to be able to interact with the application on the UI Thread while the images are downloading? If so, then I would definitely use an AsyncTask with a small ProgressBar (style="#android:style/Widget.ProgressBar.Small")
If you don't care about threading then what #inazaruk said.
Edit: the truth is most modern apps that retrieve data from a web service will use an AsyncTask with a discreet little loader in the corner just to let the user know it's updating.
Edit 2: here's an example of using a TimerTask to run something every 5 seconds. The key is the runOnUiThread(). There may be better ways to tie all the elements together but this accurately portrays all the pieces.
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
CallWebService();
}
}, 0, 1000);
}
private void CallWebService()
{
this.runOnUiThread(fetchData);
}
private Runnable fetchData = new Runnable() {
public void run() {
asyncTask.execute();
}
};
You should call asynctask inside the application main thread. Asynctask can't be called in a background thread.