Monday, July 6, 2009

POST JSON from Android using HttpClient

I'm using Ruby on Rails on the server and needed to post JSON to it from Android. Here's some quick code that I wrote to do this. Hopefully it helps someone else. All of the tutorials that I found didn't work. You basically need to make sure you post data in JSON format. Just seetting parameters won't do the trick.

In my case I had to create JSON something like:
{ fan: { email : 'foo@bar.com' } }

which equates to the HTML form input:
<input name="fan[email]" type="text"/>

To POST in Android. You can use something like this code.

public static String makeRequest(String path, Map params)
throws Exception {

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(path);
Iterator iter = params.entrySet().iterator();

JSONObject holder = new JSONObject();

while(iter.hasNext()) {
Map.Entry pairs = (Map.Entry)iter.next();
String key = (String)pairs.getKey();
Map m = (Map)pairs.getValue();

JSONObject data = new JSONObject();
Iterator iter2 = m.entrySet().iterator();
while(iter2.hasNext()) {
Map.Entry pairs2 = (Map.Entry)iter2.next();
data.put((String)pairs2.getKey(), (String)pairs2.getValue());
}
holder.put(key, data);
}

StringEntity se = new StringEntity(holder.toString());
httpost.setEntity(se);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");

ResponseHandler responseHandler = new BasicResponseHandler();
response = httpclient.execute(httpost, responseHandler);
}

Sunday, July 5, 2009

Finding Skins Under Android 1.5

I was testing using some custom skins under the Android SDK 1.5 and was a little perplexed that all of the documentation I read told me to put the skins in the directory

$SDK_ROOT/tools/lib/images/skins

This is not correct under Android 1.5 SDK! Instead you want to put them into the directory

$SDK_ROOT/platforms/android-1.5/skins

This discussion on the Android Google Group helped me.
http://is.gd/1ouFs

Also, you can find many cool skins here:
http://teavuihuang.com/android/

Hoping this will save others wasted time.