i want to integration a twitter in my application,
this is my code:
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = "<my key>";
static String TWITTER_CONSUMER_SECRET = "<my secure key>";
// Preference Constants
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";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "https://api.twitter.com/oauth/authenticate";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Login button
Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
/**
* This if conditions is tested once is redirected from twitter page.
* Parse the uri to get oAuth Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
Log.e("Twitter Login ... >", 0+"");
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
Log.e("Twitter Login ... >", 1+"");
// Shared Preferences
Editor e = mSharedPreferences.edit();
Log.e("Twitter Login ... >", 2+"");
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
Log.e("Twitter Login ... >", 3+"");
User user = twitter.showUser(userID);
String username = user.getName();
Log.e("Twitter Login ... >", 4+"");
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username
+ "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
new myConnection().execute(1);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
class myConnection extends AsyncTask<Integer, Integer, Integer> {
#Override
protected Integer doInBackground(Integer... params) {
// Check if already logged in
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);
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
}
return 1;
}
}
}
The Log prints Twitter Login ... > 0 and then an exception happened , i catch and print this statment
Log.e("Twitter Login Error", "> " + e.getMessage());
the e.getMessage() is null
any help would be appreciated
Its all about the CallbackURL. You need to put some coding for handling the WebView. SO that after redirecting from the twitter.!! Check the code that i given below.!!
I set up Twitter user authentication as in the tutorial above such that the Activity doing the Twitter authentication has its content view changed to a WebView, the Activity is declared in the manifest file containing an intent-filter to catch the Twitter callback and, on callback, the response is processed and the Activity's content view is changed back to whatever it was.
I got it working but in doing so I found (what I think is) an easier way and such that the WebView doesn't ever kick off the phone's web browser app (thereby leaving your app, which you don't really want), as follows:
(1) Remove the Activity singleInstance and intent-filter declarations you added to the manifest file (in following the tutorial above). Don't need that anymore!
(2) Add a WebView to your Activity layout file and set its initial visibility to "gone" and its position, height, width etc however you want it. I set its properties so that it covers the whole screen when visible, as follows:
<WebView
android:id="#+id/myWebView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
(3) Get a handle to your WebView in your Activity and set its WebViewClient to pick up the Twitter callback (and not to kick off the web browser app at any time), as follows...
myWebView = (WebView)findViewById(R.id.myWebView);
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
if (url != null
&& url.startsWith("myapptwittercallback:///myapp"))
handleTwitterCallback(url);
else
webView.loadUrl(url);
return true;
}
});
... Here you might also want to enable other settings of your WebView like saving form data and javascript execution (e.g. myWebView.getSettings().setJavaScriptEnabled(true);)
(4) Make your WebView visible and focused at the point you need to do Twitter authentication, as follows:
try
{
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(
myTwitterConsumerKey,
myTwitterConsumerSecret);
twitterRequestToken = twitter.getOAuthRequestToken(
"myapptwittercallback:///myapp");
myWebView.loadUrl(
twitterRequestToken.getAuthenticationURL());
myWebView.setVisibility(View.VISIBLE);
myWebView.requestFocus(View.FOCUS_DOWN);
}
catch (TwitterException ex)
{
Toast.makeText(
this,
"Login failed. Please try again.",
Toast.LENGTH_SHORT).show();
}
... Remember to clear your WebView's history (i.e. myWebView.clearHistory() and set its visibility to "gone" in your handleTwitterCallback(String) method.
(5) Lastly, override your Activity's onBackPressed() method so that your WebView handles presses of the back button if its visible, as follows...
#Override
public void onBackPressed()
{
if (myWebView.getVisibility() == View.VISIBLE)
{
if (myWebView.canGoBack())
{
myWebView.goBack();
return;
}
else
{
myWebView.setVisibility(View.GONE);
return;
}
}
super.onBackPressed();
}
That's it! You should now have Twitter integration in your app and the user should never leave your app in doing Twitter authentication.
Related
This question already has answers here:
Changing Locale within the app itself
(6 answers)
Closed 8 years ago.
I have created a login page which consists of username password login button and change language option(drop down consisting of required languages).
Login Page
My problem is how to apply internationalization to all the pages.Suppose if click on french it should be applied to to login page as well as the next page after login.Please Help..
MainActivity.java
package com.example.login11;
import java.util.HashMap;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity
{
// User Session Manager Class
UserSessionManager session;
// Button Logout
Button btnLogout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Session class instance
session = new UserSessionManager(getApplicationContext());
TextView lblName = (TextView) findViewById(R.id.lblName);
TextView lblEmail = (TextView) findViewById(R.id.lblEmail);
// Button logout
btnLogout = (Button) findViewById(R.id.btnLogout);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
// Check user login (this is the important point)
// If User is not logged in , This will redirect user to LoginActivity
// and finish current activity from activity stack.
if(session.checkLogin())
finish();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// get name
String name = user.get(UserSessionManager.KEY_NAME);
// get email
String email = user.get(UserSessionManager.KEY_EMAIL);
// Show user data on activity
lblName.setText(Html.fromHtml("Name: <b>" + name + "</b>"));
lblEmail.setText(Html.fromHtml("Email: <b>" + email + "</b>"));
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Clear the User session data
// and redirect user to LoginActivity
session.logoutUser();
}
});
}
}
LoginActivity.java
package com.example.login11;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class LoginActivity extends ActionBarActivity
{
Button btnLogin;
EditText txtUsername, txtPassword;
private Spinner language;
// User Session Manager Class
UserSessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// User Session Manager
session = new UserSessionManager(getApplicationContext());
// get Email, Password input text
txtUsername = (EditText) findViewById(R.id.txtUsername);
txtPassword = (EditText) findViewById(R.id.txtPassword);
language = (Spinner) findViewById(R.id.spinner1);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
// User Login button
btnLogin = (Button) findViewById(R.id.btnLogin);
// Spinner method to read the on selected value
ArrayAdapter<State> spinnerArrayAdapter = new ArrayAdapter<State>(this,
android.R.layout.simple_spinner_item, new State[] {
new State("english"), new State("french") });
language.setAdapter(spinnerArrayAdapter);
//language.setOnItemSelectedListener(this);
// Login button click event
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get username, password from EditText
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
// Validate if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
// For testing puspose username, password is checked with static data
// username = admin
// password = admin
if(username.equals("admin") && password.equals("admin")){
session.createUserLoginSession("Android Example",
"androidexample84#gmail.com");
// Starting MainActivity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}else{
// username / password doesn't match&
Toast.makeText(getApplicationContext(),
"Username/Password is incorrect",
Toast.LENGTH_LONG).show();
}
}else{
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Please enter username and password",
Toast.LENGTH_LONG).show();
}
}
});
}
}
userSession.java
package com.example.login11;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class UserSessionManager
{
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREFER_NAME = "AndroidExamplePref";
// All Shared Preferences Keys
private static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// Constructor
public UserSessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String name, String email){
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
// Storing email in pref
editor.putString(KEY_EMAIL, email);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
* */
public boolean checkLogin(){
// Check login status
if(!this.isUserLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
// Check for login
public boolean isUserLoggedIn(){
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
You can do something like this:
public class LanguagePesistence {
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "LanguagePesistence";
public static final String LANGUAGE_DEFAULT = Locale.getDefault().getLanguage();
public static final String LANGUAGE = "language";
public LanguagePesistence(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public String getLanguageSelected(){
return pref.getString(LANGUAGE, LANGUAGE_DEFAULT);
}
public void setLanguage(String language){
editor.putString(LANGUAGE, language);
editor.commit();
alterIdioma(language);
}
public void alterIdioma(String languageToLoad){
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
Resources res = this._context.getResources();
res.updateConfiguration(config, res.getDisplayMetrics());
}
}
To set a language
LanguagePesistence lf = new LanguagePesistence(getBaseContext());
lf.setLanguage("eng");
edited: see more here : http://mobgeek.com.br/blog/apps-android-multi-idiomas
values-en
<string name="toast_network">Network not avaliable</string>
<string name="toast_router_fail">Route not created!</string>
<string name="toast_router_create">Wait!</string>
values-pt
<string name="toast_network">Sem conexão com internet</string>
<string name="toast_router_fail">Não foi possivel criar uma rota!</string>
<string name="toast_router_create">Aguarde!</string>
Edited part 2 :
the code below is to change at runtime the language setting if you
have an option to choose a language, so that code propagates to its
application selected language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
Resources res = this._context.getResources();
res.updateConfiguration(config, res.getDisplayMetrics());
taking the language selected in the spinner and changing the system configuration to use this
language.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,int position, long id){
//get language selected example: eng or esp or fr
LanguagePesistence lf = new LanguagePesistence(getBaseContext());
lf.setLanguage("eng");
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
I am trying to use the Twitter API to display tweets of a user, the problem is I got the following error message:
06-28 11:40:58.280: E/AndroidRuntime(3191): FATAL EXCEPTION: main
06-28 11:40:58.280: E/AndroidRuntime(3191): java.lang.IllegalStateException: Authentication credentials are missing. See http://twitter4j.org/en/configuration.html for details
06-28 11:40:58.280: E/AndroidRuntime(3191): at twitter4j.TwitterBaseImpl.ensureAuthorizationEnabled(TwitterBaseImpl.java:201)
06-28 11:40:58.280: E/AndroidRuntime(3191): at twitter4j.TwitterImpl.get(TwitterImpl.java:1941)
06-28 11:40:58.280: E/AndroidRuntime(3191): at twitter4j.TwitterImpl.getRetweets(TwitterImpl.java:209)
06-28 11:40:58.280: E/AndroidRuntime(3191): at com.androidhive.twitterconnect.MainActivity.afficherTweets(MainActivity.java:286)
06-28 11:40:58.280: E/AndroidRuntime(3191): at com.androidhive.twitterconnect.MainActivity.onClick(MainActivity.java:417)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.view.View.performClick(View.java:3620)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.view.View$PerformClick.run(View.java:14292)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.os.Handler.handleCallback(Handler.java:605)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.os.Handler.dispatchMessage(Handler.java:92)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.os.Looper.loop(Looper.java:137)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.app.ActivityThread.main(ActivityThread.java:4507)
06-28 11:40:58.280: E/AndroidRuntime(3191): at java.lang.reflect.Method.invokeNative(Native Method)
06-28 11:40:58.280: E/AndroidRuntime(3191): at java.lang.reflect.Method.invoke(Method.java:511)
06-28 11:40:58.280: E/AndroidRuntime(3191): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
06-28 11:40:58.280: E/AndroidRuntime(3191): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
06-28 11:40:58.280: E/AndroidRuntime(3191): at dalvik.system.NativeStart.main(Native Method)
And this is my code:
I changed them but in vain, this is my hole code:
package com.androidhive.twitterconnect;
import java.util.List;
import com.androidhive.twitterconnect.R;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = "****************************";
static String TWITTER_CONSUMER_SECRET = "***********************************************";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = " 281012441-vTUstoGd5NpWjoviMDS87JxyS4mjj713CfPNCsh2";
static final String PREF_KEY_OAUTH_SECRET = " 4rfd76K1ZUQ0eb3Zss2q6huAZra4TmWnrtj3dPKODectP";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "https://api.twitter.com/oauth/authorize";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "https://api.twitter.com/oauth/access_token";
// Login button
Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
Button btnDisplayTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
btnDisplayTwitter = (Button) findViewById(R.id.button1);
btnDisplayTwitter.setOnClickListener(this);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/** This if conditions is tested once is
* redirected from twitter page. Parse the uri to get oAuth
* Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
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 {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
////////////////////////////////
public void displayTweets() throws TwitterException{
/*
Uri uri = getIntent().getData();
String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);*/
//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);
long userID = accessToken.getUserId();
System.out.println("==> "+userID);
try {
Twitter twitter = new TwitterFactory().getInstance();
//List<Status > statuses = twitter.getRetweets(Long.parseLong(args[0]));
List<Status> statuses = twitter.getRetweets(userID);
for (Status status : statuses) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
System.out.println("done.");
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get retweets: " + te.getMessage());
System.exit(-1);
}
}
///////////////////////////////
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
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;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
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
txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter
* It will just clear the application shared preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == btnDisplayTwitter){
try {
afficherTweets();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
What's wrong?
Authentication credentials are missing.
You're missing credentials somewhere.
From your code, I'd say these :
**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = "****************************";
static String TWITTER_CONSUMER_SECRET = "***********************************************";
plz help me in integrating twitter in my android app account using AsyncTask . I m following androidhive tutorial on integrating twitter account but i am getting Network on main thread exception.
Thanks in advance :D
This is the link of code
http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/
and this is my MainActivity.java
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = ""; // place your cosumer key here
static String TWITTER_CONSUMER_SECRET = ""; // place your consumer secret here
// Preference Constants
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";
// Twitter oauth urls
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";
// Login button
Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/** This if conditions is tested once is
* redirected from twitter page. Parse the uri to get oAuth
* Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
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 {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
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;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
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
txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter
* It will just clear the application shared preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
}
You might got this error most probably in 4.0 device or IF the http conncetion is taking too long to respond.
if you dont know asynctask then simple solution will be
public static boolean isAuthenticated(Context context) {
new Thread() {
#Override
public void run() {
TwitterPrefrences twitterPref = new TwitterPrefrences(context);
String token = twitterPref.getTwitterAuthToken();
String secret = twitterPref.getTwitterAuthTokenSecrate();
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.TWITT_CONSUMER_KEY,Constants.TWITT_CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
twitter.getAccountSettings();
return true;
} catch (TwitterException e) {
return false;
}
}
}.start();
}
I have developed one application.In my application i want to get twitter home timeline data and displaying listview.And i have used twitter4j library.I have searched a lot and also read twitter documentation.In taht documentation getting user timeline data by using the bellow webservice: "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2".It is working fine and data will be displayed.But my requirement is getting home timeline data.In that documentation they given following webservice: https://api.twitter.com/1.1/statuses/home_timeline.json.This is not working and home timeline data wont be displayed.please any one suggest me,how to do this.Thanks in advance
This is my oncreate code:This is my impotrs:
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.dss.utils.UrltoValue;
import com.ibud.adapters.TweetList;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.json.DataObjectFactory;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
And this is my instance variables:
static String TWITTER_CONSUMER_KEY = "CjHtStxCA2toDQY6xnMwg"; // place your cosumer key here
static String TWITTER_CONSUMER_SECRET = "jjhpODDhtl3FM26ETn7yt3Q1Wc7VdxZXequDrmwFg"; // place your consumer secret here
// Preference Constants
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";
// Twitter oauth urls
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";
String username="";
private String strResponse;
private String[] strText;
LinearLayout llTotal;
ListView lvlist;
List<Status> statuses = new ArrayList<Status>();
// Login button
Button btnLoginTwitter,btnLoginFaceBook,btnBack;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
AccessToken accessToken;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnBack = (Button) findViewById(R.id.back);
btnLoginFaceBook = (Button) findViewById(R.id.btnLoginFaceBook);
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
loginToTwitter();
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginFaceBook.setVisibility(View.VISIBLE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
});
btnLoginFaceBook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
Log.e("this is", "facebook onclick");
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message",
Toast.LENGTH_SHORT).show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/**
* This if conditions is tested once is redirected from twitter page.
* Parse the uri to get oAuth Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
accessToken = twitter.getOAuthAccessToken(requestToken,
verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
btnLoginFaceBook.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
Log.e("user id:", "" + userID);
Log.e("user name:", username);
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
Log.e("tryyyyyyyyy:", "try");
// TWITTER ACCESS TOKEN
String twit_access_token = mSharedPreferences
.getString(PREF_KEY_OAUTH_TOKEN, null);
Log.e("access token:", twit_access_token);
// TWITTER ACCESS TOKEN SECRET
String twit_access_token_secret = mSharedPreferences
.getString(PREF_KEY_OAUTH_SECRET, null);
Log.e("access token sec:", twit_access_token_secret);
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
builder.setOAuthAccessToken(twit_access_token);
builder.setOAuthAccessTokenSecret(twit_access_token_secret);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
// builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
AccessToken accessToken = new AccessToken(
twit_access_token, twit_access_token_secret);
Log.e("accesstoken:", "" + accessToken);
Twitter twitter = new TwitterFactory(builder.build())
.getInstance(accessToken);
Log.e("twitter:", "" + twitter);
Paging paging = new Paging(200); // MAX 200 IN ONE CALL.
// SET YOUR OWN
// NUMBER <= 200
statuses = twitter.getHomeTimeline(paging);
Log.e("statuses", "statuses");
try {
Log.e("tryyyyyyyyy in tryyyyyyyyyyyyyy:", "try");
String strInitialDataSet = DataObjectFactory
.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(
strInitialDataSet);
Log.e("lengthhhhhhhhhhhh:", "" + JATweets.length());
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e1) {
// TODO: handle exception
e1.printStackTrace();
}
} catch (Exception e2) {
// TODO: handle exception
}
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username
+ "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
/*
* Intent i = new Intent(this,ShareActivity.class);
* startActivity(i);
*/
}
}
}// oncreate.
private void loginToTwitter() {
// Check if already logged in
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 {
Log.e("clickkkkkkkkkkk:", "authoriseeeeeee");
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
Log.e("elseeeeeeeeeeeee:", "elseeeeeeee");
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
btnLoginTwitter.setVisibility(View.GONE);
btnLoginFaceBook.setVisibility(View.GONE);
// Getting user details from twitter
// For now i am getting his name only
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
accessToken = twitter.getOAuthAccessToken(requestToken,
verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
long userID = accessToken.getUserId();
Log.e("user id:", "" + userID);
User user = twitter.showUser(userID);
String username = user.getName();
Log.e("user name:", username);
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username
+ "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
/*
* Intent i = new Intent(this,ShareActivity.class);
* startActivity(i);
*/
}
}
}// login
And this is the posting tweet:
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
Log.e("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());
Log.e("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
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
txtUpdate.setText("");
}
});
}
}//update.
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginFaceBook.setVisibility(View.VISIBLE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
//Log.e("this is","default back button..............");
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
return false;
}
This is my code.Please help me where i have done mistake and this my xml code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/back"
android:layout_alignParentLeft="true"
android:text="back"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<Button android:id="#+id/btnLoginFaceBook"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login with facebook"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="30dip"/>
<!-- Twitter Login Button -->
<Button android:id="#+id/btnLoginTwitter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login with Twitter"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="30dip"/>
<!-- user name label -->
<TextView android:id="#+id/lblUserName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:layout_marginTop="30dip"/>
<!-- label update status -->
<TextView android:id="#+id/lblUpdate"
android:text="Update Status"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:visibility="gone"/>
<!-- Tweet EditText -->
<EditText android:id="#+id/txtUpdateStatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:visibility="gone"/>
<!-- Tweet Button -->
<Button android:id="#+id/btnUpdateStatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Tweet"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:visibility="gone"/>
<!-- Twitter Logout button -->
<Button android:id="#+id/btnLogoutTwitter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Logout from Twitter"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="50dip"
android:visibility="gone"/>
</LinearLayout>
</LinearLayout>
Use this code. It's production code from an app of mine. I fetch 2 values for Strings TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRET from my strings.xml file. While the values for Strings twit_access_token and twit_access_token_secret are pulled in from my SharedPreferences file. Replace those bits with your own method of storage.
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
// GET THE CONSUMER KEY AND SECRET KEY FROM THE STRINGS XML
String TWITTER_CONSUMER_KEY = getActivity().getString(R.string.TWITTER_CONSUMER_KEY);
String TWITTER_CONSUMER_SECRET = getActivity().getString(R.string.TWITTER_CONSUMER_SECRET);
// TWITTER ACCESS TOKEN
String twit_access_token = twitPrefs.getString(PREF_KEY_OAUTH_TOKEN, null);
// TWITTER ACCESS TOKEN SECRET
String twit_access_token_secret = twitPrefs.getString(PREF_KEY_OAUTH_SECRET, null);
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
builder.setOAuthAccessToken(twit_access_token);
builder.setOAuthAccessTokenSecret(twit_access_token_secret);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
AccessToken accessToken = new AccessToken(twit_access_token, twit_access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
statuses = twitter.getHomeTimeline(paging);
try {
String strInitialDataSet = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strInitialDataSet);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (Exception e) {
// TODO: handle exception
}
NOTE 1: The statuses is an instance of List<Status> statuses = new ArrayList<Status>(); that I have declared and instantiated as a global instance.
NOTE 2: This attribute is necessary builder.setJSONStoreEnabled(true); if you want the result to be in the JSON format. If you need it without JSON, let me know.
FINAL UPDATE:
After testing the OP's entire code and debugging literally everything in a test application, the culprit turns out to be a single line (well, actually, 2):
Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
statuses = twitter.getHomeTimeline(paging);
Turns out, for some reason, the Twitter API does not like the Paging paging = new Paging(200);. Changing that to Paging paging = new Paging(10); strangely enough, gave me 20 tweets. Removing the Paging.... line entirely, gave me 19. Weird result really. But my best guess at this time is that the application is perhaps new on the Twitter developer network (it still shows during authentication that the app cannot access Direct Messages).
Change that part to:
// Paging paging = new Paging(10);
statuses = twitter.getHomeTimeline();
I'm new to android development (and java in general). I'm building an application that requires a user to signup by logging-in to their twitter account from where their basic information is imported and saved. The information required would be birthday, name (full names), username, location, sex, etc.
I'm using twitter4j to accomplish this. I've tried looking at the twitter4j documentation but being an android newbie (and java in general), the documentation is a little bit hard to understand so I seem to be unable to get it to do something other than set a status update.
This is the code in my activity:
package cc.co.localsquare.app;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
public class ConnectTwitterActivity extends BaseActivity {
public final static String CONSUMER_KEY = "valid key";
public final static String CONSUMER_SECRET = "valid secret";
public final static String CALLBACK_URL = "localsquare://ConnectTwitterActivity2";
private CommonsHttpOAuthConsumer commonHttpOAuthConsumer;
private OAuthProvider authProvider;
private Twitter twitter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connect_twitter);
commonHttpOAuthConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
authProvider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token", "http://twitter.com/oauth/authorize");
try {
String oAuthURL = authProvider.retrieveRequestToken(commonHttpOAuthConsumer, CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(oAuthURL)));
} catch (OAuthMessageSignerException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (OAuthCommunicationException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
try {
authProvider.retrieveAccessToken(commonHttpOAuthConsumer, verifier);
AccessToken accessToken = new AccessToken(commonHttpOAuthConsumer.getToken(),
commonHttpOAuthConsumer.getTokenSecret());
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(accessToken);
// Alternate way:
// twitter = new TwitterFactory().getOAuthAuthorizedInstance(CONSUMER_KEY, CONSUMER_SECRET,
// new AccessToken(commonHttpOAuthConsumer.getToken(), commonHttpOAuthConsumer.getTokenSecret()));
// Tweet message to be updated.
String tweet = "Hi there, This was sent from my application - OAuth, Twitter";
twitter.updateStatus(tweet);
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG);
}
}
}
}
How EXACTLY can I solve my problem?
If you have the screen name of the twitter user for whom you need to get the details, then you can use User user = twitter.showUser(screenName);.Now you can access the information about the user by using getter functions on the object user, e.g. user.getName(), user.getLocation() etc.
Remember to import the User class in Eclipse. Generally you can also do it by pressing Ctrl+Shift+O in Eclipse.
Get the twitter object from the session once the login in complete. That can be used in the following way to extract the name
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
long userID = twitter.getId();
twitter4j.User newUser=twitter.showUser(twitter.getScreenName());
String name=newUser.getName();
You can explore several methods from User class to get different attributes of user like profile image, friendlistlength etc
#Vineet Bhatia
Use twitter.showUser() method to get user details. To get user's name do user.getName() Remember javadoc is your friend.