Android getting tweets from Twitter to your app

17 Jul

The following source code describes an app that gets ur very last tweet and displays it on a TextView, nothing to complicated on the xml part. It uses JSONParsing.

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.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class JSONStuff extends Activity{
		TextView tweet;
		final static String URL = "";
		HttpClient client;
		JSONObject json;
	protected void onCreate(Bundle b){
		tweet = (TextView) findViewById(;
		client = new DefaultHttpClient();
		new Read().execute("text");
	public JSONObject lastTweet(String username) throws ClientProtocolException, IOException, JSONException{
		StringBuilder url= new StringBuilder(URL);
		HttpGet get = new HttpGet(url.toString());
		HttpResponse r = client.execute(get);
		int status = r.getStatusLine().getStatusCode();
		if(status == 200 ){
			HttpEntity e = r.getEntity();
			String data = EntityUtils.toString(e);
			JSONArray timeline = new JSONArray(data);
			JSONObject last = timeline.getJSONObject(0);
			return last;
			Toast.makeText(JSONStuff.this, "Error", Toast.LENGTH_SHORT);
			return null;
	public class Read extends AsyncTask<String, Integer, String>{

		protected String doInBackground(String... params) {
			try {
				json = lastTweet("gilokimu");
				return json.getString(params[0]);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			return null;

		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub


Leave a comment

Posted by on July 17, 2012 in Uncategorized


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: