I want to update the icon status from red to green after successfull upload of the image in background service. I am using Otto event bus to transfer data between Service to Activity, I can able to subscribe and get the data from Service to Activity after successful uploading of image. Then I am trying to update the Grid view of my custom adapter from activity, it's working fine in debug mode but not at run time. No clue why it happening like so..
What I am doing wrong? Any suggestion/clue will be appreciated.
Here is my event publishing code in Service:
The TaskBus.java:
public class TaskBus {
public static Bus bus = new Bus();
}
In onStartCommand called thread to upload image:
// start thread to upload image
new Thread(ImageUpload).start();
Here is the thread to upload image in background:
public Runnable ImageUpload = new Runnable() {
public void run() {
try {
response = uploadImageToServer(server, imageData);
if (!TextUtils.isEmpty(response)) {
showToastMessage("Image uploaded successfully.");
// update status icon in UI
updateStatus(imageData);
// save/update in local DB
// save/Update code goes here to save status in local DB
} catch (Exception ex) {
ex.printStackTrace();
showToastMessage("Problem occurred while uploading image.");
}
}
};
private void showToastMessage(final String message) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
});
}
Here is the code to send data to activity from Service after successful upload of image:
private void updateStatus(ImageData data) {
final UploadStatusEvent uploadStatusEvent = new UploadStatusEvent();
uploadStatusEvent.data = data;
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
bus.post(uploadStatusEvent);
}
});
}
public class UploadStatusEvent {
public ImageData data;
}
Here is the subscribe code to get data from Service in Activity:
// update status icons , it called when image uploaded successfully in Service in background
@Subscribe
public void receiveTakingPhotoServiceUploadImageStatus(TakingPhotoService.UploadStatusEvent uploadStatusEvent) {
ImageData data = uploadStatusEvent.data;
if (data != null) {
imageAdapter.setImageInGridItem(data);
gridView.invalidateViews();
gridView.setAdapter(imageAdapter);
}
}
Here is my Adapter code to update grid view:
public void setImageInGridItem(ImageData data) {
try {
GridItem gridItem = getItem(data.position);
gridItem.setStatus(data.status);
gridItems.remove(vehicleImage.position);
gridItems.add(ImageData.position, gridItem);
setNotifyOnChange(true);
this.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}