need to use to call when click on twitter button
import yourpackagename.TwitterApp.TwDialogListener;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.Button;
public class TestPost extends Activity {
private TwitterApp mTwitter;
private CheckBox mTwitterBtn;
private String username = "";
private boolean postToTwitter = false;
Button postBtn;
EditText reviewEdit;
String review;
public String title1,desc1,imagurl1,fburl1;
private static final String twitter_consumer_key = "your consumer key";
private static final String twitter_secret_key = "consumer secret";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post);
Bundle b=new Bundle();
b=this.getIntent().getExtras();
title1=b.getString("title");
desc1=b.getString("desc");
fburl1=b.getString("fb_url");
Button back=(Button)findViewById(R.id.back);
back.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}});
postBtn = (Button) findViewById(R.id.button1);
postBtn.setGravity(Gravity.CENTER_HORIZONTAL);
reviewEdit = (EditText) findViewById(R.id.revieew);
postBtn.setVisibility(View.GONE);
review="";
reviewEdit.setVisibility(View.GONE);
/* reviewEdit.setFilters(new InputFilter[] {
new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend) {
// TODO Auto-generated method stub
return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
}
}
});*/
postBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
review = reviewEdit.getText().toString();
if (review.equals(""))
return;
else{
mTwitterBtn.setChecked(true);
//mTwitterBtn.setVisibility(View.INVISIBLE);
postToTwitter=true;
}
//postReview(review);
System.out.println("++"+postToTwitter);
if (postToTwitter) postToTwitter(review);
}
});
mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
mTwitter.setListener(mTwLoginDialogListener);
mTwitterBtn = (CheckBox) findViewById(R.id.twitterCheck);
mTwitterBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mTwitter.hasAccessToken()) {
postToTwitter = mTwitterBtn.isChecked();
postBtn.setVisibility(View.GONE);
reviewEdit.setText("Check out this deal from on"+"\n"+"http://"+fburl1);
} else {
mTwitterBtn.setChecked(false);
mTwitter.authorize();
}
}
});
if (mTwitter.hasAccessToken()) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
postBtn.setVisibility(View.VISIBLE);
reviewEdit.setText("Check out this deal from on "+"\n"+"http://"+fburl1);
mTwitterBtn.setVisibility(View.GONE);
reviewEdit.setVisibility(View.VISIBLE);
//mTwitterBtn.setText(" Twitter (" + username + ")");
}
}
private void postReview(String review) {
//post to server
Toast.makeText(this, "Review posted", Toast.LENGTH_SHORT).show();
}
private void postToTwitter(final String review) {
new Thread() {
@Override
public void run() {
int what = 0;
try {
mTwitter.updateStatus(review);
} catch (Exception e) {
what = 1;
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String text = (msg.what == 0) ? "Blitz posted successfully..." : "Tweet has been already posted...";
Toast.makeText(TestPost.this, text, Toast.LENGTH_SHORT).show();
}
};
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
@Override
public void onComplete(String value) {
reviewEdit.setVisibility(View.VISIBLE);
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
postBtn.setVisibility(View.GONE);
mTwitterBtn.setText(" (" + username + ")");
reviewEdit.setText("Check out this deal from on !"+"\n"+"http://"+fburl1);
postBtn.setVisibility(View.VISIBLE);
mTwitterBtn.setChecked(true);
postToTwitter = true;
Toast.makeText(TestPost.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
}
@Override
public void onError(String value) {
mTwitterBtn.setChecked(false);
Toast.makeText(TestPost.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
}
};
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
///////////////////////////
/**
* @author Lorensius W. L. T <lorenz@londatiga.net>
*
* Website: http://www.londatiga.net
*/
package blizit.app;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import twitter4j.User;
import android.os.Handler;
import android.os.Message;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.Window;
import java.net.URL;
public class TwitterApp {
private Twitter mTwitter;
private TwitterSession mSession;
private AccessToken mAccessToken;
private CommonsHttpOAuthConsumer mHttpOauthConsumer;
private OAuthProvider mHttpOauthprovider;
private String mConsumerKey;
private String mSecretKey;
private ProgressDialog mProgressDlg;
private TwDialogListener mListener;
private Context context;
public static final String CALLBACK_URL = "twitterapp://connect";
private static final String TAG = "TwitterApp";
public TwitterApp(Context context, String consumerKey, String secretKey) {
this.context = context;
mTwitter = new TwitterFactory().getInstance();
mSession = new TwitterSession(context);
mProgressDlg = new ProgressDialog(context);
mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
mConsumerKey = consumerKey;
mSecretKey = secretKey;
mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);
mHttpOauthprovider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token",
"http://twitter.com/oauth/authorize");
mAccessToken = mSession.getAccessToken();
configureToken();
}
public void setListener(TwDialogListener listener) {
mListener = listener;
}
@SuppressWarnings("deprecation")
private void configureToken() {
if (mAccessToken != null) {
mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
mTwitter.setOAuthAccessToken(mAccessToken);
}
}
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public String getUsername() {
return mSession.getUsername();
}
public void updateStatus(String status) throws Exception {
try {
mTwitter.updateStatus(status);
} catch (TwitterException e) {
throw e;
}
}
public void authorize() {
mProgressDlg.setMessage("Initializing ...");
mProgressDlg.show();
new Thread() {
@Override
public void run() {
String authUrl = "";
int what = 1;
try {
authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);
what = 0;
Log.d(TAG, "Request token url " + authUrl);
} catch (Exception e) {
Log.d(TAG, "Failed to get request token");
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
}
}.start();
}
public void processToken(String callbackUrl) {
mProgressDlg.setMessage("Finalizing ...");
mProgressDlg.show();
final String verifier = getVerifier(callbackUrl);
new Thread() {
@Override
public void run() {
int what = 1;
try {
mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier);
mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret());
configureToken();
User user = mTwitter.verifyCredentials();
mSession.storeAccessToken(mAccessToken, user.getName());
what = 0;
} catch (Exception e){
Log.d(TAG, "Error getting access token");
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private String getVerifier(String callbackUrl) {
String verifier = "";
try {
callbackUrl = callbackUrl.replace("twitterapp", "http");
URL url = new URL(callbackUrl);
String query = url.getQuery();
String array[] = query.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
verifier = URLDecoder.decode(v[1]);
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return verifier;
}
private void showLoginDialog(String url) {
final TwDialogListener listener = new TwDialogListener() {
@Override
public void onComplete(String value) {
processToken(value);
}
@Override
public void onError(String value) {
mListener.onError("Failed opening authorization page");
}
};
new TwitterDialog(context, url, listener).show();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mProgressDlg.dismiss();
if (msg.what == 1) {
if (msg.arg1 == 1)
mListener.onError("Error getting request token");
else
mListener.onError("Error getting access token");
} else {
if (msg.arg1 == 1)
showLoginDialog((String) msg.obj);
else
mListener.onComplete("");
}
}
};
public interface TwDialogListener {
public void onComplete(String value);
public void onError(String value);
}
}
/////////////////
package blizit.app;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.content.Context;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import blizit.app.TwitterApp.TwDialogListener;
public class TwitterDialog extends Dialog {
static final float[] DIMENSIONS_LANDSCAPE = {460, 260};
static final float[] DIMENSIONS_PORTRAIT = {280, 420};
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
private String mUrl;
private TwDialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
private static final String TAG = "Twitter-WebView";
public TwitterDialog(Context context, String url, TwDialogListener listener) {
super(context);
mUrl = url;
mListener = listener;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT : DIMENSIONS_LANDSCAPE;
addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
(int) (dimensions[1] * scale + 0.5f)));
}
private void setUpTitle() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
Drawable icon = getContext().getResources().getDrawable(R.drawable.twitter_icon);
mTitle = new TextView(getContext());
mTitle.setText("Twitter");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(0xFFbbd7e9);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
mContent.addView(mTitle);
}
private void setUpWebView() {
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new TwitterWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class TwitterWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "Redirecting URL " + url);
if (url.startsWith(TwitterApp.CALLBACK_URL)) {
mListener.onComplete(url);
TwitterDialog.this.dismiss();
return true;
} else if (url.startsWith("authorize")) {
return false;
}
return true;
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d(TAG, "Page error: " + description);
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(description);
TwitterDialog.this.dismiss();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(TAG, "Loading URL: " + url);
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
mSpinner.dismiss();
}
}
}
//////////////////
package blizit.app;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.Context;
import twitter4j.http.AccessToken;
public class TwitterSession {
private SharedPreferences sharedPref;
private Editor editor;
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
private static final String TWEET_USER_NAME = "user_name";
private static final String SHARED = "Twitter_Preferences";
public TwitterSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(AccessToken accessToken, String username) {
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
editor.putString(TWEET_USER_NAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(TWEET_AUTH_KEY, null);
editor.putString(TWEET_AUTH_SECRET_KEY, null);
editor.putString(TWEET_USER_NAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(TWEET_USER_NAME, "");
}
public AccessToken getAccessToken() {
String token = sharedPref.getString(TWEET_AUTH_KEY, null);
String tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);
if (token != null && tokenSecret != null)
return new AccessToken(token, tokenSecret);
else
return null;
}
}
/////////////
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background">
<LinearLayout android:name="LinearLayout" android:layout_width="fill_parent"
android:background="@drawable/navigation_bar" android:layout_height="wrap_content" android:id="@+id/linear1">
<Button android:layout_height="wrap_content" android:id="@+id/back" android:background="@layout/backselector" android:layout_width="wrap_content" android:textStyle="bold" android:textSize="16dip" android:layout_marginLeft="5dip" android:textColor="#ffffff" android:layout_gravity="center_vertical"></Button>
</LinearLayout>
<EditText
android:id="@+id/revieew"
android:layout_marginTop="15dp"
android:layout_width="250dp"
android:layout_height="90dip" android:layout_gravity="center_horizontal"/>
<CheckBox
android:id="@+id/twitterCheck"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="14sp"
android:clickable="true"
android:focusable="true"
android:button="@drawable/twitter_check" android:layout_width="fill_parent" android:layout_marginLeft="15dip" android:layout_gravity="center_horizontal" android:text="bbbb"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:text="Tweet" android:layout_height="45dip" android:background="@drawable/button_blue" android:textStyle="bold" android:textColor="#ffffff" android:layout_marginTop="25dip" android:paddingTop="5dip" android:layout_marginLeft="40dip"/>
<ImageView android:id="@+id/imageView1" android:layout_marginTop="20dip" android:background="@drawable/twitter1" android:layout_height="100dip" android:layout_width="120dip" android:layout_marginLeft="40dip"></ImageView>
</LinearLayout>
TestPost.java
package your package name;import yourpackagename.TwitterApp.TwDialogListener;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.Button;
public class TestPost extends Activity {
private TwitterApp mTwitter;
private CheckBox mTwitterBtn;
private String username = "";
private boolean postToTwitter = false;
Button postBtn;
EditText reviewEdit;
String review;
public String title1,desc1,imagurl1,fburl1;
private static final String twitter_consumer_key = "your consumer key";
private static final String twitter_secret_key = "consumer secret";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post);
Bundle b=new Bundle();
b=this.getIntent().getExtras();
title1=b.getString("title");
desc1=b.getString("desc");
fburl1=b.getString("fb_url");
Button back=(Button)findViewById(R.id.back);
back.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}});
postBtn = (Button) findViewById(R.id.button1);
postBtn.setGravity(Gravity.CENTER_HORIZONTAL);
reviewEdit = (EditText) findViewById(R.id.revieew);
postBtn.setVisibility(View.GONE);
review="";
reviewEdit.setVisibility(View.GONE);
/* reviewEdit.setFilters(new InputFilter[] {
new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend) {
// TODO Auto-generated method stub
return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
}
}
});*/
postBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
review = reviewEdit.getText().toString();
if (review.equals(""))
return;
else{
mTwitterBtn.setChecked(true);
//mTwitterBtn.setVisibility(View.INVISIBLE);
postToTwitter=true;
}
//postReview(review);
System.out.println("++"+postToTwitter);
if (postToTwitter) postToTwitter(review);
}
});
mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
mTwitter.setListener(mTwLoginDialogListener);
mTwitterBtn = (CheckBox) findViewById(R.id.twitterCheck);
mTwitterBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mTwitter.hasAccessToken()) {
postToTwitter = mTwitterBtn.isChecked();
postBtn.setVisibility(View.GONE);
reviewEdit.setText("Check out this deal from on"+"\n"+"http://"+fburl1);
} else {
mTwitterBtn.setChecked(false);
mTwitter.authorize();
}
}
});
if (mTwitter.hasAccessToken()) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
postBtn.setVisibility(View.VISIBLE);
reviewEdit.setText("Check out this deal from on "+"\n"+"http://"+fburl1);
mTwitterBtn.setVisibility(View.GONE);
reviewEdit.setVisibility(View.VISIBLE);
//mTwitterBtn.setText(" Twitter (" + username + ")");
}
}
private void postReview(String review) {
//post to server
Toast.makeText(this, "Review posted", Toast.LENGTH_SHORT).show();
}
private void postToTwitter(final String review) {
new Thread() {
@Override
public void run() {
int what = 0;
try {
mTwitter.updateStatus(review);
} catch (Exception e) {
what = 1;
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String text = (msg.what == 0) ? "Blitz posted successfully..." : "Tweet has been already posted...";
Toast.makeText(TestPost.this, text, Toast.LENGTH_SHORT).show();
}
};
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
@Override
public void onComplete(String value) {
reviewEdit.setVisibility(View.VISIBLE);
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
postBtn.setVisibility(View.GONE);
mTwitterBtn.setText(" (" + username + ")");
reviewEdit.setText("Check out this deal from on !"+"\n"+"http://"+fburl1);
postBtn.setVisibility(View.VISIBLE);
mTwitterBtn.setChecked(true);
postToTwitter = true;
Toast.makeText(TestPost.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
}
@Override
public void onError(String value) {
mTwitterBtn.setChecked(false);
Toast.makeText(TestPost.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
}
};
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
///////////////////////////
TwitterApp.java
/**
* @author Lorensius W. L. T <lorenz@londatiga.net>
*
* Website: http://www.londatiga.net
*/
package blizit.app;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import twitter4j.User;
import android.os.Handler;
import android.os.Message;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.Window;
import java.net.URL;
public class TwitterApp {
private Twitter mTwitter;
private TwitterSession mSession;
private AccessToken mAccessToken;
private CommonsHttpOAuthConsumer mHttpOauthConsumer;
private OAuthProvider mHttpOauthprovider;
private String mConsumerKey;
private String mSecretKey;
private ProgressDialog mProgressDlg;
private TwDialogListener mListener;
private Context context;
public static final String CALLBACK_URL = "twitterapp://connect";
private static final String TAG = "TwitterApp";
public TwitterApp(Context context, String consumerKey, String secretKey) {
this.context = context;
mTwitter = new TwitterFactory().getInstance();
mSession = new TwitterSession(context);
mProgressDlg = new ProgressDialog(context);
mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
mConsumerKey = consumerKey;
mSecretKey = secretKey;
mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);
mHttpOauthprovider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token",
"http://twitter.com/oauth/authorize");
mAccessToken = mSession.getAccessToken();
configureToken();
}
public void setListener(TwDialogListener listener) {
mListener = listener;
}
@SuppressWarnings("deprecation")
private void configureToken() {
if (mAccessToken != null) {
mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
mTwitter.setOAuthAccessToken(mAccessToken);
}
}
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public String getUsername() {
return mSession.getUsername();
}
public void updateStatus(String status) throws Exception {
try {
mTwitter.updateStatus(status);
} catch (TwitterException e) {
throw e;
}
}
public void authorize() {
mProgressDlg.setMessage("Initializing ...");
mProgressDlg.show();
new Thread() {
@Override
public void run() {
String authUrl = "";
int what = 1;
try {
authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);
what = 0;
Log.d(TAG, "Request token url " + authUrl);
} catch (Exception e) {
Log.d(TAG, "Failed to get request token");
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
}
}.start();
}
public void processToken(String callbackUrl) {
mProgressDlg.setMessage("Finalizing ...");
mProgressDlg.show();
final String verifier = getVerifier(callbackUrl);
new Thread() {
@Override
public void run() {
int what = 1;
try {
mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier);
mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret());
configureToken();
User user = mTwitter.verifyCredentials();
mSession.storeAccessToken(mAccessToken, user.getName());
what = 0;
} catch (Exception e){
Log.d(TAG, "Error getting access token");
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private String getVerifier(String callbackUrl) {
String verifier = "";
try {
callbackUrl = callbackUrl.replace("twitterapp", "http");
URL url = new URL(callbackUrl);
String query = url.getQuery();
String array[] = query.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
verifier = URLDecoder.decode(v[1]);
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return verifier;
}
private void showLoginDialog(String url) {
final TwDialogListener listener = new TwDialogListener() {
@Override
public void onComplete(String value) {
processToken(value);
}
@Override
public void onError(String value) {
mListener.onError("Failed opening authorization page");
}
};
new TwitterDialog(context, url, listener).show();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mProgressDlg.dismiss();
if (msg.what == 1) {
if (msg.arg1 == 1)
mListener.onError("Error getting request token");
else
mListener.onError("Error getting access token");
} else {
if (msg.arg1 == 1)
showLoginDialog((String) msg.obj);
else
mListener.onComplete("");
}
}
};
public interface TwDialogListener {
public void onComplete(String value);
public void onError(String value);
}
}
/////////////////
TwitterDialog.java
package blizit.app;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.content.Context;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import blizit.app.TwitterApp.TwDialogListener;
public class TwitterDialog extends Dialog {
static final float[] DIMENSIONS_LANDSCAPE = {460, 260};
static final float[] DIMENSIONS_PORTRAIT = {280, 420};
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
private String mUrl;
private TwDialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
private static final String TAG = "Twitter-WebView";
public TwitterDialog(Context context, String url, TwDialogListener listener) {
super(context);
mUrl = url;
mListener = listener;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT : DIMENSIONS_LANDSCAPE;
addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
(int) (dimensions[1] * scale + 0.5f)));
}
private void setUpTitle() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
Drawable icon = getContext().getResources().getDrawable(R.drawable.twitter_icon);
mTitle = new TextView(getContext());
mTitle.setText("Twitter");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(0xFFbbd7e9);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
mContent.addView(mTitle);
}
private void setUpWebView() {
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new TwitterWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class TwitterWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "Redirecting URL " + url);
if (url.startsWith(TwitterApp.CALLBACK_URL)) {
mListener.onComplete(url);
TwitterDialog.this.dismiss();
return true;
} else if (url.startsWith("authorize")) {
return false;
}
return true;
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d(TAG, "Page error: " + description);
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(description);
TwitterDialog.this.dismiss();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(TAG, "Loading URL: " + url);
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
mSpinner.dismiss();
}
}
}
//////////////////
TwitterSession.java
package blizit.app;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.Context;
import twitter4j.http.AccessToken;
public class TwitterSession {
private SharedPreferences sharedPref;
private Editor editor;
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
private static final String TWEET_USER_NAME = "user_name";
private static final String SHARED = "Twitter_Preferences";
public TwitterSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(AccessToken accessToken, String username) {
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
editor.putString(TWEET_USER_NAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(TWEET_AUTH_KEY, null);
editor.putString(TWEET_AUTH_SECRET_KEY, null);
editor.putString(TWEET_USER_NAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(TWEET_USER_NAME, "");
}
public AccessToken getAccessToken() {
String token = sharedPref.getString(TWEET_AUTH_KEY, null);
String tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);
if (token != null && tokenSecret != null)
return new AccessToken(token, tokenSecret);
else
return null;
}
}
/////////////
post.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background">
<LinearLayout android:name="LinearLayout" android:layout_width="fill_parent"
android:background="@drawable/navigation_bar" android:layout_height="wrap_content" android:id="@+id/linear1">
<Button android:layout_height="wrap_content" android:id="@+id/back" android:background="@layout/backselector" android:layout_width="wrap_content" android:textStyle="bold" android:textSize="16dip" android:layout_marginLeft="5dip" android:textColor="#ffffff" android:layout_gravity="center_vertical"></Button>
</LinearLayout>
<EditText
android:id="@+id/revieew"
android:layout_marginTop="15dp"
android:layout_width="250dp"
android:layout_height="90dip" android:layout_gravity="center_horizontal"/>
<CheckBox
android:id="@+id/twitterCheck"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="14sp"
android:clickable="true"
android:focusable="true"
android:button="@drawable/twitter_check" android:layout_width="fill_parent" android:layout_marginLeft="15dip" android:layout_gravity="center_horizontal" android:text="bbbb"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:text="Tweet" android:layout_height="45dip" android:background="@drawable/button_blue" android:textStyle="bold" android:textColor="#ffffff" android:layout_marginTop="25dip" android:paddingTop="5dip" android:layout_marginLeft="40dip"/>
<ImageView android:id="@+id/imageView1" android:layout_marginTop="20dip" android:background="@drawable/twitter1" android:layout_height="100dip" android:layout_width="120dip" android:layout_marginLeft="40dip"></ImageView>
</LinearLayout>