Android & Twitter - OAuth Authentication Tutorial

I’ve seen a lot of questions about connecting Android apps with Twitter using OAuth and thought I would write up a walkthrough of how it can be done. The example will be done using Twitter4J which is a great library for connecting Java apps with Twitter and provides a simple interface to connect to the public Twitter Web Services.

First thing you will need to do is to register your new app (even though you haven’t made it yet!). Do this by heading to https://dev.twitter.com/apps/new (you will need an existing Twitter account sign up). You should complete the form with the relevant details for your app:


You should fill in your details for the application such as name, description, URL – but the only key things to remember to do here are as follows:

1) Make sure you select “Browser” as your application type – even though we are creating an app, we will authenticate using the browser and a callback URL.

2) Tick read & write permissions

Once you have registered you will be provided with a “Consumer Key” and a “Consumer Secret” – make note of these for later – we will need to include these in the app.


Now let’s get started with the app! I will assume for this tutorial that you are familiar with the basics of Android apps so won’t go into details about how to setup the UI and what an Activity or Application is.
The first thing we will do is create an Activity that will prompt the user to login to Twitter and authorize the app to connect to Twitter to make updates. Let’s start with the onCreate method:


@Override
public void onCreate(Bundle savedInstanceState) {
 System.setProperty("http.keepAlive", "false");
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main_oauth);
 
 //check for saved log in details..
 checkForSavedLogin();

 //set consumer and provider on teh Application service
 getConsumerProvider();
 
 //Define login button and listener
 buttonLogin = (Button)findViewById(R.id.ButtonLogin);
 buttonLogin.setOnClickListener(new OnClickListener() {  
  public void onClick(View v) {
   askOAuth();
  }
 });
}

The first line we set the http keepAlive property – this is important so the app manages the connection correctly without reseting. The next important thing is our call to the checkForSavedLogin() method – this is a method that checks whether the user has previously authorised the app to access twitter, in which case we can just proceed as usual to the default twitter timeline activity (we will have a look at that method next). Otherwise we just initialise the Consumer/Provider and store them in our Application class so they are available to all Activities throughout the application. Then finally we inflate the button on the page and set a listener to call the askOAuth() method on click.


Now let’s jump in to the checkForSavedLogin() to see whats going on there:

private void checkForSavedLogin() {
 // Get Access Token and persist it
 AccessToken a = getAccessToken();
 if (a==null) return; //if there are no credentials stored then return to usual activity

 // initialize Twitter4J
 twitter = new TwitterFactory().getInstance();
 twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
 twitter.setOAuthAccessToken(a);
 ((TwitterApplication)getApplication()).setTwitter(twitter);
 
 startFirstActivity();
 finish();
}



This method calls a method getAccessToken() – all this does is check in the user SharedPreferences to see whether we have stored the users AccessToken previously – if there is no token found it just returns, so the user is left on the authentication activity waiting input.

However, if a token is found, then we initialise Twitter4J Twitter object and store that in our Application class (again, so we can use it throughout the application).
Finally we call startFirstActivity(), which simply calls the default Twitter timeline activity we have and finishes the authentication activity as it is not needed.

So that is all good, if the user has previously authenticated then no probs – however, if no saved token is found the user still needs to authenticate so we need to handle the user action (remember we are calling the askOAuth() method from within our button listener).



Let’s have a look at that method – this is where the authentication is all done:

private void askOAuth() {
 try {
  consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
  provider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token", "http://twitter.com/oauth/access_token", "http://twitter.com/oauth/authorize");
  String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
  Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
  setConsumerProvider();
  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
 } catch (Exception e) {
  Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
 }
}

First thing we do here is to initialise the Consumer and Provider objects – we are using the Commons OAuth Consumer/Provider (so you need to make sure you copy the following JARs in to your /assets/ directory and then add them to your build path: “signpost-commonshttp” and “signpost-core”).

You will see that the consumer is initialised using to static Strings CONSUMER_KEY and CONSUMER_SECRET – these need to be set to be the key and secret Twitter provided when you registered the app – you should make sure you keep these secret and not reveal them to people.

The provider is then just initialised using the relevant URLs that Twitter provides to authenticate againse.

Next, we call the retrieveRequestToken() method on the provider object, this takes two arguments: the consumer, and the CALLBACK_URL (another static string) we will come back to what this is later.

We then call startActivity with a new Intent using the authenticate URL – this is what will forward the user to the Twitter authentication service for them to securely login and authorize the app to make updates for them.



So now, we have a simple authentication activity, that if the user has never logged on before will forward them on to the Twitter OAuth service – next we need to handle the response from Twitter and if a successful response received, then store the Access Token for future use. This is all done in the onResume() method:

