Twitter recently released an update allowing users to attach up to four images to a tweet. I was wondering how to implement this in an Android application.
I've found a post that was made BEFORE Twitter released the update called "Posting multiple photos in a single tweet" (I'm not showing the link because I'm only allowed to show two links with less than 10 reputation).
Now, here is the Twitter API documentation describing how to attach multiple images to a tweet, the only problem is that I have no idea how to implement this in Android:
https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media
So I was thinking of two possible solutions - either modify one of these methods from the Twitter4j library( https://github.com/yusuke/twitter4j/tree/master/twitter4j-media-support/src/main/java/twitter4j/media) to allow for multiple image attachments OR directly implement the Twitter API documentation.
Any ideas how to do this?
Input is greatly appreciated!
I have shared the multiple images on Twitter in android using twitter4j library,it is working fine to share multiple and single image on twitter
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.UploadedMedia;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
public class SharingActivity extends AppCompatActivity implements View.OnClickListener {
private static final String PREF_NAME = "sample_twitter_pref";
private static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
private static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
private static final String PREF_KEY_TWITTER_LOGIN = "is_twitter_loggedin";
private static final String PREF_USER_NAME = "twitter_user_name";
private static final int WEBVIEW_REQUEST_CODE = 223;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private String consumerKey = null;
private String consumerSecret = null;
private String callbackUrl = null;
private String oAuthVerifier = null;
ImageView loginLayout,shareLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initTwitterConfigs();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
findViewById(R.id.twitBtnId).setOnClickListener(this);
findViewById(R.id.btn_share).setOnClickListener(this);
mSharedPreferences = getSharedPreferences(PREF_NAME, 0);
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (isLoggedIn) {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
} else {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
}
}
private void saveTwitterInfo(AccessToken accessToken) {
long userID = accessToken.getUserId();
User user;
try {
user = twitter.showUser(userID);
String username = user.getName();
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.putString(PREF_USER_NAME, username);
e.commit();
} catch (TwitterException e1) {
e1.printStackTrace();
}
}
private void initTwitterConfigs() {
consumerKey = getString(R.string.twitter_consumer_key);
consumerSecret = getString(R.string.twitter_consumer_secret);
callbackUrl = getString(R.string.twitter_callback);
oAuthVerifier = getString(R.string.twitter_oauth_verifier);
}
private void loginToTwitter() {
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (!isLoggedIn) {
final ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
final Configuration configuration = builder.build();
final TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(callbackUrl);
final Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra(WebViewActivity.EXTRA_URL, requestToken.getAuthenticationURL());
startActivityForResult(intent, WEBVIEW_REQUEST_CODE);
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
if (responseCode == Activity.RESULT_OK) {
String verifier = data.getExtras().getString(oAuthVerifier);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
saveTwitterInfo(accessToken);
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.e("Twitter Login Failed", e.getMessage());
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.twitBtnId:
loginToTwitter();
break;
case R.id.btn_share:
new ShareImage().execute();
break;
}
}
public class ShareImage extends AsyncTask<Void,Void,String>{
#Override
protected void onPreExecute() {
//show progress here
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
return uploadMultipleImages();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//hide progress here
Toast.makeText(SharingActivity.this,""+result,Toast.LENGTH_LONG).show();
}
}
public String uploadMultipleImages() {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
try {
Bitmap bmp[] = {BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1),
BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view2),
BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view3),
BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view4),
BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view5)};
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
File folder = new File(dir);
if (!folder.exists())
folder.mkdirs();
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
long[] mediaIds = new long[4];
for (int i=0; i<4; i++) {
File tempFile = new File(dir,"image_file"+(i));
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
boolean isCompres = bmp[i].compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
if (isCompres) {
UploadedMedia media = twitter.uploadMedia(tempFile);
mediaIds[i] = media.getMediaId();
tempFile.deleteOnExit();
}
}
StatusUpdate update = new StatusUpdate("test_name0");
update.setMediaIds(mediaIds);
Status status = twitter.updateStatus(update);
return "Successfully uploaded";
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to update status: " + te.getMessage());
}
} catch (Exception e){
e.printStackTrace();
}
return "not uloaded";
}
public String uploadSingleImage() {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
try {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1);
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
File folder = new File(dir);
if (!folder.exists())
folder.mkdirs();
File tempFile = new File(dir,"image_file"+(i));
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
boolean isCompres = bmp.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate update = new StatusUpdate("test_name0");
update.setMedia(tempFile);
Status status = twitter.updateStatus(update);
return "Successfully uploaded";
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to update status: " + te.getMessage());
}
} catch (Exception e){
e.printStackTrace();
}
return "not uloaded";
}
}
public class WebViewActivity extends Activity {
private WebView webView;
public static String EXTRA_URL = "extra_url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
final String url = this.getIntent().getStringExtra(EXTRA_URL);
if (null == url) {
finish();
}
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(url);
}
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
String verifier = uri.getQueryParameter(getString(R.string.twitter_oauth_verifier));
Intent resultIntent = new Intent();
resultIntent.putExtra(getString(R.string.twitter_oauth_verifier), verifier);
setResult(RESULT_OK, resultIntent);
finish();
return true;
}
}
}
for running above code please download the below library and put it in your app libs folder and add it as dependency in gradle file
(1)twitter4j-core-4.0.4.jar
(2)twitter4j-media-support-4.0.4.jar
(3)twitter4j-stream-4.0.4.jar
(4)signpost-commonshttp4-1.2.1.1.jar
(5)signpost-core-1.2.1.1.jar
(6)signpost-jetty6-1.2.1.1.jar
It is working fine, hope it will help for you also
Related
I have a problem with my Android app when I try to login with Twitter. When I login and Twitter has given permission to my account to access, it shows the next message:
"Wait a moment!
The request form's token for this page isnt being valid. Is possible that it had was used or be expired because is a few old. Please, back to the site or aplicattion which sent to here an try again, probably it only was an error."
This is my code:
AlertManager:
package com.fsvp.manocio;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class AlertManager {
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Connection Manager:
package com.fsvp.manocio;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionManager {
private Context _context;
public ConnectionManager(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
Activity Main:
package com.fsvp.manocio;
import com.fsvp.manocio.AlertManager;
import com.fsvp.manocio.ConnectionManager;
import com.fsvp.manocio.MainActivity;
import com.fsvp.manocio.R;
import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;
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.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.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
static String TWITTER_CONSUMER_KEY = "****";
static String TWITTER_CONSUMER_SECRET = "*****";
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_ACCESS_TOKEN = "*****";
static final String PREF_KEY_ACCESS_SECRET = "*****";
static final String PREF_KEY_USER_NAME = "user_name";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "https://api.twitter.com/oauth/authenticate?oauth_token=*****";
static final String URL_TWITTER_AUTH = "https://api.twitter.com/oauth/authorize";
static final String URL_TWITTER_OAUTH_VERIFIER = "https://api.twitter.com/oauth/access_token";
static final String URL_TWITTER_OAUTH_TOKEN = "https://api.twitter.com/oauth/request_token";
Button loginTwitter;
Button logoutTwitter;
TextView userName;
ImageView twitterLogo;
ProgressDialog pDialog;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private ConnectionManager cm;
AlertManager alert = new AlertManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cm = new ConnectionManager(getApplicationContext());
if (!cm.isConnectingToInternet()) {
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
return;
}
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
return;
}
loginTwitter = (Button) findViewById(R.id.loginTwitter);
twitterLogo = (ImageView) findViewById(R.id.twitterLogo);
logoutTwitter = (Button) findViewById(R.id.logoutTwitter);
userName = (TextView) findViewById(R.id.userName);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
loginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
new TwitterLogin().execute();
}
});
logoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
logoutFromTwitter();
}
});
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
new TwitterAccessToken().execute(verifier);
}
}else {
String userName = mSharedPreferences.getString(PREF_KEY_USER_NAME, "");
enableTwitterStatus(userName);
}
}
private class TwitterLogin extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... 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);
MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (isTwitterLoggedInAlready()) {
Toast.makeText(MainActivity.this, "Already Logged into Twitter", Toast.LENGTH_LONG).show();
}
}
}
private class TwitterAccessToken extends AsyncTask<String, Void, User> {
#Override
protected User doInBackground(String... params) {
String verifier = params[0];
AccessToken accessToken = null;
User user = null;
try {
accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_ACCESS_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_ACCESS_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
Log.d(TAG, "Twitter OAuth Token: " + accessToken.getToken());
long userID = accessToken.getUserId();
user = twitter.showUser(userID);
e.putString(PREF_KEY_USER_NAME, user.getName());
e.commit();
} catch (TwitterException e) {
Log.e(TAG, "Twitter Login Error: " + e.getMessage());
e.printStackTrace();
}
return user;
}
#Override
protected void onPostExecute(User user) {
super.onPostExecute(user);
if (user != null) {
enableTwitterStatus(user.getName());
}
}
}
private void enableTwitterStatus(String user) {
// Hide login button
loginTwitter.setVisibility(View.GONE);
logoutTwitter.setVisibility(View.VISIBLE);
twitterLogo.setVisibility(View.GONE);
userName.setText(Html.fromHtml("<b>Welcome " + userName + "</b>"));
userName.setVisibility(View.GONE);
}
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_ACCESS_TOKEN);
e.remove(PREF_KEY_ACCESS_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
logoutTwitter.setVisibility(View.GONE);
userName.setText("");
userName.setVisibility(View.GONE);
loginTwitter.setVisibility(View.VISIBLE);
twitterLogo.setVisibility(View.VISIBLE);
}
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
}
Finally, this is my manifest:
Anyone knows a solution?
Thanks and cheers!
I'm trying to make a Twitter app which includes posting and retrieving tweets from the user's timeline and setting it in a list view which also updates when someone tweets.
I also wish to allow the user to upload photos to Twitter.
Here's my code:
package com.example.listtweetdemo;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Paging;
import twitter4j.ResponseList;
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.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONObject;
import twitter4j.json.DataObjectFactory;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private Button twitt;
private Button read;
private Button login;
private Button logout;
private EditText edt;
private boolean man = true;
private TextView textName;
private ListView list;
List<Status> statuses = new ArrayList<Status>();
static final String consumerKey = "RVVVPnAUa8e1XXXXXXXXX";
static final String consumerSecretKey = "eCh0Bb12n9oDmcomBdfisKZIfJmChC2XXXXXXXXXXXX";
static final String prefName = "twitter_oauth";
static final String prefKeyOauthToken = "oauth_token";
static final String prefKeyOauthSecret = "oauth_token_secret";
static final String prefKeyTwitterLogin = "isTwitterLogedIn";
static final String twitterCallbackUrl = "oauth://t4jsample";
static final String urlTwitterOauth = "auth_url";
static final String urlTwitterVerify = "oauth_verifier";
static final String urlTwitterToken = "oauth_token";
static SharedPreferences pref;
private static Twitter twitter;
private static RequestToken reqToken;
private connectionDetector cd;
AlertDailogManager alert = new AlertDailogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpIds();
cd = new connectionDetector(getApplicationContext());
if(!cd.isConnectivityToInternet())
{
alert.showAlert(MainActivity.this, "Internet Connection Error", "Please Connect to working Internet connection", false);
return;
}
if(consumerKey.trim().length() == 0 || consumerSecretKey.trim().length() == 0)
{
alert.showAlert(MainActivity.this, "Twitter Oauth Token", "Please set your Twitter oauth token first!", false);
return;
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToTwitter();
}
});
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
logoutFromTwitter();
}
});
read.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
try {
statuses = twitter.getHomeTimeline();
} catch (TwitterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
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
}
/*try {
ResponseList<Status> statii = twitter.getHomeTimeline();
statusListAdapter adapter = new statusListAdapter(getApplicationContext(), statii);
setListAdapter(adapter);
Log.d("HOME TIMELINE", statii.toString());
} catch (TwitterException e) {
e.printStackTrace();
}
//list.setVisibility(View.VISIBLE);
read.setVisibility(View.GONE);*/
}
});
twitt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String status = edt.getText().toString();
if(status.trim().length() > 0)
{
new updateTwitter().execute(status);
}
}
});
if(!isTwitterLogedInAlready())
{
Uri uri = getIntent().getData();
if(uri != null && uri.toString().startsWith(twitterCallbackUrl))
{
String verify = uri.getQueryParameter(urlTwitterVerify);
try
{
AccessToken accessToken = twitter.getOAuthAccessToken(reqToken,verify);
Editor edit = pref.edit();
edit.putString(prefKeyOauthToken, accessToken.getToken());
edit.putString(prefKeyOauthSecret, accessToken.getTokenSecret());
edit.putBoolean(prefKeyTwitterLogin, true);
edit.commit();
Log.d("Twitter oauth Token", ">" + accessToken.getToken());
login.setVisibility(View.INVISIBLE);
twitt.setVisibility(View.VISIBLE);
edt.setVisibility(View.VISIBLE);
read.setVisibility(View.VISIBLE);
textName.setVisibility(View.VISIBLE);
if(man == true)
{
logout.setVisibility(View.VISIBLE);
}
long userId = accessToken.getUserId();
User user = twitter.showUser(userId);
//User user = twitter.getHomeTimeline();
Status n = user.getStatus();
String userName = user.getName();
textName.setText(userName);
}
catch(Exception e)
{
Log.d("Twitter Login Error", ">" + e.getMessage());
}
}
}
}
private void setUpIds() {
twitt = (Button)findViewById(R.id.buttTwitt);
login = (Button)findViewById(R.id.buttLogin);
read = (Button)findViewById(R.id.buttRead);
edt = (EditText)findViewById(R.id.editText1);
logout = (Button)findViewById(R.id.buttLogout);
textName = (TextView)findViewById(R.id.textName);
//list = (ListView)findViewById(R.id.listView1);
pref = getApplicationContext().getSharedPreferences("myPref", 0);
}
protected void logoutFromTwitter() {
Editor e = pref.edit();
e.remove(prefKeyOauthSecret);
e.remove(prefKeyOauthToken);
e.remove(prefKeyTwitterLogin);
e.commit();
login.setVisibility(View.VISIBLE);
logout.setVisibility(View.GONE);
twitt.setVisibility(View.GONE);
edt.setVisibility(View.GONE);
read.setVisibility(View.GONE);
textName.setVisibility(View.GONE);
}
protected void loginToTwitter() {
if(!isTwitterLogedInAlready())
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
twitter = factory.getInstance();
try{
reqToken = twitter.getOAuthRequestToken(twitterCallbackUrl);
this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(reqToken.getAuthenticationURL())));
}
catch(TwitterException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
logout.setVisibility(View.VISIBLE);
man = false;
}
}
private boolean isTwitterLogedInAlready() {
return pref.getBoolean(prefKeyTwitterLogin, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class updateTwitter extends AsyncTask<String , String, String>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to Twitter status..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
// Access Token
String access_token = pref.getString(prefKeyOauthToken, "");
// Access Token Secret
String access_token_secret = pref.getString(prefKeyOauthSecret, "");
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;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Status update successfully", Toast.LENGTH_SHORT).show();
edt.setText("");
}
});
}
}
}
Use the new Twitter Fabric SDK for Android. Requires sign up first. If you don't want to wait to be approved for the sign up, then I recommend using the following link
https://github.com/Rockncoder/TwitterTutorial
The link above explains how to retrieve tweets. You should be able to use the above link COMBINED with the information in the link below to POST tweets!
https://dev.twitter.com/overview/documentation
First i have downloaded twitter4j-3.0.3 and put its .jar files into libs folder of my eclipse app.After that i create an app on https://dev.twitter.com/ and get all the credentials needed and gave callback url as https://google.co.in
Now my code is as follows
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.content.Intent;
import android.net.Uri;
import android.os.Bundle;
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 TwitterSampleActivity extends Activity {
private static final String CONSUMER_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxx";
private static final String CONSUMER_SECRET = "xxxxxxxxxxxxxxxxxxx";
private static final String CALLBACK = "https://google.co.in";
private String OAuthToken;
private String OAuthSecret;
private boolean isLogged;
private static Twitter twitter;
private static RequestToken requestToken;
private Button loginButton;
private Button logoutButton;
private Button sendStatus;
private EditText status;
private TextView userName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter);
loginButton = (Button) findViewById(R.id.twitter_log_in);
logoutButton = (Button) findViewById(R.id.twitter_log_out);
sendStatus = (Button) findViewById(R.id.twitter_send);
status = (EditText) findViewById(R.id.twitter_text);
userName = (TextView) findViewById(R.id.twitter_username);
loginButton.setVisibility(View.VISIBLE);
userName.setVisibility(View.GONE);
sendStatus.setVisibility(View.GONE);
status.setVisibility(View.GONE);
logoutButton.setVisibility(View.GONE);
Uri uri = getIntent().getData();
if(uri!=null && uri.toString().startsWith(CALLBACK)) {
String verifier = uri.getQueryParameter("oauth_verifier");
try {
AccessToken token = twitter.getOAuthAccessToken(requestToken, verifier);
OAuthToken = token.getToken();
OAuthSecret = token.getTokenSecret();
isLogged = true;
loginButton.setVisibility(View.GONE);
userName.setVisibility(View.VISIBLE);
sendStatus.setVisibility(View.VISIBLE);
status.setVisibility(View.VISIBLE);
logoutButton.setVisibility(View.VISIBLE);
User user = twitter.showUser(token.getUserId());
String username = user.getName();
userName.setText("Logged as: " + username);
} catch (Exception e) {
Log.e("Login error: ", e.getMessage());
}
}
}
public void onLogInClicked(View v) {
if(!isLogged) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(CONSUMER_KEY);
builder.setOAuthConsumerSecret(CONSUMER_SECRET);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(CALLBACK);
this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "Already logged", Toast.LENGTH_LONG).show();
}
}
public void onLogOutclicked(View v) {
OAuthToken = "";
OAuthSecret = "";
isLogged = false;
loginButton.setVisibility(View.VISIBLE);
userName.setVisibility(View.GONE);
userName.setText("");
sendStatus.setVisibility(View.GONE);
status.setVisibility(View.GONE);
logoutButton.setVisibility(View.GONE);
}
public void onSendClicked(View v) {
String text = status.getText().toString();
if(text.length()>0) {
new SendTwitterStatusUpdate(this, CONSUMER_KEY, CONSUMER_SECRET,
OAuthToken, OAuthSecret).execute(text);
} else {
Toast.makeText(this, "Enter some text" , Toast.LENGTH_SHORT).show();
}
}
}
and my activity_twitter.xml file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/twitter_log_in"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="twitter log in"
android:onClick="onLogInClicked" />
<TextView
android:id="#+id/twitter_username"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/twitter_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
<Button
android:id="#+id/twitter_send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="twitter send"
android:onClick="onSendClicked" />
<Button
android:id="#+id/twitter_log_out"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="twitter log_out"
android:onClick="onLogOutClicked" />
</LinearLayout>
and SendTwitterStatusUpdate.java file is
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
public class SendTwitterStatusUpdate extends AsyncTask<String, Void, Boolean>{
private Context context;
private String consumerKey;
private String consumerSecret;
private String accessToken;
private String accessTokenSecret;
public SendTwitterStatusUpdate(Context context, String consumerKey, String consumerSecret, String accessToken,String accessTokenSecret) {
this.context=context;
this.consumerKey=consumerKey;
this.consumerSecret=consumerSecret;
this.accessToken=accessToken;
this.accessTokenSecret=accessTokenSecret;
}
#Override
protected Boolean doInBackground(String... params) {
String status = params[0];
if(status!=null) {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
AccessToken token = new AccessToken(accessToken, accessTokenSecret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(token);
twitter.updateStatus(status);
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
#Override
public void onPostExecute(Boolean result) {
if(result) {
Toast.makeText(context, "Status successfully updated", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Status not updated", Toast.LENGTH_LONG).show();
}
}
Now when i run my application i got this window
and apart from that when i am clicking on that button twitter log in ...that button is not working..need help
}
can anyone tell me why i am getting null on Uri uri = getIntent().getData();...uri object value is null..thus this part is not executing
if(uri!=null && uri.toString().startsWith(CALLBACK)) {
String verifier = uri.getQueryParameter("oauth_verifier");
try {
AccessToken token = twitter.getOAuthAccessToken(requestToken, verifier);
OAuthToken = token.getToken();
OAuthSecret = token.getTokenSecret();
isLogged = true;
loginButton.setVisibility(View.GONE);
userName.setVisibility(View.VISIBLE);
sendStatus.setVisibility(View.VISIBLE);
status.setVisibility(View.VISIBLE);
logoutButton.setVisibility(View.VISIBLE);
User user = twitter.showUser(token.getUserId());
String username = user.getName();
userName.setText("Logged as: " + username);
} catch (Exception e) {
Log.e("Login error: ", e.getMessage());
}
}
Check out this Demo links , you will get idea how it works and then try to implement own
you can download both
you have to just create your Twitter app.That is also explain by blogger.Follow them you will get two keys.
TWITTER_CONSUMER_KEY="**********************";
TWITTER_CONSUMER_SECRET="********************";
Replace inside your activity and run your project.
First Example
Second Example
Enjoy.!!!
i'm using Selvin's code in my apps..but not getting how to post a message on wall..
here is my code..
i have refer this link for Integration Here Posting LinkedIn message from Android application
package pl.osadkowski.LITest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.Person;
public class LITestActivity extends Activity {
// /change keysssssssssssssssssssssssssssss!!!!!!!!!!
static final String CONSUMER_KEY = "6oj6vol2hva6";
static final String CONSUMER_SECRET = "rreH5PzHDgzXZMpq";
static final String APP_NAME = "LITest";
static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
static final String OAUTH_CALLBACK_HOST = "litestcalback";
static final String OAUTH_CALLBACK_URL = String.format("%s://%s",
OAUTH_CALLBACK_SCHEME, OAUTH_CALLBACK_HOST);
static final String OAUTH_QUERY_TOKEN = "oauth_token";
static final String OAUTH_QUERY_VERIFIER = "oauth_verifier";
static final String OAUTH_QUERY_PROBLEM = "oauth_problem";
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(CONSUMER_KEY,
CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
static final String OAUTH_PREF = "LIKEDIN_OAUTH";
static final String PREF_TOKEN = "token";
static final String PREF_TOKENSECRET = "tokenSecret";
static final String PREF_REQTOKENSECRET = "requestTokenSecret";
TextView tv = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(PREF_TOKEN, null);
final String tokenSecret = pref.getString(PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
final LinkedInRequestToken liToken = oAuthService
.getOAuthRequestToken(OAUTH_CALLBACK_URL);
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit()
.putString(PREF_REQTOKENSECRET, liToken.getTokenSecret())
.commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(OAUTH_QUERY_PROBLEM);
if (problem == null) {
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF,
MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(uri
.getQueryParameter(OAUTH_QUERY_TOKEN),
pref.getString(PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(PREF_TOKEN, accessToken.getToken())
.putString(PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(PREF_REQTOKENSECRET).commit();
showCurrentUser(accessToken);
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit()
.remove(PREF_TOKEN).remove(PREF_TOKENSECRET)
.remove(PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
final LinkedInApiClient client = factory
.createLinkedInApiClient(accessToken);
try {
final Person p = client.getProfileForCurrentUser();
// /////////////////////////////////////////////////////////
// here you can do client API calls ...
// client.postComment(arg0, arg1);
// client.updateCurrentStatus(arg0);
// or any other API call (this sample only check for current user
// and shows it in TextView)
// /////////////////////////////////////////////////////////
tv.setText(p.getLastName() + ", " + p.getFirstName());
} catch (LinkedInApiClientException ex) {
clearTokens();
Toast.makeText(
this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
}
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
}
plz provide me java and xml code as well...Thanks in advance
Once you got the accessToken just like you got in finishAuthenticate() method, write the following code to post update in any AsyncTask's doInBackground Method.
LinkedInApiClient client = factory.createLinkedInApiClient(accessToken);
client.postNetworkUpdate(YOUR_MESSAGE_STRING);
Simple, isn't it?
1.You can download source code from http://socialauth-android.googlecode.com/files/socialauth-android-sdk-3.0.zip .
2.Go to socialauth-android-sdk-3.0 -->examples, now import the share-button project.
3.Now go back to socialauth-android-sdk-3.0 --> src, now import socialauth-android as a library for share-button project.
4.Run the share-button project.
Follow Android LinkedIn OAuth implementation from
http://www.sourcetricks.com/2012/07/android-linkedin-oauth-implementation.html
you can also download the sample project from here..
First, I have all configured (twitter keys, callback in the manifest, etc), then I do the call to twitter and get browser open, then I signIn in twitter and I accept the application, then the browser returns to application and try to get the response from twitter, but I get NULL as answer.
package com.example.fragmenttwitter;
import twitter4j.IDs;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends SherlockFragmentActivity {
private final int LOGIN = 1;
private final int TweetMenu = 2;
private final int Retweet = 3;
private final int FOWLOIING = 5;
private final int SETTING = 6;
private final int LOGOUT = 7;
static String TWITTER_CONSUMER_KEY = "xxx";
static String TWITTER_CONSUMER_SECRET = "yyy";
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static boolean isLogin;
private WebView wv;
private String Url = null;
Uri u;
ImageButton close;
Button cancel;
Button btnUpdateStatus;
EditText txtUpdate;
TextView lblUpdate;
TextView lblUserName;
ProgressDialog pDialog;
private PopupWindow Popup;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
/// option menu
#Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
menu.add(Menu.NONE, LOGIN, Menu.NONE, "Login").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS);
SubMenu submenu = menu.addSubMenu("Option");
submenu.add(Menu.NONE, TweetMenu, Menu.NONE, "Tweet").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
submenu.add(Menu.NONE, FOWLOIING, Menu.NONE, "Following")
.setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
submenu.add(Menu.NONE, SETTING, Menu.NONE, "Setting").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
submenu.add(Menu.NONE, LOGOUT, Menu.NONE, "Logout").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case LOGIN:
if (item.getTitle().equals(("Login"))) {
loginToTwitter();
//new Login().execute();
item.setTitle("Logout");
} else {
logoutFromTwitter();
item.setTitle("Login");
}
break;
case TweetMenu:
ImageButton bt1 = (ImageButton) findViewById(R.id.imageButton1);
bt1.setVisibility(View.VISIBLE);
setContentView(R.layout.activity_main1);
Button bt_status = (Button) findViewById(R.id.btnUpdateStatus);
bt_status.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final EditText etStaus = (EditText) findViewById(R.id.txtUpdateStatus);
String status = etStaus.getText().toString();
if (status.trim().length() > 0) {
new updateTwitterStatus().execute(status);
} else {
Toast.makeText(getApplicationContext(),
"Please enter status message",
Toast.LENGTH_SHORT).show();
}
}
});
break;
case Retweet:
String retweet = txtUpdate.getText().toString();
if (retweet.trim().length() > 0) {
Twitter twitter = new TwitterFactory().getInstance();
try {
twitter.retweetStatus(Long.parseLong(retweet));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Please enter Tweet message", Toast.LENGTH_SHORT)
.show();
}
break;
case FOWLOIING:
Toast.makeText(getApplicationContext(), "Fowllowing called",
Toast.LENGTH_SHORT).show();
followingList();
break;
case SETTING:
Toast.makeText(getApplicationContext(), "setting called",
Toast.LENGTH_SHORT).show();
break;
case LOGOUT:
Toast.makeText(getApplicationContext(), "Logout called",
Toast.LENGTH_SHORT).show();
logoutFromTwitter();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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;
}
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
FragmentManager f = getSupportFragmentManager();
TweetList tl = new TweetList();
FragmentTransaction ft = f.beginTransaction().add(R.id.Lineary2, tl);
ft.commit();
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// check for already login in or not
if (!isTwitterLoggedInAlready()) {
Uri uri=getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
///AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
} catch (Exception e) {
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
else
Toast.makeText(getBaseContext(), "not Login",Toast.LENGTH_LONG).show();
}
}
// code 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();
new Thread(new Runnable() {
public void run() {
try {
//requestToken = twitter
//.getOAuthRequestToken(TWITTER_CALLBACK_URL);
// twitter.setOAuthConsumer(TWITTER_CONSUMER_KEY,TWITTER_CONSUMER_SECRET);
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
MainActivity.this.startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse(requestToken
.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
}
}).start();
}
}
//update the stastus from twiiter app
class updateTwitterStatus extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
String access_token = mSharedPreferences.getString(
PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(
PREF_KEY_OAUTH_SECRET, "");
Log.i("Access Token", access_token);
Log.i("Access Token secrate", access_token_secret);
AccessToken accessToken = new AccessToken(access_token,
access_token_secret);
Log.i("Access Token", accessToken.toString());
Twitter twitter = new TwitterFactory(builder.build())
.getInstance(accessToken);
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
txtUpdate.setText("");
}
});
}
}
//Logout from twitter app
public 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();
}
private boolean isTwitterLoggedInAlready() {
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
public void onResume() {
super.onResume();
}
}