Wednesday, September 21, 2011

Query and parse Google+ JSON using Google+ API.

There is a post in The official Google Code blog, discuss about Getting started on the Google+ API. It's a exercise to query and parse Google+ JSON using Google+ API.



Query and Parse Google+ JSON


To use Google+ API, you have to


package com.exercise.AndroidGooglePlus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidGooglePlusActivity extends Activity {
 
   TextView item_kind;
   TextView item_id;
   TextView item_displayName;
   TextView item_tagline;
   TextView item_gender;
   TextView item_aboutMe;
   TextView item_url;
  
   final static String GooglePlus_url
   = "https://www.googleapis.com/plus/v1/people/108189587050871927619?key=<your own Google+ API key>";
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       item_kind = (TextView)findViewById(R.id.item_kind);
       item_id = (TextView)findViewById(R.id.item_id);
       item_displayName = (TextView)findViewById(R.id.item_displayName);
       item_tagline = (TextView)findViewById(R.id.item_tagline);
       item_gender = (TextView)findViewById(R.id.item_gender);
       item_aboutMe = (TextView)findViewById(R.id.item_aboutMe);
       item_url = (TextView)findViewById(R.id.item_url);
      
       String googlePlusResult = QueryGooglePlus();
       ParseGooglePlusJSON(googlePlusResult);
      
   }
  
   String QueryGooglePlus(){
    String qResult = null;
    
    HttpClient httpClient = new DefaultHttpClient();
       HttpGet httpGet = new HttpGet(GooglePlus_url);
      
       try {
        HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
        
        if (httpEntity != null){
         InputStream inputStream = httpEntity.getContent();
         Reader in = new InputStreamReader(inputStream);
         BufferedReader bufferedreader = new BufferedReader(in);
         StringBuilder stringBuilder = new StringBuilder();
         
         String stringReadLine = null;
 
         while ((stringReadLine = bufferedreader.readLine()) != null) {
          stringBuilder.append(stringReadLine + "\n"); 
         }
         
         qResult = stringBuilder.toString(); 
        } 
       } catch (ClientProtocolException e) {
        e.printStackTrace(); 
        Toast.makeText(AndroidGooglePlusActivity.this,
          e.toString(),
          Toast.LENGTH_LONG).show();
       } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(AndroidGooglePlusActivity.this,
          e.toString(),
          Toast.LENGTH_LONG).show();
       }
    
    return qResult;
   }
  
   void ParseGooglePlusJSON(String json){
    if(json != null){
     try {
      JSONObject JsonObject = new JSONObject(json);
      item_kind.setText("kind: " + JsonObject.getString("kind"));
      item_id.setText("id: " + JsonObject.getString("id"));
            item_displayName.setText("displayName: " + JsonObject.getString("displayName"));
            item_tagline.setText("tagline: " + JsonObject.getString("tagline"));
            item_gender.setText("gender: " + JsonObject.getString("gender"));
            item_aboutMe.setText("aboutMe: " + Html.fromHtml(JsonObject.getString("aboutMe")));
            item_url.setText("url: " + JsonObject.getString("url"));
      
      Toast.makeText(AndroidGooglePlusActivity.this,
              "finished",
              Toast.LENGTH_LONG).show();
      
     } catch (JSONException e) {
      e.printStackTrace();
      Toast.makeText(AndroidGooglePlusActivity.this,
              e.toString(),
              Toast.LENGTH_LONG).show();
     }
    }
    
   }
}




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
<TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   />
<TextView 
   android:id="@+id/item_kind"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView 
   android:id="@+id/item_id"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView 
   android:id="@+id/item_displayName"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView 
   android:id="@+id/item_tagline"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView 
   android:id="@+id/item_gender"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView 
   android:id="@+id/item_aboutMe"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView 
   android:id="@+id/item_url"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
</LinearLayout>




note: have to modify AndroidManifest.xml to grant permission of "android.permission.INTERNET".

Apply your own Google+ API key

Apply your own Google+ API key  

The official Google Code blog have a new post about Getting started on the Google+ API. Google+ gives users full control over their information, supporting everything from intimate conversations with family to public showcases and debates. This initial API release is focused on public data only — it lets you read information that people have shared publicly on Google+.



In order to read information from Google+, you have to apply your API Key. Visit APIs Console, you have to login your Google account to create your API key.




  • Click on the API project on the left and select Create...
    Apply your own Google+ API key
  • Enter the name of your project and click Create project.
    Apply your own Google+ API key
  • Click to enable Google+ API, you will be asked to review and accept the terms of service.
    Apply your own Google+ API key
  • Click API Access, your API Key will be found.
    Apply your own Google+ API key



Now you can copy the link with your own API key at browser to read the JSON returned from Google+.

https://www.googleapis.com/plus/v1/people/108189587050871927619?key=<your API key>
Google+ API key

XML PARSING SAMPLE IN ANDROID

XML PARSING SAMPLE IN ANDROID 