@Override
protected void onResume() {
 super.onResume();
 if (this.getIntent()!=null && this.getIntent().getData()!=null){
  Uri uri = this.getIntent().getData();
  if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
   String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
   try {
    // this will populate token and token_secret in consumer
    provider.retrieveAccessToken(consumer, verifier);

    // Get Access Token and persist it
    AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
    storeAccessToken(a);

    // initialize Twitter4J
    twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    twitter.setOAuthAccessToken(a);
    ((TwitterApplication)getApplication()).setTwitter(twitter);
    //Log.e("Login", "Twitter Initialised");
    
    startFirstActivity();

   } catch (Exception e) {
    //Log.e(APP, e.getMessage());
    e.printStackTrace();
    Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
   }
  }
 }
}


First thing, the method checks that the intent that has called the onResume is the expected intent, and then pulls out the verifying string from the callback URI – it then uses this string to retrieve the access token. Once we have called the retrieveAccessToken() method, we can initialise an AccessToken and store it. Next we initialise the Twitter4J object with the CONSUMER_KEY and SECRET again and then set the Access Token – once this has all been setup we just start the first activity as normal.
Once the user has authenticated they will be forwarded to the their friends timeline!

Now, the only thing remaining, is that we need to tell the app that once Twitter has finished authenticating that it needs to return to our Authentication Activity to call the above onResume method, or else it won’t be able to continue. To do this, Twitter will attempt to use the CALLBACK_URL we saw earlier. If you remember, when we requested the token from Twitter we passed in the CALLBACK_URL. I have previously defined this as follows:

private String CALLBACK_URL =           "callback://tweeter";

The name of the callback is up to you (I have named it “tweeter”), what is important is that this matches the callback you define in your Manifest XML. For the welcome activity (our Authentication activity) it needs to be defined as follows:


 
  
  
 
 
  
  
  
  
 



As you can see, we have defined an intent-filter with a scheme called “callback” and we provide the host name as “tweeter” – matching that used to call the Twitter service.

And thats it! The user has been authenticated and returned to our application correctly, so it can now continue to read timelines, post tweets, retweet, etc.



The complete source code of the application is available here (NOW ON GITHUB!), please note that I have removed my own CONSUMER_KEY/SECRET details, so to make this work you will need to register your app and populate with your own details to see it work in your emulator/device.

71 comments:

Getting Started - A Complete Android App walkthrough for Beginners (Part 2)

This is part 2 of a walkthrough of one of my first ever Android app, that happened to get a little bit of love in the android market, and for which the ENTIRE(!!) source code of the application is available to you good people to do whatever you want with.. see part 1 for more details of the app, what happened and the first steps in getting started!

So far, we have created a simple Activity class, designed a layout with several buttons and then implemented an onClickListener within our Activity class to handle the required actions for all of our buttons. The remaining Activities are all fairly straight forward, and work in a similar fashion: the RulesActivity is just a simple activity what has a block of text with a brief description of the game; the SettingsActivity is a simple activity that has three radio buttons which allows the user to select the difficulty; the QuestionsActivity just displays a question and then a selection of multiple choice answers.

If you are not familiar with Activities then you can open up those other classes and see exactly what is going on, they are all pretty similar but each have slight nuances or differences in their components and actions.

At the moment the application is pretty simple – there is a basic welcome screen with some buttons, and once you start the game you get taken through the QuestionsActivity several times, refreshing with different questions until you have answered all the questions, and then at the end it displays a simple graphic based on your accumulated score. Easy right?!

Really, the only big gap in what is going on is the DB – all the questions need to be stored in the DB on the client device, and then that data needs to be accessed, so we basically need a DAO type class.

In this app, we have a single DBHelper class – you may want to wrap this with a service class, to allow better separation of layers and decreased coupling etc, but for the sake of this app, lets just jump into the DBHelper. To access the DB on Android you need to have your class extend SQLLiteOpenHelper, now lets walk through the code required

private static String DB_PATH = "/data/data/com.tmm.android.chuck/databases/";
private static String DB_NAME = "questionsDb";
private SQLiteDatabase myDataBase; 
private final Context myContext;

First of all we define some simple class member variables. The DB_PATH will be used later to access our file that contains all our questions in it, the DB_NAME is just a name of choice to reference the DB.

public DBHelper(Context context) {
 super(context, DB_NAME, null, 1);
 this.myContext = context;
} 

You have to make sure you override the constructor, as this needs to initialise the context and DB before starting.

Next we have the createDatabase method – this one is quite straight forward:

public void createDataBase() throws IOException{

 boolean dbExist = checkDataBase();
 if(!dbExist)
 {
  this.getReadableDatabase();
  try {
   copyDataBase(); 
  } catch (IOException e) {
   throw new Error("Error copying database");
  }
 }
}


As you can see, it simply checks if the DB already exists, if it doesn’t (in which case its the first time that the app has been launched on this device) then it calls the copyDataBase() method:

