Show me the code! – By Davanum Srinivas

Web Services, Apache, Websphere, IBM, etc.

Twitter Client for Android (How to make XML over HTTP calls)

with 48 comments

Since pictures say a thousand words! – Here are the screen shots

001
002
003

Functionality

Code for posting a new tweet

package org.apache.twitter;

import android.app.Activity;
import android.content.Intent;
import android.net.http.RequestQueue;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Initial screen with edit box for tweets and
 * a web view to display the tweets from friends
 */
public class TwitterClient extends Activity {

    static final int GET_LOGIN_INFORMATION = 1;

    WebView webView;
    RequestQueue requestQueue;
    String authInfo;

    /**
     * Called with the activity is first created.
     */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        // Set the initial text
        webView = (WebView) findViewById(R.id.webView);
        webView.loadData(
                "Please click on setup and enter your twitter credentials",
                "text/html", "utf-8");

        // When they click on the set up button show the login screen
        Button button = (Button) findViewById(R.id.setup);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(TwitterClient.this, TwitterLogin.class);
                startSubActivity(intent, GET_LOGIN_INFORMATION);
            }
        });

        // When they click on the Tweet! button, then get the
        // text in the edit box and send it to twitter
        final Activity activity = this;
        Button button2 = (Button) findViewById(R.id.update);
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.i("http", "Update clicked");
                Map headers = new HashMap();
                if (authInfo == null) {
                    return;
                }
                headers.put("Authorization", "Basic " + new String(Base64.encodeBase64(authInfo.getBytes())));
                EditText user = (EditText) findViewById(R.id.updateText);
                String text = null;
                try {
                    text = "status=" + URLEncoder.encode(user.getText().toString(), "UTF-8");
                    Log.i("http", "with " + text);
                } catch (UnsupportedEncodingException e) {
                    Log.e("http", e.getMessage());
                }
                byte[] bytes = text.getBytes();
                ByteArrayInputStream baos = new ByteArrayInputStream(bytes);
                // See Twitter API documentation for more information
                // http://groups.google.com/group/twitter-development-talk/web/api-documentation
                requestQueue.queueRequest(
                        "https://twitter.com/statuses/update.xml",
                        "POST", headers, new MyEventHandler2(activity), baos, bytes.length, false);
            }
        });

        // Start a thread to update the tweets from friends every minute
        requestQueue = new RequestQueue(this);
        Thread t = new Thread(new MyRunnable(this));
        t.start();
    }

    protected void onActivityResult(int requestCode, int resultCode,
                                    String data, Bundle extras) {
        if (requestCode == GET_LOGIN_INFORMATION && resultCode == RESULT_OK) {
            // Save the user login information
            authInfo = data;
        }
    }

}

Download the sources and Application – TwitterClient.zip

UPDATE (3:41 PM EST on Nov 25) : Updated zip with the correct manifest file

Written by Davanum Srinivas

November 21, 2007 at 10:21 am

Posted in Uncategorized

48 Responses

