I have Written the code to Integrate the Twitter in android.In that I am getting the first scrren and when I am writing some message to twitt and click on the twitt button I am getting following Exception as OauthCommunication Exception communication with the service provider failed.I have entered the Consumer key Consumer secrete properly.
Public class MainActivity extends Activity {
private static final String TAG = "TwitterDemo";
private static final String CONSUMER_KEY = "xxx";
private static final String CONSUMER_SECRET = "xxx";
private static final String CALLBACK_SCHEME = "twitter-OAUTH-test-app";
private static final String CALLBACK_URL = CALLBACK_SCHEME + "://callback";
private static final String TWITTER_USER = "androidtestacc1#gmail.com";
private OAuthSignpostClient oauthClient;
private OAuthConsumer mConsumer;
private OAuthProvider mProvider;
private Twitter twitter;
SharedPreferences prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
mProvider = new DefaultOAuthProvider(
"http://api.twitter.com/oauth/request_token",
"http://api.twitter.com/oauth/access_token",
"http://api.twitter.com/oauth/authorize");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
String token = prefs.getString("token", null);
String tokenSecret = prefs.getString("tokenSecret", null);
if (token != null && tokenSecret != null) {
mConsumer.setTokenWithSecret(token, tokenSecret);
oauthClient = new OAuthSignpostClient(CONSUMER_KEY,
CONSUMER_SECRET, token, tokenSecret);
twitter = new Twitter(TWITTER_USER, oauthClient);
} else {
Log.d(TAG, "onCreate. Not Authenticated Yet " );
new OAuthAuthorizeTask().execute();
}
}
class OAuthAuthorizeTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String authUrl;
String message = null;
Log.d(TAG, "OAuthAuthorizeTask mConsumer: " + mConsumer);
Log.d(TAG, "OAuthAuthorizeTask mProvider: " + mProvider);
try {
authUrl = mProvider.retrieveRequestToken(mConsumer,
CALLBACK_URL);
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(authUrl));
startActivity(intent);
} catch (OAuthMessageSignerException e) {
message = "OAuthMessageSignerException";
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
message = "OAuthNotAuthorizedException";
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
message = "OAuthExpectationFailedException";
e.printStackTrace();
} catch (OAuthCommunicationException e) {
message = "OAuthCommunicationException";
e.printStackTrace();
}
return message;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
}
public void tweet(View view) {
if (twitter == null) {
Toast.makeText(this, "Authenticate first", Toast.LENGTH_LONG)
.show();
return;
}
EditText status = (EditText) findViewById(R.id.editTextTweet);
new PostStatusTask().execute(status.getText().toString());
}
class PostStatusTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
twitter.setStatus(params[0]);
return "Successfully posted: " + params[0];
} catch (TwitterException e) {
e.printStackTrace();
return "Error connecting to server.";
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
/* Responsible for retrieving access tokens from twitter */
class RetrieveAccessTokenTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String message = null;
String oauthVerifier = params[0];
try {
// Get the token
Log.d(TAG, " RetrieveAccessTokenTask mConsumer: " + mConsumer);
Log.d(TAG, " RetrieveAccessTokenTask mProvider: " + mProvider);
Log.d(TAG, " RetrieveAccessTokenTask verifier: " + oauthVerifier);
mProvider.retrieveAccessToken(mConsumer, oauthVerifier);
String token = mConsumer.getToken();
String tokenSecret = mConsumer.getTokenSecret();
mConsumer.setTokenWithSecret(token, tokenSecret);
Log.d(TAG, String.format(
"verifier: %s, token: %s, tokenSecret: %s", oauthVerifier,
token, tokenSecret));
// Store token in prefs
prefs.edit().putString("token", token)
.putString("tokenSecret", tokenSecret).commit();
// Make a Twitter object
oauthClient = new OAuthSignpostClient(CONSUMER_KEY,
CONSUMER_SECRET, token, tokenSecret);
twitter = new Twitter(null, oauthClient);
Log.d(TAG, "token: " + token);
} catch (OAuthMessageSignerException e) {
message = "OAuthMessageSignerException";
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
message = "OAuthNotAuthorizedException";
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
message = "OAuthExpectationFailedException";
e.printStackTrace();
} catch (OAuthCommunicationException e) {
message = "OAuthCommunicationException";
e.printStackTrace();
}
return message;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
}
/*
* Callback once we are done with the authorization of this app with
* Twitter.
*/
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "intent: " + intent);
// Check if this is a callback from OAuth
Uri uri = intent.getData();
if (uri != null && uri.getScheme().equals(CALLBACK_SCHEME)) {
Log.d(TAG, "callback: " + uri.getPath());
String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Log.d(TAG, "verifier: " + verifier);
Log.d(TAG, " xxxxxxxxxxx mConsumer access token: " + mConsumer.getToken());
Log.d(TAG, " xxxxxxxxxxxx mConsumer access token secret: " + mConsumer.getTokenSecret());
Log.d(TAG, " xxxxxxxxxxxxx OAuth.OAUTH_TOKEN: " + OAuth.OAUTH_TOKEN);
Log.d(TAG, " xxxxxxxxxxxxx OAuth.OAUTH_TOKEN_SECRET: " + OAuth.OAUTH_TOKEN_SECRET);
new RetrieveAccessTokenTask().execute(verifier);
}
}
public void logout(View view){
SharedPreferences.Editor editor = prefs.edit();
editor.putString("token", null);
editor.putString("tokenSecret", null);
editor.commit();
finish();
}
}
error
10-19 15:18:55.424: W/System.err(995): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: http://api.twitter.com/oauth/request_token
10-19 15:18:55.424: W/System.err(995): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
10-19 15:18:55.438: W/System.err(995): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
10-19 15:18:55.655: W/System.err(995): ... 9 more
try another way to integerate twitter in your app
Using auth & webview(Twitter4j library)
http://davidcrowley.me/?p=410
http://www.mokasocial.com/2011/07/writing-an-android-twitter-client-with-image-upload-using-twitter4j/
code(url open in web view)
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(TwitterConstants.CONSUMER_KEY,
TwitterConstants.CONSUMER_SECRET);
RequestToken requestToken = null;
try {
requestToken = twitter.getOAuthRequestToken();
System.out.println("requesttoken"+requestToken);
} catch (TwitterException e) {
e.printStackTrace();
}
twitterUrl = requestToken.getAuthorizationURL();
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthAccessToken(TwitterConstants.ACCESS_TOKEN);
builder.setOAuthAccessTokenSecret(TwitterConstants.ACCESS_TOKEN_SECRET);
builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
OAuthAuthorization auth = new OAuthAuthorization(builder.build());
twitter = new TwitterFactory().getInstance(auth);
try {
twitter.updateStatus("Hello World!");
} catch (TwitterException e) {
System.err.println("Error occurred while updating the status!");
}
2. On Button Click(Without auth)
String message="";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://twitter.com/?status=" + Uri.encode(message)));
startActivity(i);
Please put following permission in your Manifest file
<uses-permission android:name="android.permission.INTERNET"/>
also check this link....
http://www.android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application
Related
I want to use the Yahoo API to get login user's email in Android. I already have got access token and user GUID, but the next step to get user email is not working.
I got the following response message:
{oauth=WWW-Authenticate: OAuth oauth_problem="OST_OAUTH_SIGNATURE_INVALID_ERROR", realm="yahooapis.com"}
My code can be found here and the problem is documented here at line 179.
Please help me to resolve this issue.
I got an answer
Full Code :
public class YahooScreen extends Activity {
private static final String REQUEST_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_request_token";
private static final String AUTHORIZE_WEBSITE_URL ="https://api.login.yahoo.com/oauth/v2/request_auth";
private static final String ACCESS_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_token";
static final String YAHOO_CALLBACK_URL = "YOUR_YAHOO_CALLBACK_URL";
static final String YAHOO_CONSUMER_KEY = "YOUR_YAHOO_CONSUMER_KEY";
static final String YAHOO_CONSUMER_SECRET = "YOUR_YAHOO_CONSUMER_SECRET";
private String oAuthVerifier;
CommonsHttpOAuthConsumer mainConsumer;
CommonsHttpOAuthProvider mainProvider;
private Button button1;
private OnClickListener button1_onclick = new OnClickListener()
{
public void onClick(View v)
{
new OAuthRequestTokenTask(v.getContext(),mainConsumer,mainProvider).execute();
}
};
private Button button2;
private OnClickListener button2_onclick = new OnClickListener()
{
public void onClick(View v)
{
new OAuthGetAccessTokenTask().execute();
}
};
private Button button3;
private OnClickListener button3_onclick = new OnClickListener()
{
public void onClick(View v)
{
getGUID();
}
};
private Button button4;
private OnClickListener button4_onclick = new OnClickListener()
{
public void onClick(View v)
{
showToken();
}
};
private Button button5;
private OnClickListener button5_onclick = new OnClickListener()
{
public void onClick(View v)
{
getProfile();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mainConsumer = new CommonsHttpOAuthConsumer(YAHOO_CONSUMER_KEY, YAHOO_CONSUMER_SECRET);
this.mainProvider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_ENDPOINT_URL, ACCESS_TOKEN_ENDPOINT_URL, AUTHORIZE_WEBSITE_URL);
//this.mainConsumer.setSigningStrategy(new YahooAuthorizationHeaderSigningStrategy());
// It turns out this was the missing thing to making standard Activity launch mode work
//this.mainProvider.setOAuth10a(true);
// get request
button1 = (Button) this.findViewById(R.id.button1);
button1.setOnClickListener(button1_onclick);
// access token
button2 = (Button) this.findViewById(R.id.button2);
button2.setOnClickListener(button2_onclick);
// guid
button3 = (Button) this.findViewById(R.id.button3);
button3.setOnClickListener(button3_onclick);
// show token
button4 = (Button) this.findViewById(R.id.button4);
button4.setOnClickListener(button4_onclick);
// Profile
button5 = (Button) this.findViewById(R.id.button5);
button5.setOnClickListener(button5_onclick);
}
#Override
protected void onNewIntent(Intent intent) {
Toast.makeText(getApplicationContext(), "OnNewIntent - It works!",
Toast.LENGTH_LONG).show();
Uri uriData = intent.getData();
if (uriData != null && uriData.toString().startsWith(YAHOO_CALLBACK_URL)) {
setVerifier(uriData.getQueryParameter("oauth_verifier"));
}
super.onNewIntent(intent);
}
class OAuthRequestTokenTask extends AsyncTask<Void, Void, String> {
final String TAG = getClass().getName();
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
}
#Override
protected String doInBackground(Void... params) {
try {
Log.i(TAG, "Retrieving request token from Google servers");
final String url = provider.retrieveRequestToken(consumer, YAHOO_CALLBACK_URL);
Log.i(TAG, "Popping a browser with the authorize URL : " + url);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
return url;
} catch (Exception e) {
Log.e(TAG, "Error during OAUth retrieve request token", e);
}
return null;
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
Log.i(TAG, "onPostExecute result : " + result);
super.onPostExecute(result);
}
}
public class OAuthGetAccessTokenTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
try {
mainProvider.retrieveAccessToken(mainConsumer, oAuthVerifier);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
showToken();
}
}
public void setVerifier(String verifier)
{
this.oAuthVerifier = verifier;
// this.webview.loadData("verifier = " + this.OAuthVerifier + "<br>", "text/html", null);
Log.d("setVerifier", verifier);
this.showToken();
}
public void showToken()
{
//Log.d("SubPlurkV2", "Token = " + mainConsumer.getToken() + " and secret = " + mainConsumer.getTokenSecret());
String str =
"verifier = " + this.oAuthVerifier + "<br>" +
"Token = " + mainConsumer.getToken() + "<br>" +
"secret = " + mainConsumer.getTokenSecret() + "<br>" +
"oauth_expires_in = " + mainProvider.getResponseParameters().getFirst("oauth_expires_in") + "<br>" +
"oauth_session_handle = " + mainProvider.getResponseParameters().getFirst("oauth_session_handle") + "<br>" +
"oauth_authorization_expires_in = " + mainProvider.getResponseParameters().getFirst("oauth_authorization_expires_in") + "<br>" +
"xoauth_yahoo_guid = " + mainProvider.getResponseParameters().getFirst("xoauth_yahoo_guid") + "<br>";
Log.i("YahooScreen", "str : " + str);
}
private void doGet(String url) {
OAuthConsumer consumer = this.mainConsumer;
final HttpGet request = new HttpGet(url);
Log.i("doGet","Requesting URL : " + url);
try {
consumer.sign(request);
Log.i("YahooScreen", "request url : " + request.getURI());
new Thread(new Runnable() {
#Override
public void run() {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute((HttpUriRequest) request);
Log.i("doGet","Statusline : " + response.getStatusLine());
InputStream data = response.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(data));
String responeLine;
StringBuilder responseBuilder = new StringBuilder();
while ((responeLine = bufferedReader.readLine()) != null) {
responseBuilder.append(responeLine);
}
Log.i("doGet","Response : " + responseBuilder.toString());
//return responseBuilder.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getGUID()
{
String GUID_URL="http://social.yahooapis.com/v1/me/guid?format=json";
this.doGet(GUID_URL);
}
public void getProfile()
{
String guid = mainProvider.getResponseParameters().getFirst("xoauth_yahoo_guid");
String url = "https://social.yahooapis.com/v1/user/" + guid + "/profile?format=json";
this.doGet(url);
}
}
I use the following snippet to get token:
private class task extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
Bundle appActivities = new Bundle();
appActivities.putString(
GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
Constants.ADD_ACTIVITY_SCHEME + " "
+ Constants.BUY_ACTIVITY_SCHEME);
String serverClientID = "My_Client_Id";
String scopes = "oauth2:server:client_id:" + serverClientID
+ ":api_scope:" + Scopes.PLUS_LOGIN + " "
+ Scopes.PLUS_PROFILE;
String code = null;
try {
code = GoogleAuthUtil.getToken(MainActivity.this, // Context
// context
mPlusClient.getAccountName(), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
} catch (IOException transientEx) {
code = "Loi 1";
} catch (UserRecoverableAuthException e) {
code = "Loi 2: "+e.getMessage();
} catch (GoogleAuthException authEx) {
code = "Loi 3";
} catch (Exception e) {
throw new RuntimeException(e);
}
return code;
}
#Override
protected void onPostExecute(String token) {
showToast(token);
}
}
I execute this line of code in onConnected method:
new task.execute();
UserRecoverableAuthException occur and my toast show message: "NeedPermission".
How can i fix it?
Have your added the following permission in your manifest?
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
here is the working code for me!
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
String accountName = mPlusClient.getAccountName();
// Get user's information
task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
try {
token = GoogleAuthUtil.getToken(MyNetwork.this,
mPlusClient.getAccountName(), "oauth2:"
+ Scopes.PROFILE);
Log.i("TAG", "token" + token);
} catch (IOException transientEx) {
// Network or server error, try later
Log.e(TAG, transientEx.toString());
} catch (UserRecoverableAuthException e) {
// Recover (with e.getIntent())
Log.e(TAG, e.toString());
Intent recover = e.getIntent();
startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
} catch (GoogleAuthException authEx) {
Log.e(TAG, authEx.toString());
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
mHandler.sendEmptyMessage(STOP_PROGRESS);
getProfileInformation(token);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mHandler.sendEmptyMessage(SHOW_PROGRESS);
}
};
task.execute();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG)
.show();
}
and i am getting user information like the following.
/**
* Fetching user's information name, email, profile pic
* */
private void getProfileInformation(String mToken) {
String mAccessToken = mToken == null ? "" : mToken;
String mProfileId = "";
String mProfileName = "";
String mImageUrl = "";
String mSecretKey = "";
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
txtGooglePlus.setText(currentPerson.getDisplayName());
mProfileName = currentPerson.getDisplayName();
mImageUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + mProfileName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + mImageUrl);
mProfileId = currentPerson.getId();
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
It is working fine for me. Tested. Check and feel free to ask if there is any issue.
I m trying to tweet image from sd card folder but still can't do that. I m using twitter4j-core-3.0.3 api and gave permissions android.permission.INTERNET,android.permission.ACCESS_NETWORK_STATE. Here is my code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
twitterButton = (Button) findViewById(R.id.twitPic);
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
new ImageSender().execute();
}
});
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 {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
// 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());
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
private class ImageSender extends AsyncTask<URL, Integer, Long> {
private String url;
protected void onPreExecute() {
pDialog = ProgressDialog.show(MainActivity.this, "", "Sending image...", true);
pDialog.setCancelable(false);
pDialog.show();
}
protected Long doInBackground(URL... urls) {
long result = 0;
Log.d(TAG, "Start sending image...");
try {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Friends/"+"image4.jpg";
File targetDirector = new File(targetPath);
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 = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate status = new StatusUpdate("");
status.setMedia(targetDirector);
twitter.updateStatus(status);
result = 1;
Log.d(TAG, "Image uploaded, Twitpic url is " + url);
} catch (TwitterException e) {
Log.e(TAG, "Failed to send image "+e);
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
pDialog.cancel();
String text = (result == 1) ? "Image sent successfully.\n Twitpic url is: " + url : "Failed to send image";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
}
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
Here is my log
04-02 06:38:02.275: E/Tag(1762): Failed to send image 400:The request was invalid. An accompanying error message will explain why. This is the status code will be returned during version 1.0 rate limiting(https://dev.twitter.com/pages/rate-limiting). In API v1.1, a request without authentication is considered invalid and you will get this response.
04-02 06:38:02.275: E/Tag(1762): message - Bad Authentication data
04-02 06:38:02.275: E/Tag(1762): code - 215
04-02 06:38:02.275: E/Tag(1762): Relevant discussions can be found on the Internet at:
04-02 06:38:02.275: E/Tag(1762): http://www.google.co.jp/search?q=b2b52c28 or
04-02 06:38:02.275: E/Tag(1762): http://www.google.co.jp/search?q=11331d43
04-02 06:38:02.275: E/Tag(1762): TwitterException{exceptionCode=[b2b52c28-11331d43], statusCode=400, message=Bad Authentication data, code=215, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
Edit: When i try to tweet a text in this portion
StatusUpdate status = new StatusUpdate("");
status.setMedia(targetDirector);
twitter.updateStatus(status);
to twitter.updateStatus("If you're reading this on Twitter, it worked!"); then same error creates.
I m on it from some days but get no solution. Please anyone help me to solve the problem.Thanks
change you AsyncTask use like this it is working for me
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String status = null;
new updateTwitterStatus().execute(status);
}
});
public class updateTwitterStatus extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar_show();
}
protected String doInBackground(String... args) {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
access_token = SharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
access_token_secret = SharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
String upload_image_url = postPicture( "/mnt/sdcard/yourimage.jpg", " ");
Log.d("--------------upload_image_url=" + upload_image_url.toString() + "---------", " ");
} catch (Exception e) {
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
public String postPicture(String fileName, String message) {
try {
Log.d("----start---postPicture()---", " ");
File file = new File(fileName);
MediaProvider mProvider = getMediaProvider();
String accessTokenToken = access_token;
String accessTokenSecret = access_token_secret;
Properties props = new Properties();
props.put(PropertyConfiguration.MEDIA_PROVIDER, mProvider);
props.put(PropertyConfiguration.OAUTH_ACCESS_TOKEN, accessTokenToken);
props.put(PropertyConfiguration.OAUTH_ACCESS_TOKEN_SECRET, accessTokenSecret);
props.put(PropertyConfiguration.OAUTH_CONSUMER_KEY, TWITTER_CONSUMER_KEY);
props.put(PropertyConfiguration.OAUTH_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET);
Configuration conf = new PropertyConfiguration(props);
ImageUploadFactory factory = new ImageUploadFactory(conf);
ImageUpload upload = factory.getInstance(mProvider);
String url;
url = upload.upload(file, message);
Log.d("----end---postPicture()---", " ");
return url;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
MediaProvider getMediaProvider() {
Log.d("----start---getMediaProvider()---", " ");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String provider = preferences.getString("pictureService", "twitter");
MediaProvider mProvider;
if (provider.equals("yfrog"))
mProvider = MediaProvider.YFROG;
else if (provider.equals("twitpic"))
mProvider = MediaProvider.TWITPIC;
else if (provider.equals("twitter"))
mProvider = MediaProvider.TWITTER;
else
throw new IllegalArgumentException("Picture provider " + provider + " unknown");
Log.d("----end---getMediaProvider()---", " ");
return mProvider;
}
protected void onPostExecute(String file_url) {
ProgressBar_hide();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Status tweeted successfully", Toast.LENGTH_SHORT).show();
}
});
}
}
i have some trouble with the OAuth signing.
on the point i expect to get the retrieveRequestToken i got the following error:
01-05 17:26:02.775: W/System.err(24358): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: null
i have no idea why i get this. Any suggestions here?
My Code:
connectionDec = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!connectionDec.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;
}
CommonsHttpOAuthConsumer consumer =
new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
CommonsHttpOAuthProvider provider =
new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL,
AUTHORIZE_URL);
provider.setOAuth10a(true);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String token = sharedPreferences.getString("token", null);
String tokenSecret = sharedPreferences.getString("token_secret", null);
if (token == null || tokenSecret == null)
{
Map requestHeaders = provider.getRequestHeaders();
requestHeaders.put("User-Agent", USER_AGENT);
requestHeaders.put("Accept-Encoding", "gzip");
try
{
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
}
catch (OAuthMessageSignerException e)
{
e.printStackTrace();
}
catch (OAuthNotAuthorizedException e)
{
e.printStackTrace();
}
catch (OAuthExpectationFailedException e)
{
e.printStackTrace();
}
catch (OAuthCommunicationException e)
{
e.printStackTrace();
}
}
else
{
}
any tipps and helps ... thank you
PS: It is Discogs and not Twitter
Greets Mad
OK, i have answered the question myself ... i have implement a asynctask like the following and it works:
public class StartUpActivity extends Activity implements OnClickListener
{
private static String CONSUMER_KEY = "consumerkey";
private static String CONSUMER_SECRET = "yourconsumersecret";
private static String REQUEST_TOKEN_URL = "http://api.discogs.com/oauth/request_token";
private static String AUTHORIZE_URL = "http://www.discogs.com/oauth/authorize";
private static String ACCESS_TOKEN_URL = "http://api.discogs.com/oauth/access_token";
private static String USER_AGENT = "youruseragent";
private static String CALLBACK_URL = "http://www.callback.com";
private ConnectionDetector connectionDec;
private SharedPreferences sharedPreferences;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.start_up_layout);
connectionDec = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!connectionDec.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;
}
}
class ProgressTask extends AsyncTask<Integer, Integer, Void>{
#Override
protected void onPreExecute() {
// initialize the progress bar
// set maximum progress to 100.
}
#Override
protected void onCancelled() {
// stop the progress
}
#Override
protected Void doInBackground(Integer... params) {
// get the initial starting value
int start=params[0];
// increment the progress
try {
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
CommonsHttpOAuthProvider provider =
new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZE_URL);
provider.setOAuth10a(true);
// Check if token and tokensecret are already stored at app preferences
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String token = sharedPreferences.getString("token", null);
String tokenSecret = sharedPreferences.getString("token_secret", null);
if (token == null || tokenSecret == null)
{
Map<String, String> requestHeaders = provider.getRequestHeaders();
requestHeaders.put("User-Agent", USER_AGENT);
requestHeaders.put("Accept-Encoding", "gzip");
try
{
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
}
catch (OAuthMessageSignerException e)
{
e.printStackTrace();
}
catch (OAuthNotAuthorizedException e)
{
e.printStackTrace();
}
catch (OAuthExpectationFailedException e)
{
e.printStackTrace();
}
catch (OAuthCommunicationException e)
{
e.printStackTrace();
}
}
else
{
}
}
catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// increment progress bar by progress value
}
#Override
protected void onPostExecute(Void result) {
// async task finished
}
}
}
Trying to send user details who is log in to my app with facebook details to mysql database using databasehelper.java here i am getting error in DatabaseHelper helper1 = new DatabaseHelper(this); is there any syntax mistake or any wrong code i am using for sending the data to my server ??
public void getProfileInformation() {
Bundle params = new Bundle();
params.putString("fields", "id,name,email");
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
final String id = profile.getString("id");
/*runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Name: " + name + "\nEmail: " + email + "\nid" + id,
Toast.LENGTH_LONG).show();
}
});*/
if(id != null && id.length() > 0){
String accessToken = null;
DatabaseHelper helper1 = new DatabaseHelper(this);
DatabaseUtility dao = new DatabaseUtility(helper);
try {
accessToken = dao.getAccessToken();
} catch (Exception e1) {
}
Map<String , String> params = new HashMap<String,String>();
params.put(Constants.FACEBOOK_ID, id);
params.put(Constants.ACCESS_TOKEN_PARAM, accessToken);
Status status = null;
try {
status = Utils.addFacebookAccount(params, LoginActivity.this);
} catch (NullPointerException e) {
}
catch (JSONException e) {
}
Utils.showErrorMessage(getApplicationContext(), Constants.CONNECTED_TO_FACEBOOK_ERROR, Constants.TOAST_VISIBLE_LONG);
Intent i=new Intent(getApplicationContext(),ProfileActivity.class);
startActivity(i);
}}
catch (JSONException e) {
e.printStackTrace();
}
}