The requirement is : I have a background service and in that service I am doing a REST call to get a JSON data. I want to send the JSON data to UI and update contents.
One method I can use i.e. store the entire JSON string in SharedPreferences and retrieve in UI but I don't think that's efficient.
Any idea guys ? I have added a Handler in UI to update elements but I am not that familiar in using it.
Sample REST call code :
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(DATA_URL);
httpPost.setHeader("Content-Type", "application/json");
//passes the results to a string builder/entity
StringEntity se = null;
try {
se = new StringEntity(RequestJSON.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//sets the post request as the resulting string
httpPost.setEntity(se);
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
try {
HttpResponse response = (HttpResponse) httpClient.execute(httpPost, responseHandler);
// response will have JSON data that I need to update in UI
//Show notification
showNotification("Update Complete");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// httpClient = null;
}
On UI activity
pass the messanger to service and once result ready:
Something like that may be suitable for you. TL;DR: Create a listener in the service that updates the activity.
In the service, make a static function and a static field:
Populate the _instance field on the onCreate function:
Once a REST call is complete call:
Now in your activity, simply add the listener to the service once it starts:
Don't forget to dispose all the pointers when needed.
Hope this helps :)