Thursday, September 13, 2012

Andriod App that uses Google App Engine as Backend

Now that was 4 days of tiresome job. But now that its finally done, I would like to post it to my blog. I would be happy if I can rescue anyone else who has been slogging like me.

So, I want to create an Android app that consumes data from an application hosted on the Google app Engine.
The first rule is to get the steps right. That was the basic mistake I did, by trying n no. of solutions without making a clear picture in my mind how to achieve it. Here are the basic steps to be taken in the same order they have been jotted down:

1. Create a GAE application that exposes your data in JSON or XML format. The example I would be mentioning below uses JSON. Publish it to GAE.

2. Create an Android Application. Preferably make an Hello Wold application first, so that you get a hang of things.

3. Now, change your Android app to access any public URL to see if you can read from it.

4. Finally, pass the URL of your GAE application.

Step 1:

public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, ServletException {

        
resp.setContentType("text/plain");

        List list = new ArrayList();
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

        Query fetchQuery = new Query("Offers");

        List pages = new ArrayList();

        pages =  datastore.prepare(fetchQuery).asList(FetchOptions.Builder.withDefaults()); 

............................

I assume, we are familiar with the above code snippet. This is going to fetch from your table on GAE.

for (Entity page: pages) {
            // Add the pojo as a JSONObject
            list.add(new JSONObject(page));
        }
        // Create a JSONArray based from the list of JSON Obejcts
        JSONArray jsonArray = new JSONArray(list);

        // Then output the JSON string to the servlet response
         resp.getWriter().println(jsonArray.toString());

The above code converts your list data into JSONObject and attaches it to the response object. And with this we complete the first step.


Step 4 : 

Now, in your android onCreate method, add the following code to access the JSON Object sent as a response from the GAE Application.

ArrayList listItems = new ArrayList();
            
            try {
                URL url= new URL(
                        "the GAE app URL here");
                URLConnection tc = url.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        tc.getInputStream()));
   
                String line;
                while ((line = in.readLine()) != null) {
                    JSONArray ja = new JSONArray(line);
   
                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject jo = (JSONObject) ja.get(i);
                       
                        String obj=jo.getString("properties");
                        listItems.add(
obj);
                    }
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return listItems;
        }

Assign the list to the TextView in your main.xml

TextView text = (TextView) findViewById(R.id.textviewId);
              for(String s: listItems){
                  sb.append(s+"\n");
              }
              text.setText(sb.toString());

And now you have a GAE application that posts data into a store and an Android Application that's listening.



No comments:

REFACTORING

 What is Refactoring? A software is built initially to serve a purpose, or address a need. But there is always a need for enhancement, fixin...