Advertisement
Android SDK

Build a Twitter Search App: Project Setup

by

This two-part tutorial series will introduce you to the fundamentals of working with RESTful web services using the Android SDK. Along the way, you'll learn how to perform searches against the public Twitter API!

It goes without saying that Internet access is one of the main assets you can exploit in Android devices. Many popular sites and social networks use Web services to provide access to their data, often using architectural models such as REST (Representational State Transfer). Twitter is one such service, with various APIs for accessing tweets and timelines. In this two-part series we will use the Twitter Search API to fetch recent tweets on a search term chosen by the user.

In this first part we will capture the user input and build the URL to use in an HTTP request to the Twitter search URL for tweets on the input term. In the second part we will retrieve the results, which will be formatted in JSON. We will parse the returned JSON tweet feed and display it within a simple visual interface.

This tutorial series on Android Twitter Search is in two parts:


Step 1: Create a New Project and Layout

Create a new Project in Eclipse: choose File > New > Project, and then select Android Application Project and click Next. Enter your chosen application, project and package names. You can leave the default minimum and target API levels selected. Select your chosen configuration options. In the Create Activity screen, select Blank Activity. In the next screen, enter "TwitterSearchActivity" as the Activity name and let Eclipse generate the layout file for you ("activity_twitter_search" by default).

New Android Activity

On clicking Finish, Eclipse should open your new layout file.

Open the Manifest file for your new project and select the "AndroidManifest.xml" tab to edit the code. Add the following element anywhere inside the Manifest element but outside all other elements:

<uses-permission android:name="android.permission.INTERNET"/>

This is necessary for any app accessing Internet resources.


Step 2: Build the User Interface

Let's now build the user interface elements. Open your main Activity layout file again and select the XML tab to edit the code directly. Depending on your Eclipse setup, you should have something like the following outline:

<RelativeLayout 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"
	tools:context=".TwitterSearchActivity" >

	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_centerHorizontal="true"
		android:layout_centerVertical="true"
		android:text="@string/hello_world" 
/>

</RelativeLayout>

If you have something different in your layout file, replace it with this code to begin with.

We can leave the Relative Layout the way it is, but replace the existing Text View with another slightly different one:

<TextView
	android:id="@+id/intro_txt"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:layout_centerHorizontal="true"
	android:textStyle="italic"
	android:text="@string/intro" 
/>

The ID is for laying out other items relative to this one. The other properties are for simple styling and positioning. Open your "res/values/strings.xml" file and add the string we've referred to above:

<string name="intro">Enter your Twitter search term</string>

This is just some informative text. Back in your layout file, after the Text View, add an Edit Text to capture the user search term:

<EditText
        android:id="@+id/search_edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="@string/hint"
        android:layout_below="@+id/intro_txt"
        android:padding="10dp"
        android:background="#ffff66"
        android:layout_margin="5dp"
/>

We position the element relative to the Text View we already added. Most of the other attributes are for styling; feel free to amend them as you wish. Add the string mentioned as a hint to your "strings.xml" file:

<string name="hint">Search Term</string>

After the Edit Text, add a button for the user to execute their search:

<Button
	android:id="@+id/search_btn"
	android:layout_height="wrap_content"
	android:layout_width="wrap_content"
	android:layout_centerHorizontal="true"
	android:text="@string/search_label"
	android:layout_below="@+id/search_edit"
	android:onClick="searchTwitter"
	android:layout_margin="5dp"
/>

Here we apply relative positioning and styling attributes again. We also specify a method to execute when the user clicks the button using the onClick attribute - we will add this method to the Activity class later. Add the specified string to your values file:

<string name="search_label">Search</string>

Next we will create the area in which retrieved tweets will be displayed. We do not know how long this section will be when it is displayed on-screen, so let's add a Scroll View so that users will be able to access all of it - after the Button:

<ScrollView
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:layout_below="@+id/search_btn">
        
</ScrollView>

Inside the Scroll View, add a final Text View:

<TextView
	android:id="@+id/tweet_txt"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:layout_gravity="top|center"
	android:padding="10dp"
	android:background="#330000"
	android:textColor="#ffffff"
	android:layout_margin="5dp"
	android:text="@string/placeholder" 
	android:freezesText="true"
/>

We will use the ID attribute to identify this Text View in Java when we display the retrieved tweets. Aside from layout properties, we also specify that the text should freeze, so that Android does not discard it on orientation changes. Add the final string to your strings values file:

<string name="placeholder">---</string>

That's our layout complete. You can of course modify the layout if you like, in these tutorials we are focusing on the practice of fetching the tweet feed over the Web. This is how the app will appear when you run it later:

Activity Layout

Step 3: Prepare the Activity Class

Open your main Activity class. The opening line of your class declaration should appear as follows:

