Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Android - Twitter Timeline Feeds Example


Today we will see how to display Twitter Timeline feeds in an android application through API calls. In this example we will fetch the recent 10 tweets posted from BBCNews Twitter account.

So let us start:

1.Create a new project File ->New -> Project ->Android ->Android Application Project. While creating the new project, name the activity as TwitterTimelineActivity(TwitterTimelineActivity .java) and layout as main.xml.

2.Now let us design the UI for the TwitterTimelineActivity i.e main.xml with a TextView within a ScrollView. Note the attribute autoLink of the TextView is set to web to display Url links.

main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >


        <TextView
            android:id="@+id/tweetTextView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:autoLink="web"
            android:background="#FFFFFF"
            android:textColor="@android:color/black" />
    </ScrollView>

</LinearLayout>
3.Now in the TwitterTimelineActivity we will call http://api.twitter.com/1/statuses/user_timeline/BBCNews.json?count=10&include_rts=1&callback=? To get the json response which will contain data like users name,id,date created text etc.. we will parse the response and fetch the date created and tweet posted and display it in the textview.To call another twitter account replace ”BBCNews” in the url with the desired account .

TwitterTimelineActivity.java
package com.twitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class TwitterTimelineActivity extends Activity {
 TextView tweetTextView;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  String twitterTimeline = getTwitterTimeline();
  try {
   String tweets = "";
   JSONArray jsonArray = new JSONArray(twitterTimeline);
   for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    int j = i + 1;
    tweets += "Tweet #" + j + " \n";
    tweets += "Date:" + jsonObject.getString("created_at") + "\n";
    tweets += "Post:" + jsonObject.getString("text") + "\n\n";
   }
   tweetTextView = (TextView) findViewById(R.id.tweetTextView);
   tweetTextView.setText(tweets);
  } catch (JSONException e) {
   e.printStackTrace();
  }
 }

 public String getTwitterTimeline() {
  StringBuilder builder = new StringBuilder();
  HttpClient client = new DefaultHttpClient();
  HttpGet httpGet = new HttpGet(
    "http://api.twitter.com/1/statuses/user_timeline/BBCNews.json?count=10&include_rts=1&callback=?");
  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) {
     builder.append(line);
    }
   } else {
    // Display couldn't obtain the data from twitter
   }
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return builder.toString();
 }
}
4.Make the changes in AndroidManifest.xml file by including internet permission <uses-permission android:name="android.permission.INTERNET" />

5.This project is tested in android 2.2 call the url in a separate thread in android 3.0+ if a NetworkonMainThreadExecption occurs. Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows:






Android JSON Parser Example



In this example we will see how to parse a JavaScript Object Notation(JSON) response. Here we will use a set of classes from the org.json package offered in Android SDK by simply creating new JSONObject from the formatted string data.

Let us parse the following JSON response:

JSON response:
{
“person”:{
“name”:“Jack”,
“age”:27
}
}
1.Create a new project File ->New -> Project ->Android ->Android Application Project. Follow the wizard to create a project. After the project is created in the layout file activity_main.xml (in my case) create two text views and give the id as name and age. Refer the below code.

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="110dp"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

    <TextView
        android:id="@+id/age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

</RelativeLayout>

2.Now in the corresponding java file MainActivity.java (in my case) we will put the JSON response in a string and parse it. Since JSON parser is strict by default , meaning the execution will halt with an exception if an invalid JSON data is found or no data is found.

MainActivity.java:
import org.json.JSONException;
import org.json.JSONObject;

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

public class MainActivity extends Activity {

 public static final String JSON_STRING = "{\"person\":{\"name\":\"Jack Sparrow\",\"age\":27}}";

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  TextView name = (TextView) findViewById(R.id.name);
  TextView age = (TextView) findViewById(R.id.age);
  try {
   JSONObject person = (new JSONObject(JSON_STRING))
     .getJSONObject("person");
   String Name = person.getString("name");
   int Age = person.getInt("age");
   name.setText("Whats the name?\n" + Name);
   age.setText("Whats the age?\n" + Age);
  } catch (JSONException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}
3.Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows: