Friday 5 December 2014

Twitter Integration in Android and Its new API v1.1

Twitter API v1 Retirement and Use case of Use API v1.1

The Twitter REST API v1 will officially retire on June 11, 2013 . So it is time now to migrate your all application from API v1 to API v1.1.

If you are using Twitter4J jar file in your application then simply update your application with this jar file “ twitter4j-core-3.0.3” in your libs folder of application. There is some change in method also in this file. Here I am showing the list of that method changed in this new jar file.

Retired method
migrate to
disableNotification()
updateFriendship()
enableNotification()
updateFriendship()
getProfileImage()
User#getBigger|Mini|OriginalProfileImageURL()
getBlockingUsersIDs()
getBlocksIDs()
getLocationTrends()
getPlaceTrends()
getAllUserLists()
getUserLists()
getAvailableTrends(GeoLocation)
getClosestTrends(GeoLocation)
getFavorites(int)
getFavorites(Paging paging)
getBlockingUsers()
getBlocksList(cursor)
getPublicTimeline()
N/A
AccountTotals getAccountTotals()
N/A
IDs getNoRetweetIds()
N/A
IDs getRetweetedByIDs(long)
N/A
IDs getRetweetedByIDs(long, Paging)
N/A
getRetweetedByMe()
N/A
getRetweetedByUser()
N/A
getRetweetedToMe()
N/A
getRetweetedToUser()
N/A
getRetweetsOfMe()
N/A
getDailyTrends()
N/A
getWeeklyTrends()
N/A
getRetweetedBy()
N/A
boolean existsBlock()
N/A
boolean existsFriendship()
N/A
boolean test()
N/A

Updating Twitter4j jar file in Android Application

step 1:-
Open You existing project Right click on Project folder >> property>>Java Build Path>>library>> select previous Twitter4j-core file >> click on remove

Now Copay and paste Twitter4j-core-3.0.3 jar file in your existing project libs folder and do the following
right click on Project >> properties>>java Build Path>>library>> add Jar >> choose your project libs folder >.select the Twitter4j-core-3.0.3 file and >> apply.

Step 2
After performing step first and go into your src folder source code and modify the required method if needed as per above given table.This the basic way to you update existing twitter integration in android.
Now I am going to show a simple integration of Twitter in android
 Step 1.
You need to create a following classes and xml file for this integration:-
1. TwitterHomeActivity (main class)
2. ConnectionDetector( For checking Internate connection)
3. AlertDialogManager ( For Alert Message)
4. activity_twitter_home.xml( mail activity class xml)

Step 2
Use following code for this integration:-
public class AlertDialogManager {

public void showAlertDialog(Context context, String title, String message, Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    if(status != null)
        // Setting alert dialog icon
        alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }
    });

    // Showing Alert Message
    alertDialog.show();
}}

public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context){
    this._context = context;
}
public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      Log.d("Network", "NETWORKnAME: "+info[i].getTypeName());
                      return true;
                  }

      }
      return false;
}}
 Android Manifest file look like this
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk
    android:minSdkVersion="6"
    android:targetSdkVersion="8" />
<!-- Permission - Internet Connect -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.sks.twitter.TwitterHomeActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="t4jsample"
                android:scheme="oauth" />
        </intent-filter>
    </activity>
</application>
 Activity_twitter_home.xml look like this
<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=".TwitterHomeActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="106dp"
    android:layout_marginTop="21dp"
    android:text="@string/hello_world"
    android:textColor="#A52A2A"
    android:textStyle="bold"
    android:typeface="serif" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="80dp"
    android:text="Login to twitter" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:visibility="gone"
    android:ems="10" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="34dp"
    android:visibility="gone"
    android:text="Tweets" />
 Finally TwitterHomeActivity code
