AsyncTask refreshing google map api v2 - android

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);

Related

AsyncTask or threads

In my app, activity A connects to server database retaining Latitude and Longitude from different cities and activity B connects to google maps directions calculating distances between cities. The results are shown via List adapter.
Because there are a couple of distances to be calculate every time (20 -30), which is the fastest way to achieve this; Using many times AsyncTask or using threads;
Should i merge these two activities to speed up work; ( But then, i am facing problems because FragmentActivity, the extending class of activity B doesn't support List adapter
Thanks
1) Multithreading
I personally like AsyncTasks because they are a clean way to handle multithreading. (Note that AsyncTasks are running on separate threads in the doInBackground() part)
However, if you think the workload is too intensive for the AsyncTask than the android developer guide recommends you use a background Service instead.
To me it seems like you might be able to a sequence of two asynctasks: the first grabs the lat/long values from the server in doInBackground(). In the first's onPostExecute() you can start the second, giving it the server values. The second can then calculate the distance in its doInBackground() method.
2) Activities and ListAdapter
Combine both activities into one for sure. Even though FragmentActivity obviously can't be a ListActivity, you can still pull out your ListView from xml with
ListView list = (ListView) findViewById(R.id.list);
Or programmatically create a list view with
ListView list = new ListView(this);
Then you can instantiate whatever type of adapter class you want and set it to the ListView. The following example show this using a CursorAdapter but this will work with any adapter, custom or built in.
CursorAdapter dataAdapter = new SimpleCursorAdapter(
getActivity(), R.layout.list_spot,
cursor,
columns,
to,
0);
list.setAdapter(dataAdapter);
Hope this helps!

Android - running background tasks that can fail

I need to be able to cancel tasks involving web requests.
but I got some issues of memory management and exception handling when something fail.
For example:
I want to create a text edit for searching apps in user device.
so whenever user end a key, I want to clear current search task, and restart search.
The problem I got is in android 4.4, when trying to load the label of the app (to get it's name) I get an exception.
Also of I try to search contacts I'm getting an invlalid uri, fo rcontact photo.
I don't want any help dealing with this errors, I want a solution that will help me ignore this erros (try catach dont work) currently the entire ui get's stuck and app crash.
I'm using the executors service and call cancel when user gives me an input. but it's not enough.
Any advice will be appreciated, thanks.
if you're using AsyncTask i would like to suggest you to make it like this
AsyncTask<Void, Void, Void> a = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
return null;
}
};
a.execute();
// at some point you want to cancel just use
a.cancel(true);
You can even put tasks together in List or array and loop to cancel it whenever you want.
You can try like this: what you want is getting result in background by network and show result in view ,you can Register a Listener to one task,. you can callback method of listener to use show result in view if it get the results in background ,if you do not need the result of current task and want satrt the next task ,you can only remove listener of current task,so the view will not reload
This is my idea ,I am so sorry for my bad english , if you do not see ,you can send message to me, and my email is bjltxsp#gmail.com

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

Android pausing with thread but adding stuff to a text view

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!

complex listeviewitem image load hang application problem

I am suing Listview and customize listview to display image inside a list item.
I want display image with every search result.
to display complext listeim i am following the following example
http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List4.html
inside wrapper class i am initiating new thread for every new list item's image so that i won't dealy the displaying image.
my code is below
new Handler().post(new Runnable(){
#Override
public void run() {
Drawable dImage = Util.getImageFromURL(imageURL);
getImageIcon().setImageDrawable(dImage);
}
});
mean 10 images initiates 10 different image loading threads other static data is not inside thread.
problem arises when during image loading page application getting hang it should not hang.... any idea what to do ?
alt text http://img509.imageshack.us/img509/7519/thumbnailx.jpg
Use a background operation to retrieve your images, such as an AsyncTask. All your new Handler().post() stuff does is delay the work by a nanosecond, not have it be performed in the background.
Also, if you are going to use Handlers, just create one.

Categories

Resources