Saturday, October 27, 2012

Working with JSON and ListPreferences! Wooo Doggy, exciting!

So today, I made a preference screen, that dynamically pulled down JSON data.. and displayed it.

The issue with the Kiosks that it is resolving is pretty simple.  At read and respond, the person in charge wants to be able to see how long someone has been clocked in at their station.  Well, the current app didn't have any way really to give that information.  So, I added a web service method that would return that information for a given kiosk.  In .NET this was easy.  On the android side it took a little reading, and fiddling though.

This is how I do my HTTP requests.  I changed the URL to protect the innocent,
and it should allow me to use certificates in the headers eventually, so that only clients with
the right signature have access to the web service.

StringBuilder builder = new StringBuilder()
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://#####"+String.valueOf(arg0[0]));try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
    HttpEntity entity = response.getEntity();
    InputStream content = entity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
    String line;
    while ((line = reader.readLine()) != null) {
} else {
catch (ClientProtocolException e) {
catch (IOException e) {
return builder.toString();

This code, combined with this:

JSONArray jsonObject = new JSONArray(data);
ListPreference l = (ListPreference) findPreference("clocktimes");
CharSequence[] entries = new CharSequence[jsonObject.length()]
CharSequence[] entryValues = new CharSequence[jsonObject.length()];
for(int i = 0; i < jsonObject.length(); i++)
  JSONObject j = jsonObject.getJSONObject(i);
  entries[i] = (CharSequence) j.get("message");
  entryValues[i] = (CharSequence) String.valueOf(i);

Allowed me to customize a PreferenceScreen with a ListPreference inside to dynamically display data.

Keep in mind, there are going to be a lot of try / catches in there.. and you'll want to use that ASync task, that I mentioned in my post earlier.

Like so:

No comments:

Post a Comment