private void copyDataBase() throws IOException{

 InputStream myInput = myContext.getAssets().open(DB_NAME);

 String outFileName = DB_PATH + DB_NAME;

 OutputStream myOutput = new FileOutputStream(outFileName);

 byte[] buffer = new byte[1024];
 int length;
 while ((length = myInput.read(buffer))>0){
  myOutput.write(buffer, 0, length);
 }

 //Close the streams
 myOutput.flush();
 myOutput.close();
 myInput.close();
}

Again, this is pretty straight forward – it just opens an Input stream to read the file (our questions file that we have saved in the /assets/ directory) and then writes it to the output stream which has been set up to be our DB Path/Name. Easy right?

So now we pretty much have our DBHelper class that checks for an existing DB, if its found then it opens a connection, if its not then it loads the data (our question set) in for the first time.

Now, the only remaining thing that our helper needs to do is to be able to access the data so we can select questions to show the user. So let’s look at how we add some DAO access methods. What I have done here is create a simple method to return a (random) question set:

public List getQuestionSet(int difficulty, int numQ){
 List questionSet = new ArrayList();

Cursor c = myDataBase.rawQuery("SELECT * FROM QUESTIONS WHERE DIFFICULTY=" + difficulty +
   " ORDER BY RANDOM() LIMIT " + numQ, null);
 
while (c.moveToNext()){
  Question q = new Question();
  q.setQuestion(c.getString(1));
  q.setAnswer(c.getString(2));
  q.setOption1(c.getString(3));
  q.setOption2(c.getString(4));
  q.setOption3(c.getString(5));
  q.setRating(difficulty);
  questionSet.add(q);
 }
 return questionSet;
}

Here, I am modelling the questions in a pre-created “Question” class – this just has the necessary member variables so I can handle the questions more easily than having to try and deal with DB cursors throughout the code. In the above method we just call a pure SQL statement, and then iterate through the cursor to populate my Question ArrayList.

And thats it! There are some other Activity classes and helper classes running doing small things throughout the app, but the core features are covered, so feel free to have a look around the code, edit it, change the design and just generally have fun.

43 comments:

Getting Started - A Complete Android App walkthrough for Beginners (Part 1)

About a year ago I released my first app on to the Android market. I had developed the market primarily as a learning tool, and at the end decided that putting it on the market would be a good step to understand the process and get some feedback.
The application was a simple quiz app based on the popular NBC series Chuck, I released it for free (no-ads) and no real advertising other than one or two target tweets. The app currently has about 4,000 – 5,000 downloads with a 4 star rating – both of which it achieved pretty quickly in the first month or two.



DISCLAIMER: I believe this to be purely down to the fact that at the time there weren’t really any other Chuck related apps, and it has a nerd-ish, cult like following, so I think the rating and popularity is more of a reflection on the show’s popularity than the quality of the app!


Anyway, I thought it might be interesting/helpful to release the source code here and walkthrough the different aspects of the code in a tutorial “my first app” kind of way.

I won’t go in to the setting up Eclipse/Android plug-ins stuff here, so will assume familiarity with getting around the IDE.


Android Directory Structure
Creating a new Android project in Eclipse (using the Android plug-ins) creates the required project structure automatically for you. Lets have a look at that now:


Src : as you would expect, this is the main java source directory, so this is where all your source code lives

Gen: this is the generated code that Eclipse handles for you – the files in here will be generated from your config. You needn’t really worry about what happens in here as Eclipse takes care of it for you

Assets: this can be used to contain any resources or libraries you want to bundle with the app – such as third party jars and data sets (you will see later we use this directory to store the data that we will load to populate all the questions in the DB when the app is first launched on a new device)

Res: this is where the configuration for the layout/UI aspects live:
- Drawable – keep you image files in here (.png/jpg/etc)
- Layout – this is where you keep the xml config for UI layout
- Values – this is where you keep the config with application code, such as application name or set text. This means you can easily change text through out the application without having to change hardcoded strings in the java code and re-compile


Getting Started
Ok, lets get started – the first thing we need is a welcome screen that is displayed when a user first launches the app. In Android, a screen is modelled by an “Activity” class, so to create our welcome screen we need to extend Activity.

public class SplashActivity extends Activity implements OnClickListener{