Subscribe to comments with RSS.

  1. [...] Plus d’infos chez Davanum. [...]

  2. [...] de poster et lire ses messages sur son compte Twitter. L’application est disponible sur Show Me The Code, un très bon site au passage !! Cet article à été publié le Mercredi, novembre 21st, 2007 at [...]

    » Twitter sur Android

    November 21, 2007 at 12:49 pm

  3. [...] Tras la salida de Android, aparecen las primeras aplicaciones desarrolladas para este sistema operativo móvil. Y como no, una de las primeras aplicaciones ha sido un cliente twitter. [...]

  4. [...] Davanum Srinivas has been having some fun creating Android tutorials and releasing his sample code since the platform was released last week.  Yesterday, he released his sample concept code for a Twitter client. [...]

  5. [...] n’aura pas fallu attendre longtemps pour voir un client Twitter pour Android voir le jour que je suggère d’ailleurs d’appeler Twitteroid ! Cette application [...]

  6. [...] http://davanum.wordpress.com/2007/11/21/twitter-client-for-android-how-to-make-xml-over-http-calls (Pas de chance, je me suis fait grillé, cf: mon post d’hier sur mon développement utilisant Xml + Http. A noter que je n’ai pas utilisé les même techniques…) [...]

  7. thanks for the sample code; could you fix the AndroidManifest.xml though? It’s a zip-file itself, and the real AndroidManifest.xml is nowhere to be found. Thanks!

    MikeR

    November 21, 2007 at 5:16 pm

  8. It’s funny I found this exactly today, I just posted about my twitter client http://underdev.org/2007/11/21/announcing-twitteroid/
    I had a look at your code, I was unaware of the requestqueue and ended up doing it myself, well it was a good exercise.

    Cheers.

    Diogo Ferreira

    November 21, 2007 at 6:45 pm

  9. [...] и исходники Twitter Client’а [...]

  10. I’m From Brazil!
    Very Good you Blog!

    Letra

    November 22, 2007 at 1:22 pm

  11. [...] Link – Twitter Client for Android (How to make XML over HTTP calls) [...]

  12. [...] Source codes of this free application are available from the author’s homepage. [...]

  13. [...] vous permet de dire au monde entier ce que vous êtes en train de faire à l’instant t. Le code source du client Android est disponible sur le site de [...]

  14. Great little app! I’m quite suprised how short and easy the actual final code is. Though the hardest part is the UI I guess. As MikeR says, can you put the correct version of AndroidManifest.xml in your zip? The one that’s there is corrupt (is actually indeed a zip file). Thanks!

    Marco

    November 25, 2007 at 2:21 pm

  15. Sorry folks, here’s the AndroidManifest.xml

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.apache.twitter">
    <application>
    <activity class=".TwitterClient" android:label="Twitter Client">
    <intent-filter>
    <action android:value="android.intent.action.MAIN"/>
    <category android:value="android.intent.category.LAUNCHER"/>
    </intent-filter>
    </activity>
    <activity class=".TwitterLogin" android:label="TwitterLogin">
    <intent-filter>
    </intent-filter>
    </activity>
    </application>
    </manifest>

    davanum

    November 25, 2007 at 3:39 pm

  16. [...] is very active these days on Android application development, he created the first twitter client for Android showing how to make XML over HTTP calls. The application allow simply to send tweets and view your [...]

  17. How did you discover the ” android.net.http.* ” package?

    I’d like to get some documentation on the RequestQueue class, but the http package is no where to be found at http://code.google.com/android/

    Danny

    November 28, 2007 at 6:14 pm

  18. Interesting application, in fact this one is the first that i could see with this SDK. Nice job.

    KnxDT

    November 30, 2007 at 10:06 am

  19. [...] para el idioma castellano para el nuevo sistema. Podemos descargar el cliente Twitter desde este enlace tambien encontraremos capturas de pantalla pero lo mas importante por lo que debes visitar ese [...]

  20. [...] monde entier sur des projets simples mais intéressant et fonctionnels. On peux citer en vrac son Client Twitter, son Client GTalk, son utilitaire de GéoLocalisation sans GPS et bien d’autre que nous vous [...]

    » Le développeur du mois

    December 2, 2007 at 1:34 pm

  21. [...] recognition)(链接) 当前位置声音提示(Tweet current location)(链接) 在屏幕上动态跟踪GPS定位并把GPS路线存储到数据库上(以便今后查看) [...]

  22. do u have some doc of package android.net.http

    Neo

    December 26, 2007 at 12:13 am

  23. [...] para Android” está bastante complicado. A CallFreq también se agrega el cliente de Twitter y WhatsOpen, ésta última desarrollada por el mismísimo Sergei [...]

  24. [...] is very active these days on Android application development, he created the first twitter client for Android showing how to make XML over HTTP calls. The application allow simply to send tweets and view your [...]

  25. [...] Twitter Client for Android (How to make XML over HTTP calls) [...]

  26. [...] 提交的代码:Twitter Client for Android (How to make XML over HTTP calls) 名字(必须) Email(必须) 网址 [...]

  27. [...] get started Davanum also provides the source code on his page to give developers and insight view into Android [...]

  28. [...] Link:Twitter Client for Android (How to make XML over HTTP calls)  Name Mail (will not be published) [...]

  29. [...] Source  : davanum.wordpress.com [...]

  30. Does anyone know another place to get the .zip file. the link on this page does not work.

    I really need the res files
    thanks

    Jeff

    September 17, 2008 at 12:24 pm

  31. [...] blog has the source code, but the screenshots and downloads are missing, so I’m hosting a copy of the .ZIP download [...]

  32. [...] enviar y recibir tweets. Fue una de las primeras aplicaciones desarrolladas para Android por un desarrollador que no pertenecía a [...]

  33. [...] There are actually three other Twitter apps in development for Android, as shown here – TwitterDroid, Trak, and one that isn’t really named, by Davanum Srinivas. [...]

  34. I saw about 3 project which were based upon this code. Too pity davanum is not contributing to the Android community :( Great tutorial anyway!

    android freeware

    October 30, 2008 at 9:45 pm

  35. Hi, I can’t download TwitterClient.zip, there is page error. How can i get it, if there are other useful source code sample links, show me the way coz i am a beginner!
    Thanks….

    Thaw

    November 5, 2008 at 8:15 pm

  36. Tony

    February 17, 2009 at 9:33 am

  37. [...] Twitter Client for Android A tutorial showing how to create a Twitter client for Android (i.e. how to make XML-over-HTTP calls). [...]

  38. [...] Twitter Client for Android A tutorial showing how to create a Twitter client for Android (i.e. how to make XML-over-HTTP calls). [...]

  39. [...] Twitter Client for Android A tutorial showing how to create a Twitter client for Android (i.e. how to make XML-over-HTTP calls). [...]

  40. [...] for the emulator). There is an interesting Twitter Client example, albeit it’s an M3 project here by Davanum Srinivas. This example uses a WebView rather than an Adapter so it ‘might’ [...]

  41. Hi:

    I would like to use your code for an application that I am planning to do. Are you releasing it under any kind of license?

    Thank you very much
    Regards

    Pipex

    March 16, 2009 at 6:41 pm

  42. The link is broken, help!

    Craig Allen

    April 7, 2009 at 9:05 pm

  43. where can i download the soure code?

    virtue

    May 10, 2009 at 6:37 am

    • See tony’s reply above for missing zip file.

      yenliangl

      May 13, 2009 at 12:27 am

  44. All the links to the source of your apps are broken

    ScaredyCat

    May 17, 2009 at 8:20 am


Leave a Reply