In this exercise, we read our own XML Resource (in /res/xml folder) using XmlResourceParser, and display the contents on screen.



First of all, create a folder /res/xml, and our own XML file myxml.xml
<?xml version="1.0" encoding="utf-8"?>
<rootelement1>
<subelement>
 Hello XML Sub-Element 1
</subelement>
<subelement>
 Hello XML Sub-Element 2
 <subsubelement>Sub Sub Element</subsubelement>
</subelement>
</rootelement1>


Modify main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/my_xml"
  />
</LinearLayout>


Finally, modify java code
package com.exercise.AndroidXmlResource;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidXmlResource extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
    
      TextView myXmlContent = (TextView)findViewById(R.id.my_xml);
      String stringXmlContent;
 try {
  stringXmlContent = getEventsFromAnXML(this);
  myXmlContent.setText(stringXmlContent);
 } catch (XmlPullParserException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
  }

  private String getEventsFromAnXML(Activity activity)
  throws XmlPullParserException, IOException
  {
   StringBuffer stringBuffer = new StringBuffer();
   Resources res = activity.getResources();
   XmlResourceParser xpp = res.getXml(R.xml.myxml);
   xpp.next();
   int eventType = xpp.getEventType();
   while (eventType != XmlPullParser.END_DOCUMENT)
   {
    if(eventType == XmlPullParser.START_DOCUMENT)
    {
     stringBuffer.append("--- Start XML ---");
    }
    else if(eventType == XmlPullParser.START_TAG)
    {
     stringBuffer.append("\nSTART_TAG: "+xpp.getName());
    }
    else if(eventType == XmlPullParser.END_TAG)
    {
     stringBuffer.append("\nEND_TAG: "+xpp.getName());
    }
    else if(eventType == XmlPullParser.TEXT)
    {
     stringBuffer.append("\nTEXT: "+xpp.getText());
    }
    eventType = xpp.next();
   }
   stringBuffer.append("\n--- End XML ---");
   return stringBuffer.toString();
  }
}

A simple RSS reader, using Android's org.xml.sax package.

A simple RSS reader, using Android's org.xml.sax package.



In order to make it simple, only the contents under "title" tag will be retrieved and appended as a string.



To allow the Android application, "android.permission.INTERNET" have to be granted to the application. Modify AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.exercise.AndroidRssReader"
    android:versionCode="1"
    android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name">
      <activity android:name=".AndroidRssReader"
                android:label="@string/app_name">
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
      </activity>

  </application>
  <uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>


Modify main.xml to add a TextView to display the result.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/result" />
</ScrollView>
</LinearLayout>


Java source code.
package com.exercise.AndroidRssReader;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidRssReader extends Activity {

String streamTitle = "";

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
    
      TextView result = (TextView)findViewById(R.id.result);
    
      try {
  URL rssUrl = new URL("http://example.com/example.xml.........");
  SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
  SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
  XMLReader myXMLReader = mySAXParser.getXMLReader();
  RSSHandler myRSSHandler = new RSSHandler();
  myXMLReader.setContentHandler(myRSSHandler);
  InputSource myInputSource = new InputSource(rssUrl.openStream());
  myXMLReader.parse(myInputSource);
 
  result.setText(streamTitle);
 
 } catch (MalformedURLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  result.setText("Cannot connect RSS!");
 } catch (ParserConfigurationException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  result.setText("Cannot connect RSS!");
 } catch (SAXException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  result.setText("Cannot connect RSS!");
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  result.setText("Cannot connect RSS!");
 }
    
    
  }

  private class RSSHandler extends DefaultHandler
  {
   final int stateUnknown = 0;
   final int stateTitle = 1;
   int state = stateUnknown;
  
   int numberOfTitle = 0;
   String strTitle = "";
   String strElement = "";
  
 @Override
 public void startDocument() throws SAXException {
  // TODO Auto-generated method stub
  strTitle = "--- Start Document ---\n";
 }

 @Override
 public void endDocument() throws SAXException {
  // TODO Auto-generated method stub
  strTitle += "--- End Document ---";
  streamTitle = "Number Of Title: " + String.valueOf(numberOfTitle) + "\n"
     + strTitle;
 }

 @Override
 public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {
  // TODO Auto-generated method stub
  if (localName.equalsIgnoreCase("title"))
  {
   state = stateTitle;
   strElement = "Title: ";
   numberOfTitle++;
  }
  else
  {
   state = stateUnknown;
  }
 }

 @Override
 public void endElement(String uri, String localName, String qName)
   throws SAXException {
  // TODO Auto-generated method stub
  if (localName.equalsIgnoreCase("title"))
  {
   strTitle += strElement + "\n";
  }
  state = stateUnknown;
 }

 @Override
 public void characters(char[] ch, int start, int length)
   throws SAXException {
  // TODO Auto-generated method stub
  String strCharacters = new String(ch, start, length);
  if (state == stateTitle)
  {
   strElement += strCharacters;
  }
 }
  
  }
}