 @Override
 public void onCreate(Bundle savedInstanceState) {

Every class that overrides the Activity class must implement the onCreate() method – this is called when the activity is launched. As our welcome screen will just be a simple screen with a few buttons on it (play, rules, exit) we don’t need to do much at this point other than set up the buttons to have a listener so we know when one of them is pressed. For convenience here, we will set our current activity class to implement “OnClickListener” – this means we can define the onClick() method directly in our activity to handle the button events.

@Override
 public void onClick(View v) {
  Intent i; 
  switch (v.getId()){
  case R.id.playBtn :
   List questions = getQuestionSetFromDb();

   GamePlay c = new GamePlay();
   c.setQuestions(questions);
   c.setNumRounds(getNumQuestions());
   ((ChuckApplication)getApplication()).setCurrentGame(c);  

   //Start Game Now.. //
   i = new Intent(this, QuestionActivity.class);
   startActivityForResult(i, Constants.PLAYBUTTON);
   break;
   
  case R.id.rulesBtn :
   i = new Intent(this, RulesActivity.class);
   startActivityForResult(i, Constants.RULESBUTTON);
   break;
   
  case R.id.settingsBtn :
   i = new Intent(this, SettingsActivity.class);
   startActivityForResult(i, Constants.SETTINGSBUTTON);
   break;
   
  case R.id.exitBtn :
   finish();
   break;
  }
 }

As you can see, we have one single method that handles any button press, and we manage this with a switch statement checking the id of the view (we will go into this later). Mostly, the cases are simple, “exit” finishes the application whilst “rules” and “settings” have code like this:

i = new Intent(this, RulesActivity.class);
startActivityForResult(i, Constants.RULESBUTTON);

Intents are objects in Android that are used to communicate between activities, and as you can probably spot from the above, this simply creates a new Intent and then uses it to start another Activity class, in this case, our RulesActivity class.

The “Play” case is slightly more complicated – as this needs to initialise the game and load the questions to be used from the DB. Once it has done this, it loads the information in to our “Application” class (we will cover this later also) and then just kicks of the QuestionsActivity with a new Intent as per above.

So that is our welcome page pretty much done, we have a single screen that has a few buttons and we have setup listeners to perform appropriate actions on pressing them. The only remaining issue is the layout of the screen.


Activity Design

In the onCreate() method of our Activity you will notice the second line is

setContentView(R.layout.welcome);

This call tells Android which layout xml file should be used to configure the design – to find the relevant file is quite intuitive, its simply going to be located at /layout/welcome.xml



There are several layouts available to use, each of which are applicable in different circumstances, but as we are just going to have a straight list of buttons, we will use the simple “LinearLayout”. You can nest layouts, as you will see in this example, but lets walk through some of the config options we are using for our layout:

android:orientation="vertical" – This defines our layout as vertical, so new elements will be added on a new row below (if it were horizontal it would add as a new column)

android:layout_width="fill_parent" – this tells the activity to fill the whole width of the screen with the contents

android:layout_height="fill_parent" – this tells the activity to fill the whole width of the screen with the contents

android:gravity="center_horizontal" – this centers all elements that are contained in this layout

android:background="@drawable/background – this defines a background image to use for the activity (this image should exist at /drawable/background.png)


Now, if we look inside the layout you will see some simple components. The first one being a simple ImageView, which points to an image that we want to use as a header. The following elements are the buttons – you will notice that the ID of each button corresponds to the onCreate() method of our Activity where we inflate the button to set the onClickListener.
If you press the “Graphical Layout” tab in eclipse, you will see what the welcome screen will look like.




Ok, so we have our welcome Activty, we have designed a nice UI to control the app and have an onClick handler - the next part will cover intergrating with the DB to pull out the questions and then we are all there!


Grab complete source code for the project here

38 comments:

Getting Started - Best Books to learn Android

I wanted to recommend a couple of great books to get people started learning Android (of course, you could just skip the books and just use some of my tutorials including source code ;)



Hello, Android
This is a nice introduction to the Android platform - walking through from simple applications (as you may guess from the title!) through to some more complex topics such as working with Android's built in SQLite DB and OpenGl Graphics.
Note though that the book isnt a Java book (as none of these here are), and whilst its an introduction to Android, its not an introduction to the wider Java language structure/syntax - so will assume an understanding of the background.



Beginning Android Games
A great book to get started with Android game development! One of the nice things about this book is that it a more hollistic walkthrough of mobile game development and covers more general topics and issues for the area, whilst also providing specific Android examples to try out, it should give you a firm grounding in Android Game development.
The one thing to note that whilst this book does give you an excellent base in game development, it doesn't cover any of the great libraries currently existing for game development such as AndEng, libGDX, Rokon etc


Pro Android 2
This book is actually in its third edition now, but I only have the second edition, so I will link that here - although edition 3 is probably also a good shout.
First thing to mention, don't be fooled by the name! Whilst it descibes itself as Pro Android, it is still pretty suitable for a beginner (I found it was anyway, as long as you know Java, XML, etc) - and actually if you are looking for a "Pro" book this may not be the one for you as it doesn't cover all the topics you may expect for a pro book - such as use of the accelerometer and physics engines. That said, it does provide a solid covering of core topics needed for Android development right through from UI/Menu design through to also covering 2+3/D graphics.

1 comments: