message NeedPermission when get token code - android

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.

Related

Android Login facebook integration

I am developing app using eclipse ADT. I am trying to login and get user data in facebook. I can login with facebook but i am unable to retrieve the user data. here i wrote a method
public void loginFacebook() {
Log.d("Login Facebooktest Sessions", "loginfb called");
mPrefs = getActivity().getPreferences(0);
access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
mFacebook.setAccessToken(access_token);
Log.d("Facebooktest Sessions", "" + mFacebook.isSessionValid());
}
if (expires != 0) {
mFacebook.setAccessExpires(expires);
}
if (!mFacebook.isSessionValid()) {
Log.d("login Facebooktest Sessions",
"" + !mFacebook.isSessionValid());
mFacebook.authorize(getActivity(), new String[] {},
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Log.d("login Facebooktest onFacebookError", "" + e);
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Log.d("login Facebooktest onError ", "" + e);
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Log.d("login Facebooktest bundle", "" + values);
try {
JSONObject me = new JSONObject(mFacebook
.request("me"));
SharedPreferences.Editor editor = mPrefs.edit();
id = me.getString("id");
name = me.getString("name");
email = me.getString("email");
gender = me.getString("gender");
try {
imageLink = new URL(
"https://graph.facebook.com/" + id
+ "/picture?type=large");
Bitmap bmp = null;
try {
bmp = BitmapFactory
.decodeStream(imageLink
.openConnection()
.getInputStream());
} catch (IOException e) {
e.printStackTrace();
Log.e("facebook complete IO error ", ""
+ e);
}
proPic.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e("facebook complete image error ", ""
+ e);
}
Log.d("facebook.getAccessToken()", "" + id
+ mFacebook.getAccessToken());
editor.putString("userid", id);
editor.putString("access_token",
mFacebook.getAccessToken());
editor.putLong("access_expires",
mFacebook.getAccessExpires());
editor.commit();
new getFacebookData(id, name, email, gender)
.execute();
// getProfileInformation();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.e("login facebook complete error ", "" + e);
}
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Log.d("login Facebooktest onCancel", "onCancel");
}
});
} else {
Log.d("login Facebook login method",
"" + mFacebook.isSessionValid());
}
}
this is method is working upto if (!mFacebook.isSessionValid()) this if condition and i can get the true value, but my problem is, the onComplete() method is not working. If its work, i doing doinbackground operation for starting new page. How i can solve this issue
Thanks in advance
use socialauth-android, easy and fast https://code.google.com/p/socialauth-android/
Just check your logcat for any NullPointerException if your values of id, name,gender ... are coming in JSON Object.If NO then first handle this like this
id=me.getString("id")==null ? "":me.getString("id");
or
if(me.getString("id")==null)
{
id = "";
}else
{
id=me.getString("id");
}
make one more dialog and use it in else part of if (!mFacebook.isSessionValid()) :
else
{
facebook.dialog(this, "feed", new DialogListener(){
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Log.d("login Facebooktest bundle", "" + values);
try {
JSONObject me = new JSONObject(mFacebook
.request("me"));
SharedPreferences.Editor editor = mPrefs.edit();
id = me.getString("id");
name = me.getString("name");
email = me.getString("email");
gender = me.getString("gender");
try {
imageLink = new URL(
"https://graph.facebook.com/" + id
+ "/picture?type=large");
Bitmap bmp = null;
try {
bmp = BitmapFactory
.decodeStream(imageLink
.openConnection()
.getInputStream());
} catch (IOException e) {
e.printStackTrace();
Log.e("facebook complete IO error ", ""
+ e);
}
proPic.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e("facebook complete image error ", ""
+ e);
}
}
});

Use Oauth to call yahoo api in android

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);
}
}

Android inserting value in database in background

I am using asyntask to enter value in database. in do in backgroud method i am calling this method.
private void callLogin() {
GetDataFromApi getDataFromApi = new GetDataFromApi(url);
if (!isTableFalse) {
Log.e("MAI A GAAYA SYNCRONISE DATA BASE MAI", "HA MAI AYA");
String message =
getDataFromApi.postSignIn().toString().trim();
syncroniseDatabase(message);
populateChurchListOnValidating
.populateChurchList(parseJsonToArrayList());
} else {
try {
loginValue =
Integer.parseInt(getDataFromApi.postSignIn());
Log.e("Login VAlue", "" + loginValue);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
}
}
and my syncroniseDatabase(message) is like this
private void syncroniseDatabase(String mesString) {
Log.e("URL IN SYNCRONISATION", ""+ url);
try {
InsertTable insertTable = new InsertTable();
JSONObject jsonObject = new JSONObject(mesString);
insertTable.addRowforMemberTable(jsonObject.getString(
RegistrationAppConstant.MEMBER_ID),
jsonObject.getString(RegistrationAppConstant.CLIENT_ID),
jsonObject.getString(RegistrationAppConstant.FIRSTNAME),
jsonObject.getString(RegistrationAppConstant.SURNAME),
jsonObject.getString(RegistrationAppConstant.EMAIL_ID),
jsonObject.getString(RegistrationAppConstant.PASSWORD));
Log.e("Inserting Data DONE", "" + "Done");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and my class forInsertTable is like this
public class InsertTable {
public void addRowforMemberTable(String memberID,
String clientID, String
firstName,String surName, String emailIDString, String passWordString)
{
Log.e("NAME", "" + memberID + " " + clientID + " " + firstName + " "
+ surName + " " + emailIDString + " " +
passWordString);
ContentValues contentValue = new ContentValues();
contentValue.put(AppConstant.MCM_MEMBER_MEMEBER_ID, memberID);
contentValue.put(AppConstant.MCM_MEMBER_CLIENT_ID, clientID);
contentValue.put(AppConstant.MCM_MEMBER_FIRST_NAME, firstName);
contentValue.put(AppConstant.MCM_MEMBER_LAST_NAME, surName);
contentValue.put(AppConstant.MCM_MEMBER_EMAIL_ID, emailIDString);
contentValue.put(AppConstant.MCM_MEMBER_PASSWORD, passWordString);
Log.e("Cotent value", "" + contentValue);
try {
SplashActivity.databaseHelper.insertInToTable(
SplashActivity.databaseHelper.getWritableDatabase(),
AppConstant.MEMBER_TABLE_NAME,
contentValue);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
this is my json String
[{"MemberId":77,"ClientId":37,"FirstName":"John","SurName":"Banian","Address1":null,"Address2":null,"Street":null,"Town":null,"City":null,"County":null,"State":null,"Country":null,"PostCode":null,"Mobile":null,"HomeTelephone":null,"WorkTelephone":null,"EmailId":"jbunian#yahoo.com","ConfirmEmailId":null,"Password":"123","Age":null,"Sex":null,"Profession":null,"MartialStatus":null,"Nationality":null,"Children":null,"ChurchMembershipId":null,"SecurityQuestion":null,"SecurityAnswer":null,"IsApproved":null,"IsLockedOut":null,"CreateDate":null,"LastLoginDate":null,"LastPasswordChangedDate":null,"LastLogOutDate":null,"FailedPasswordAttemptDate":null,"FailedPasswordAttemptWindowStart":null,"FailedPasswordAnswerAttemptCount":null,"FailedPasswordAnswerAttemptWindowStart":null,"Comment":null,"Active":null,"IsAuthToApproveNewMember":null,"Record_Created":null,"Record_Updated":null,"LastUpdated_LoginUserID":null,"LastUpdated_WindowsUser":null,"ClientAdminEmailId":null,"EmailListForApproval":null,"AppRegistrationStatus":null,"MemberEmailMessage":null,"AdminEmailMessage":null,"PhysicalDeviceId":null,"DeviceOS":null,"DeviceIdFromGCMorAPNS":null,"DeviceType":null}]
but my code will not executing after this line and hence i am not able to insert value.I have bold the log after which its not executing.please tell why its not executing?
Problem is that you tring to get values from JSONObject, but in reality it's JSON array. (json string starts with [.
Try to do something like this:
JSONArray jsonArray = new JSONArray(mesString);
JSONObject jsonObject = jsonArray.get(0);
insertTable.addRowforMemberTable(jsonObject.getString(RegistrationAppConstant.MEMBER_ID),
jsonObject.getString(RegistrationAppConstant.CLIENT_ID),
.....
.....

Get access token from google plus Android

Can anyone tell me what am I doing wrong? I need to get the access token from Google Plus..
I put this in my onConnected() method but I am not getting the access token, instead I am getting error...
Code:
try {
String token = GoogleAuthUtil.getToken(this, mPlusClient.getAccountName() + "", "oauth2:" + Scopes.PLUS_PROFILE +
"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email");
Log.d("AccessToken", token);
} catch (UserRecoverableAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Error:
08-07 10:10:24.199: E/GoogleAuthUtil(17203): Calling this from your main thread can lead to deadlock and/or ANRs
Can anyone tell me what would be the correct way to get the Google Plus access token from the user?
You need to put the request for a token in a background thread. I've posted some example code showing how to do it in this question:
"Calling this from your main thread can lead to deadlock and/or ANRs while getting accesToken" from GoogleAuthUtil(Google Plus integration in Android)
You can access token in onConnected() method. add this code onConnected() methods scope.
final String SCOPES = "https://www.googleapis.com/auth/userinfo.profile";
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String ace = "";
try {
ace = GoogleAuthUtil.getToken(getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
}
catch (IOException e) {
e.printStackTrace();
}
catch (GoogleAuthException e) {
e.printStackTrace();
}
Log.i("", "mustafa olll " + ace);
return null;
}
}.execute();
You need to fetch it using async task.
public void onConnected(Bundle connectionHint) {
// Reaching onConnected means we consider the user signed in.
Log.i(TAG, "onConnected");
// Update the user interface to reflect that the user is signed in.
mSignInButton.setEnabled(false);
mSignOutButton.setEnabled(true);
mRevokeButton.setEnabled(true);
// Retrieve some profile information to personalize our app for the user.
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
AsyncTask<Void, Void, String > task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
final String SCOPES = "https://www.googleapis.com/auth/plus.login ";
try {
token = GoogleAuthUtil.getToken(
getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
} catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
e.printStackTrace();
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
}
};
task.execute();
System.out.print("email" + email);
mStatus.setText(String.format(
getResources().getString(R.string.signed_in_as),
currentUser.getDisplayName()));
Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
.setResultCallback(this);
// Indicate that the sign in process is complete.
mSignInProgress = STATE_DEFAULT; }
Your access token will be stored into token variable.
Here is the code you can use. If someone has better suggestion then please post:
/**
* Successfully connected (called by PlusClient)
*/
#Override
public void onConnected(Bundle connectionHint) {
/* First do what ever you wanted to do in onConnected() */
....
....
/* Now get the token using and async call*/
GetGooglePlusToken token = new GetGooglePlusToken(this.getActivity(), mPlusClient);
token.execute();
}
class GetGooglePlusToken extends AsyncTask<Void, Void, String> {
Context context;
private GoogleApiClient mGoogleApiClient;
private String TAG = this.getClass().getSimpleName();
public GetGooglePlusToken(Context context, GoogleApiClient mGoogleApiClient) {
this.context = context;
this.mGoogleApiClient = mGoogleApiClient;
}
#Override
protected String doInBackground(Void... params) {
String accessToken1 = null;
try {
Bundle bundle = new Bundle();
String accountname = Plus.AccountApi.getAccountName(mGoogleApiClient);
String scope = "oauth2:" + Scopes.PLUS_LOGIN + " " + "https://www.googleapis.com/auth/userinfo.email" + " https://www.googleapis.com/auth/plus.profile.agerange.read";
accessToken1 = GoogleAuthUtil.getToken(context,
accountname,
scope);
return accessToken1;
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
//TODO: HANDLE
Log.e(TAG, "transientEx");
transientEx.printStackTrace();
accessToken1 = null;
} catch (UserRecoverableAuthException e) {
// Recover
Log.e(TAG, "UserRecoverableAuthException");
e.printStackTrace();
accessToken1 = null;
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
Log.e(TAG, "GoogleAuthException");
authEx.printStackTrace();
accessToken1 = null;
} catch (Exception e) {
Log.e(TAG, "RuntimeException");
e.printStackTrace();
accessToken1 = null;
throw new RuntimeException(e);
}
Log.wtf(TAG, "Code should not go here");
accessToken1 = null;
return accessToken1;
}
#Override
protected void onPostExecute(String response) {
Log.d(TAG, "Google access token = " + response);
}
}

Getting Exception while Integrating twitter in android

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

Categories

Resources