public class TwitterHomeActivity extends Activity {
    static String TWITTER_CONSUMER_KEY = "marlVCZaLYAG52rVvholRw"; 
static String TWITTER_CONSUMER_SECRET = "5uZZFboHSK9psBPsqJUDSb1GuC36Fy83cYornOPu9A"; 
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

ProgressDialog pDialog;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
EditText sts;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_twitter_home);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


    cd = new ConnectionDetector(getApplicationContext());
    if (!cd.isConnectingToInternet()) {
        alert.showAlertDialog(TwitterHomeActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        return;
    }
    // Check if twitter keys are set
    if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
        alert.showAlertDialog(TwitterHomeActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
        return;
    }
    mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

    findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            loginToTwitter();
        }
    });
    findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            sts = (EditText)findViewById(R.id.editText1);
            String status = sts.getText().toString();
            if (status.trim().length() > 0) {
                new updateTwitterStatus().execute(status);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter status message", Toast.LENGTH_SHORT).show();
            }

        }
    });

    if (!isTwitterLoggedInAlready()) {
        Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
            String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
            try {
                AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
                // Shared Preferences
                Editor e = mSharedPreferences.edit();
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET,accessToken.getTokenSecret());
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit();

                Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

                findViewById(R.id.button1).setVisibility(View.GONE);
                findViewById(R.id.editText1).setVisibility(View.VISIBLE);
                findViewById(R.id.button2).setVisibility(View.VISIBLE);

                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);
                String username = user.getName();
                Log.e("UserID: ", "userID: "+userID+""+username);
                Log.v("Welcome:","Thanks:"+Html.fromHtml("<b>Welcome " + username + "</b>"));
            } catch (Exception e) {
                Log.e("Twitter Login Error", "> " + e.getMessage());
            }
        }
    }
}

private void loginToTwitter() {
    if (!isTwitterLoggedInAlready()) {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        Configuration configuration = builder.build();

        TwitterFactory factory = new TwitterFactory(configuration);
        twitter = factory.getInstance();

        try {
            requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
            this.startActivity(new Intent(Intent.ACTION_VIEW, 
                    Uri.parse(requestToken.getAuthenticationURL())));
        } catch (TwitterException e) {
            e.printStackTrace();
        }
    } else {
        Toast.makeText(getApplicationContext(),
                "Already Logged into twitter", Toast.LENGTH_LONG).show();
    }
}
private boolean isTwitterLoggedInAlready() {
    return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
class updateTwitterStatus extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(TwitterHomeActivity.this);
        pDialog.setMessage("Updating to twitter...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected String doInBackground(String... args) {
        Log.d("Tweet Text", "> " + args[0]);
        String status = args[0];
        try {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
            // Access Token 
            String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
            // Access Token Secret
            String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

            AccessToken accessToken = new AccessToken(access_token, access_token_secret);
            Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

            // Update status
            twitter4j.Status response = twitter.updateStatus(status);

            Log.d("Status", "> " + response.getText());
        } catch (TwitterException e) {
            // Error in updating status
            Log.d("Twitter Update Error", e.getMessage());
        }
        return null;
    }
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),
                        "Status tweeted successfully", Toast.LENGTH_SHORT)
                        .show();
                // Clearing EditText field
                sts.setText("");
            }
        });
    }

}}
Refrence Link for more detail:--
https://dev.twitter.com/blog/changes-coming-to-twitter-api
https://dev.twitter.com/docs/api/1.1/overview
https://dev.twitter.com/blog/planning-for-api-v1-retirement
http://twitter4j.org/en/versions.html#migration22x-30x
https://groups.google.com/forum/?fromgroups#!forum/twitter4j
                   Happy Coding!!!

27 comments:

  1. hello,i followed the steps for adding twitter4j-core-3.0.3.jar in my exsisting project.But still not able to login twitter successfully from my application.Please can u help me or help me with some sample code..(before my application was able to login successfully)

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. 12-03 19:45:01.695: W/System.err(20743): 403:The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (https://support.twitter.com/articles/15364-about-twitter-limits-update-api-dm-and-following).
      12-03 19:45:01.695: W/System.err(20743): SSL is required
      12-03 19:45:01.695: W/System.err(20743): Relevant discussions can be found on the Internet at:

      Delete
  2. thank you very much
    very good post

    ReplyDelete
  3. Thank 's man , i am implement your code that is running success fully ,but this will not open in dialog box ,please tell me how to open twitter in dialog box.

    ReplyDelete
  4. Thanks You All
    @test Twitter authentication API is different from Facebook Authentication. Facebook use Graph API . So Facebook shows Dialog but Twitter did not..

    @ Joshe Here is the link you can download whole Eclipse project in Zip file
    https://github.com/Saurabh-12/SocialIntegrationAndroid.git

    ReplyDelete
  5. Hi Saurabh

    This Code is working on 2.3 (Gingerbread) but not in the 4.0 (Ice Cream Sandwich)any suggestion

    Regards
    Vikash

    ReplyDelete
    Replies
    1. @Vikash This code working properly in 2.3 to 4.0 . I tested it and same sample code i posted on Github. Please post your LogCat error or give the name of error so that i solve this issue.

      Delete
  6. IT is working Saurabh thanks nice tutorial

    ReplyDelete
  7. it gives me android.os.NetworkOnMainThreadException on login button.please needful to me.

    ReplyDelete
    Replies
    1. You run your login operation on asynchrnous thread....

      Delete
    2. just you add within oncreate method

      if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
      }

      Delete
  8. Good one Saurabh. Nice tutorial

    ReplyDelete
  9. hi saurabh...

    nice example from you..
    But its not working in ics throwing android.os.NetworkOnMainThreadException error...

    pls check n update...

    ReplyDelete
    Replies
    1. You run your login operation on asynchrnous thread....

      Delete
    2. if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
      }

      Delete
  10. Hi, I get this messages in orange. Any help? :( thanks

    09-23 02:52:20.837: W/System.err(3122): 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
    09-23 02:52:20.837: W/System.err(3122):
    09-23 02:52:20.837: W/System.err(3122):
    09-23 02:52:20.837: W/System.err(3122): Desktop applications only support the oauth_callback value 'oob'
    09-23 02:52:20.847: W/System.err(3122): /oauth/request_token
    09-23 02:52:20.847: W/System.err(3122):

    09-23 02:52:20.857: W/System.err(3122): TwitterException{exceptionCode=[10f5ada3-e574402b], statusCode=401, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
    09-23 02:52:20.867: W/System.err(3122): at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:177)
    09-23 02:52:20.867: W/System.err(3122): at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
    09-23 02:52:20.867: W/System.err(3122): at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:98)
    09-23 02:52:20.867: W/System.err(3122): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:122)
    09-23 02:52:20.867: W/System.err(3122): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
    09-23 02:52:20.867: W/System.err(3122): at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:281)
    09-23 02:52:20.878: W/System.err(3122): at com.lepe.androidtwitter.TwitterHomeActivity.loginToTwitter(TwitterHomeActivity.java:138)
    09-23 02:52:20.878: W/System.err(3122): at com.lepe.androidtwitter.TwitterHomeActivity.access$1(TwitterHomeActivity.java:127)
    09-23 02:52:20.878: W/System.err(3122): at com.lepe.androidtwitter.TwitterHomeActivity$1.onClick(TwitterHomeActivity.java:77)
    09-23 02:52:20.887: W/System.err(3122): at android.view.View.performClick(View.java:4202)
    09-23 02:52:20.887: W/System.err(3122): at android.view.View$PerformClick.run(View.java:17340)
    09-23 02:52:20.887: W/System.err(3122): at android.os.Handler.handleCallback(Handler.java:725)
    09-23 02:52:20.897: W/System.err(3122): at android.os.Handler.dispatchMessage(Handler.java:92)
    09-23 02:52:20.897: W/System.err(3122): at android.os.Looper.loop(Looper.java:137)
    09-23 02:52:20.897: W/System.err(3122): at android.app.ActivityThread.main(ActivityThread.java:5039)
    09-23 02:52:20.897: W/System.err(3122): at java.lang.reflect.Method.invokeNative(Native Method)
    09-23 02:52:20.897: W/System.err(3122): at java.lang.reflect.Method.invoke(Method.java:511)
    09-23 02:52:20.897: W/System.err(3122): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    09-23 02:52:20.897: W/System.err(3122): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    09-23 02:52:20.897: W/System.err(3122): at dalvik.system.NativeStart.main(Native Method)
    09-23 02:52:20.917: W/Trace(3122): Unexpected value from nativeGetEnabledTags: 0

    ReplyDelete
  11. I made it work. The error was appearing because there was no callback url in my Twitter App. I just added a valid url (google+ in my case) in my twitter app at (https://dev.twitter.com/) saved changes and that's it.

    Thanks

    ReplyDelete
  12. In my application, i will select a content that will tweet in twitter, please provide for this example.

    ReplyDelete
  13. after login on twitter i donot redirect back to app...what is the solution of this problem

    ReplyDelete
  14. I get a twitter login error, do you have any idea why this might be happening?

    11-22 18:02:49.679: E/ Twitter Login Error(23182): > null

    ReplyDelete
  15. Hello saurabh good artical .And is there any code for posting Image with text in twitter new api with android application because olderjar fiole is not working in n4.0 version devices

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. Very useful information that you have shared and it is very useful to me.Thanks for sharing the information with us.

    ios app development company in chennai

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...