Android pausing with thread but adding stuff to a text view - android

I have a linear layout in which I am placing a textview with the id "out". In my code i am getting this textview and calling out.append("Some string here");. What i want to do is have it use a thread.sleep(1000); to wait one second and then do another append. When i just use a for loop and iterate through it ten times it waits ten seconds and then updates the view at the end. How can i make this update the view in between the sleeps?
ps. The main reason for this is because i have another thread running with a bluetooth output stream and i want it to update the textview every time i send a byte to an arduino connected through a bluesmirf module. I can get it to send data but the updating of the screen happens at the end of the for loop. If i put a sleep in this loop it will wait the one second and then output to the arduino no problem. I just want to update it so i can see where things fail as they fail without using the logs.

Maybe you can use a postdelay handler
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//Here is the code you want to run after 1 second
}
}, 1000);
The handler is not blocking, but maybe it can help
Excuse me for my bad english, good luck!

Related

Why setText() after sleep doesn't work? Inside android how message queue works?

I know the 2 rules that UI thread shouldn't blocked and udating ui in only UI thread.
So I know roughly why using Thread.sleep() with setText() doesn't work. (Because call Thread.sleep() blocks the UI thread !!)
But...why??
Imagine below code, I clicked a button to start timer to represent number every 50 milli seconds.
public void onTimerClicked(View v){
TextView tv = (TextView) findViewById( .. )
for( int i = 1; i <= 10; i++ ){
Thread.sleep(50) // in milil seconds
tv.setText(String.valueOf(i));
}
}
I already know when I click a button, after I get some freezing time only displays '10' on a text view. But why?? If UI thread encounter tv.setText(..) , it doesn't work for updating UI immediately?? or queueing the task( updating text view UI ) to message queue on main thread?? Then what is the criteria for queueing to message queue instead running the code immediately when it faces.
also, if setting text view with numbers are all queued, then after all sleeping is end. Does UI update all the task very fast?? is it reason that I can only last update ??
I am really curious about how UI thread works for dealing with UI datating internally.. but there are rarely information or explanation about this.
please let me understand !!
Thanks for reading

Android GridView and threading wait

I have a method playSoE() that performs an operation on each view and updates the ArrayAdapter and thus GridView after each operation. I want to do is have the code wait for 1 second after the update is done, and then perform the operation on the next view. For example:
public class MainActivity extends Activity{
public void playSoE(){
for(int i = 0; i < primesLE; i++) //iterates to each view
mAdapter.setPositionColor(index, 0xffff0000 + 0x100 * index); //operation performed on view
mAdapter.notifyDataSetChanged(); //updates adapter/GridView
//Code that waits for one second here
}
}
I have tried many threading APIs but none of them seem to work, they've either froze up the application for primesLE seconds and shown all the operations at the end, skip the second wait and just performed all the operations at once, or gotten an Exception related to concurrency.
Assuming the update itself is quick, you should not be creating additional threads at all. Create a Handler and use postDelayed(...) to time your updates in the UI thread.
You may have to take a look at AsyncTask.
Put the wait code at the doInBackground() and then the following that affects the visual on the onPostExecute()
All you do on doInBackground() will not freeze your application.

AsyncTask refreshing google map api v2

My android application retrieves some json data from remote API for each Marker (a Marker shows the position of a real device, there are less than 10 devices to watch) present on the map, and sets status of a device by changing a color of the marker according to some rule working on a given json data. I use AsyncTask to fetch json data and change a status of a device. I keep fetched data in ConcurrentHashMap<Device, Data>. So, I run a number of asynctasks, one for each device. I also use a custom info window (in fact custom InfoWindowAdapter) to show some more data about device. First I draw a markers and keep them in a map HashMap<Device, Marker>. I execute asynctasks one by one using:
new MyAsyncTask(markerMap).execute(device)
My custom InfoWindowAdapter overrides getInfoContents method, where some collected by asynctasks data are used to be shown in InfoWindow, when clicked.
Everything works fine. But now I want to refresh my markers every 10 sec. I have tried to do it using the following approach:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run() {
new MyAsyncTask(markerMap).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, device1);
new MyAsyncTask(markerMap).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, device2);
}}, 0, 10000);
My question is if it is the right/ best way to refresh my map? Or should I use Runnable instead of AsyncTask, and within a Runnable send a message to Handler when fetching json data to update Marker? One more question: should I use Timer or ScheduledExecutorService? I have read some StackOverflow discussions but I dont know the final recommendation. Thanks.
Finally I have solved my problem. In mean time I have rewritten part of my program in order to use ScheduledThreadPoolExecutor with subclassed Runnable (instead of Asynctask). In addition I have added onResume() method where I restart ScheduledThreadPoolExecutor using: mScheduledThreadPoolExecutor.scheduleAtFixedRate(runnable, 0, interval, TimeUnit.MILLISECONDS);

How to show an image for a specific time period?

In my application i need to decrypt the certain message format, to extract information like message id, timeout and so on.i need to show an corresponding image for the given id as well as to show it for the mentioned time period.
For that i have created one custom layout to show the image and other details. i'm using imageview for displaying the image. but dont know how to set timeiut for that?
Do anyone have idea on that?
You can easily use Handler to do that, like this
imageuser.setImageBitmap(bitmapObject);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
imageuser.setImageBitmap(null);
}
}, 5000);
here, imageuser is your ImageView and replace 5000 with your specific time in miliseconds.
Just use it like whenever you want to show image just call your UI and start a thread for the given time you want to show the image and when the time complete just make that ui visibility gone,this is the logic try it in your own way.
thanks

wait t time before launch an action?

I actually had a multiautocompletetextview, where i call host after 3 characters to have a dynamic search list.
But if the user put others characters, my code call host for each of them. So it must be very long.
Could I wait a moment (about 500 ms) before launching the action , in order to look if user do an action or not ? that's possible ?
You could use a separeted thread. When the user entered the text you could create a thread, make it sleep for 500ms and when it will wake up check if the text typed is changed.
EDIT
Create a Handler
private Handler h = new Handler();
Create a runnable that makes your dynamic search
private Runnable myrunnable = new Runnable() {
public void run() {
....
};
Then call your runnable in onTextChanged like
h.postDelayed(myrunnable, 500);
see Handler for more options/informations
Make sure that your threads will access the memory in a consistent way!

Categories

Resources