public class TwitterSearchActivity extends Activity {

Eclipse should also have added a default onCreate method and optionally also an options menu method. Your onCreate method should set the main layout file we worked on as follows:

setContentView(R.layout.activity_twitter_search);

If any of the items mentioned are not present in your class file as created by Eclipse, please refer to the download folder attached to this tutorial.

Add the following import statements to your class, replacing any that Eclipse has already filled in:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
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.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

As you can see, we have imports for HTTP request and response handling, for processing incoming data, for parsing JSON data and for general Android components.

Inside your class declaration, add an instance variable to keep track of the Text View we created for displaying the fetched tweets:

private TextView tweetDisplay;

Inside your onCreate method, after the existing code, retrieve a reference to the Text View, storing it in the variable:

tweetDisplay = (TextView)findViewById(R.id.tweet_txt);

Now we can refer to this user interface item throughout the class. We will do so when displaying the fetched tweet feed and also when displaying error messages for the user if something goes wrong.


Step 4: Provide the Click Method

Remember that in the layout file, we added an onClick attribute to the Button, specifying a method named "searchTwitter" - let's implement that method now. Add it to your class after the existing methods:

public void searchTwitter(View view){

}

Because we listed it as an onClick attribute, the method will receive a reference to the View that was clicked. We do not actually need the Button that was clicked, what we want is the Edit Text View. Let's retrieve the text entered by the user, storing it as a string:

EditText searchTxt = (EditText)findViewById(R.id.search_edit);
String searchTerm = searchTxt.getText().toString();

We use the ID we gave the Edit Text in the layout file to identify it. Now, before we proceed, let's check that the user has entered a search term to prevent any unnecessary processing:

if(searchTerm.length()>0){
			
}
else 
	tweetDisplay.setText("Enter a search query!");

If the user has not entered anything, we simply output a message in the tweet feed Text View we have a reference to throughout the class.

Error Message

Step 5: Prepare and Encode the URL

The processing we are going to add next can throw Exceptions, so add try and catch blocks inside the if statement in the "searchTwitter" method:

try{

}
catch(Exception e){ 
	tweetDisplay.setText("Whoops - something went wrong!");
	e.printStackTrace(); 
}

If an Exception is thrown we simply write out an error message as we did when the user did not enter a search term.

To use the Twitter Search API, you append your search term to a base URL for the service. In case the user enters characters such as spaces, we will encode their text. Inside the try block, add the following:

String encodedSearch = URLEncoder.encode(searchTerm, "UTF-8");

Now let's build the Twitter Search API URL. This is the general format:

http://search.twitter.com/search.json?q=query

The text "query" should be replaced by the text you are searching for. To build the user text into this URL, add the following:

String searchURL = "http://search.twitter.com/search.json?q="+encodedSearch;

You can try fetching the JSON tweet feed in your Web browser by pasting the URL into your address bar and using any search term you want on the end, for example:

http://search.twitter.com/search.json?q=android

Your browser should display the JSON results, which are not easy to read but should give you an idea of what your application will receive on executing the query.


Conclusion

We are now ready to execute our Twitter search. In the next tutorial, we will create an AsyncTask class inside the main Activity class. This class will handle fetching the tweet feed using HTTP request and response objects in a background thread, then displaying the results within the UI. We will use the Java JSON processing libraries to parse the tweet feed and present it within the layout we created above.

Related Posts
  • Code
    Android SDK
    Create a Music Player on Android: Project Setup0d63m preview image@2x
    The Android platform provides resources for handling media playback, which your apps can use to create an interface between the user and their music files. In this tutorial series, we will create a basic music player application for Android. The app will present a list of songs on the user device, so that the user can select songs to play. The app will also present controls for interacting with playback and will continue playing when the user moves away from the app, with a notification displayed while playback elapses.Read More…
  • Code
    Android SDK
    Using the Accelerometer on Android06lom preview image@2x
    In this tutorial, we are going to explore how to use the accelerometer, one of the many hardware sensors of modern smartphones, in an Android application. I'll explain what an accelerometer is and why it may be something you want to take advantage of in your Android applications.Read More…
  • Code
    Android SDK
    Create a Hangman Game: User InterfaceAndroid hangman game preview retina
    In this series, we are creating a Hangman game for the Android platform. In the first tutorial, we set the application up to present two screens to the user and we also made a start with the user interface elements, the images and shape drawables to be precise. In the second tutorial, we will zoom in on the game's layout.Read More…
  • Code
    Android SDK
    Android SDK: User Interface DesignAndroid preview@2x
    In this series we're learning about Android SDK development from scratch! In this tutorial, we will build a simple user interface layout with a few visual elements.Read More…
  • Code
    Android SDK
    Android SDK: Create an Arithmetic Game - Setup and Interface CreationMath game preview@2x
    The Android platform provides the ability to facilitate interaction, to carry out computation, and to save data. To explore some of these basic features with a practical focus, this series will create a simple arithmetic game for the Android platform. The series will involve creating user interface elements and layouts, four Activity classes, and one helper class. The gameplay logic will be relatively complex if you do not have much Java experience, but you will learn to use various Java control structures along the way! Read More…
  • Code
    Android SDK
    Android SDK: Create a Book Scanning App - Interface & Book SearchBookscanning series preview@2x
    With the ZXing library, you can create Android applications with barcode scanning functionality. In Android SDK: Create a Barcode Reader, we implemented basic barcode reading with the library in a simple app. In this tutorial series, we will build on what we learned to create an app that will scan books and retrieve related information about them from Google Books API.Read More…