Pages

Sunday, March 17, 2013

Retrieve last tweet from twitter using JSON

XML
Don't forget to add Internet Permission. 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

   

    <Button
        android:id="@+id/btnShowTweets"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showTweets"
        android:text="Show Tweets!" />

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/tvJson"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Tweets:" />

        </LinearLayout>
    </ScrollView>

</LinearLayout>


JAVA

package com.example.jsontwiter;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

TextView tv;

// json used in async task do in background
JSONObject jsoon;

HttpClient client;
//Url from where data is retrived
final static String URL = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tvJson);


// In execute () write what we need to retrieve , it is the key reference . Here we need the tweet i.e tweet
//  is the key reference or maybe 'created at' key from twitter . Enter this address in your browser //http://api.twitter.com/1/statuses/user_timeline.json?screen_name=mehviish . You can see various keys .text //is the tweet.

new Read().execute("text");

}
//Creat a method called lastTweet and add exceptions.
public JSONObject lastTweet(String username) throws ClientProtocolException , IOException , JSONException{
client = new DefaultHttpClient();
StringBuilder urll = new StringBuilder(URL); //give above url
// In append add whatever is passed in the above STRING name i.e username
urll.append(username);


HttpGet get = new HttpGet(urll.toString());
HttpResponse r = client.execute(get);

int status = r.getStatusLine().getStatusCode();
// 200 is sucesful
if (status == 200) {
HttpEntity entity = r.getEntity();
String data = EntityUtils.toString(entity);
JSONArray timeline = new JSONArray(data);
// 0 coz we are retieving last tweet we can also keep any other number.
JSONObject last = timeline.getJSONObject(0); 

return last;

}
else


{

Toast.makeText(MainActivity.this, "Error",
Toast.LENGTH_SHORT).show();
return null;

}


}

public class Read extends AsyncTask<String, Integer, String>
{


@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// set json object equal to the method that we created above and in arguements give the id/username whose tweets you want to retrieve .
try {
// surrond with try catch
jsoon = lastTweet("mehviish");
// to return position 0 set param 0
return jsoon.getString(params[0]);


} catch (ClientProtocolException 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 null;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
tv.setText(result);

}

}
}

No comments:

Post a Comment