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.
Related
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 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();
}
};
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
}
On button click I want to begin a timer of 5 minutes and then execute a method that will check for certain conditions and set off alerts if conditions are right. I've seen examples with timers and postDelay, but don't really understand why one would use one vs another. What is the best way to accomplish what I am trying to do? I don't want to lock up the UI during the 5 minutes. The user should be free to use the app as normal during the countdown.
EDIT: I am trying the postDelayed suggestion but visual studio is not liking something about my code. It looks exactly like examples I've found. My be a mono for android thing.
Handler h = new Handler();
Runnable r = new Runnable(){
public void run()
{
Dialog d = inst2.showBuilder(this, "test", "test");
d.Show();
}
};
h.postDelayed(r, 5000);
Specifically the code block inside of run throws all kinds of "} expected" and "a namespace cannot directly contain members such as fields or methods" exceptions.
Try using Timer Object :
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask()
{
#Override
public void run()
{
// Your code goes here
}
}, 1000); // 1sec
final Handler handler = new Handler();
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
handler.post(new Runnable()
{
public void run()
{
// YOUR Code
}
});
}
}, 1000); // 1sec
You can start a simple Thread that will sleep in background for 5 minutes and then call a function. While the thread sleeps in background the UI will not freeze. When the thread finish executing what you want you can set off alerts by sending some intents as notifications and receive them in some Broadcast Receivers.
Hope this helps
Use Handler.postDelayed(Runnable block); method to execute delay, as android also not recommend to use timer.
Handler h = new Handler();
Action myAction = () =>
{
// your code that you want to delay here
};
h.PostDelayed(myAction, 1000);
I am new to Android and I am having trouble understanding the concept so basically this is what i want to do to understand it better..
I created a DrawShape class that extends view. In this class in the OnDraw() I am creating a circle and filling it with a color.
From the Activity I am calling the application. //Until this point I am doing fine.
Now, I need to re-paint the Circle multiple times (Blue, Red, Yellow etc..)
So I was reading and the best way is to use Threads.. I also read you need to use postInvalidate() to redraw (I still dont understand from where I should be calling this) is this called from the Activity?, or within the OnDraw()?.
Hopefully you understand what i want to accomplish, is just that i havent found a good tutorial that shows this, how to repaint something x amount of times .. when I do Thread.sleep() it all stops then it shows my app.. but now i understand why, because i am playing with the main Thread.
Please help me understand this..
Thank you
i did something like this
animcolor()
{
Timer timer = new Timer();
int delay = ...;
int period = ...;
timer.schedule(new TimerTask(){
run() {
setColor( randomint() ); )
customview.postInvalidate();
}
}, delay, period);
threads? not necessary to create them; Timers make a good job on concurrency.
... and the code would somewhat look like....
res/layout/file.xml
<org.customviewlayout a:id="#+id/customlayout"/>
src/org.MyActivity.java
class MyActivity
{
onCreate()
{
customlayout = findViewById(R.id.customlayout);
customlayout.animcolor();
}
}
src/org.customlayout.java
import org.customview;
class customlayout
{
customview;
customlayout(context, attrs)
{
customview = new customview();
addview(customview); // so it's onDraw() method will be called
}
onlayout(...)
{
customview.layout(...);
}
animcolor()
{
Timer timer = new Timer();
int delay = ...;
int period = ...;
timer.schedule(new TimerTask(){
run() {
setColor( randomint() ); )
customview.postInvalidate();
}
}, delay, period);
}
setcolor(int)
{
....
}
}
i think, you can do this using a Timer and a TimerTask inside your activity. The TimerTask runs with the delay you specify and when run all you what to do is yourDrawShapeInstance.postInvalidate();
the mechanism is this, because you arent on the ui thread you call postInvalidate() to add an invalidate on the ui queue, when the ui engine pick the delayed invalidate that you invoke before, then calls automatically the onDraw method of your DrawShape view and the view will be redrawed.
(i donĀ“t test this, i write here)
TimerTask task = new TimerTask(){
public void run(){
myDrawShapeInstance.postInvalidate();
}
}
When drawing, always use a thread away from the main thread and always invalidate after thread has finished (for the most part -- to display current results from drawing). You will probably call your drawing functions from some user-related event, so make sure you're making another thread for that drawing process. Follow those rules and you will be fine.
void drawCircleToCanvas(int color)
{
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
myDrawShapeInstance.postInvalidate();
}
};
Thread updateUI = new Thread() {
public void run() {
//************draw something here***************
handler.sendEmptyMessage(0);
}
};
updateUI.start();
}