Not getting friends list in google plus android - android

I want to get user circle's list of visible friends name and email address with Google Plus.
I have done following code and tried with 4 to 5 phone but in all I am getting zero list
class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener, ResultCallback<People.LoadPeopleResult> {
private static final int RC_SIGN_IN = 22;
private static final String TAG = null;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.addScope(Plus.SCOPE_PLUS_PROFILE)
.build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle arg0) {
System.out.println("onConnected");
Plus.PeopleApi.loadVisible(mGoogleApiClient, null).setResultCallback(
this);
}
#Override
public void onResult(LoadPeopleResult peopleData) {
System.out.println("onResult");
if (peopleData.getStatus().getStatusCode() == CommonStatusCodes.SUCCESS) {
PersonBuffer personBuffer = peopleData.getPersonBuffer();
try {
System.out.println("PersonBuffer : - "
+ personBuffer.getCount()); <=======HERE I AM GETTING ALWAYS 0
int count = personBuffer.getCount();
for (int i = 0; i < count; i++) {
Log.d(TAG, "Display name: "
+ personBuffer.get(i).getDisplayName());
}
} finally {
personBuffer.close();
}
} else {
Log.e(TAG,
"Error requesting visible circles: "
+ peopleData.getStatus());
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}

Please check the following cases below
On the Consent Screen, you don't select circle which allow to see in your app
1.1 When the consent screen is showing after login to google+ in your app,
Click on the first sentence 'Know your basic profile info and list of people in your circle'
1.2 Be sure that you select 'All circles', or any non-empty circle
Your google+ account was set disallow your app to see the people in circle
2.1 Open Google+ app
2.2 Select 'Settings'
2.3 In the 'Account Settings' section, Select your account
2.4 Select 'Apps with Google+ Sign-in'
2.5 Select 'All apps & devices'
2.6 Select your app
2.7 In the 'This app can see these people', Be sure that it select 'All circles' or any non-empty circle.
2.8 For more detail, see the 'Change your Google+ Sign-In settings', In the 'Manage who in your circles the app can view' section in link below
https://support.google.com/plus/answer/2980770?hl=en

Related

Android Google Places Photos Search API not working on PlaceId returned from Place Search web service API

I have the following logic:
Server side making Place Search web service call and gets valid unique cross Google maps API's PlaceId string. Check: Constructing manually URL for Place Details from him (returned PlaceId) returns the expected Place indicating that he has photos in Google's places DB (photos[] in the result Json is not empty...).
So now the server sends to Android client this PlaceId and in android I make API call to Places Photos to get at least one image. It should work because PlaceId is unique place identifier across all Google Maps products. The workflow is pretty much straight forward based on official Google sample, and as seen in the comments in the code the connection part is succeeding and all API set up is good (in the dev console, manifest with API KEY etc.).
The problem is that it's not working: In dev console I see usage count increasing and in the place in the code where I expect to fetch the image nothing happens - The result is that any PlaceId I try (and as mentioned above should have photos) don't have any photos in Google's DB. Also ain't exceptions or something like this to debug. Where is the problem? Thanks,
//Under Activity extends FragmentActivity implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks
private GoogleApiClient mGoogleApiClient = null;
private boolean isConnected = false;
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
/* Regular code... */
//Next 2 lines: I don't for what they are good - But in the official Google sample
//they appears - So probably it's right...
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if (mGoogleApiClient == null) {
rebuildGoogleApiClient();
}
if (isConnected) {
/* This is printed! */
Log.e("TAG", "Start of API Call");
String placeId = /* Call to my server, the result is 100% valid PlaceId that has photos*/
placePhotosTask(placeId, 800, 400); //Height, Width
}
}
private void placePhotosTask(final String placeId, final int width, final int height) {
new PhotoTask(width, height) {
#Override
protected void onPreExecute() {
//TODO Display a temporary image to show while bitmap is loading.
//mImageView.setImageResource(R.drawable.empty_photo);
}
#Override
protected void onPostExecute(AttributedPhoto attributedPhoto) {
if (attributedPhoto != null) {
/* THIS IS NOT PRINTED */
Log.e("TAG", "Success of API Call");
mImageView.setImageBitmap(attributedPhoto.bitmap);
}
}
}.execute(placeId);
}
private class PhotoTask extends AsyncTask<String, Void, PhotoTask.AttributedPhoto> {
private int mHeight;
private int mWidth;
public PhotoTask(int width, int height) {
mHeight = height;
mWidth = width;
}
//Loads the first photo for a place id from the Geo Data API. The place id must be the first (and only) parameter.
#Override
protected AttributedPhoto doInBackground(String... params) {
if (params.length != 1) {
return null;
}
final String placeId = params[0];
AttributedPhoto attributedPhoto = null;
PlacePhotoMetadataResult result = Places.GeoDataApi.getPlacePhotos(mGoogleApiClient, placeId).await();
if (result.getStatus().isSuccess()) {
PlacePhotoMetadataBuffer photoMetadataBuffer = result.getPhotoMetadata();
//BUG!: photoMetadataBuffer.getCount() == 0 Always!
if (photoMetadataBuffer.getCount() > 0 && !isCancelled()) {
//Get the first bitmap and its attributions.
PlacePhotoMetadata photo = photoMetadataBuffer.get(0);
CharSequence attribution = photo.getAttributions();
//Load a scaled bitmap for this photo.
Bitmap image = photo.getScaledPhoto(mGoogleApiClient, mWidth, mHeight).await().getBitmap();
attributedPhoto = new AttributedPhoto(attribution, image);
}
//Release the PlacePhotoMetadataBuffer.
photoMetadataBuffer.release();
}
return attributedPhoto;
}
//Holder for an image and its attribution.
class AttributedPhoto {
public final CharSequence attribution;
public final Bitmap bitmap;
public AttributedPhoto(CharSequence attribution, Bitmap bitmap) {
this.attribution = attribution;
this.bitmap = bitmap;
}
}
}
protected synchronized void rebuildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0 /* clientId */, this)
.addConnectionCallbacks(this)
.addApi(Places.GEO_DATA_API)
.build();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
isConnected = false;
}
#Override
public void onConnected(Bundle bundle) {
isConnected = true;
}
#Override
public void onConnectionSuspended(int i) {
isConnected = false;
}
I disagree with the bug comment - photoMetadataBuffer.getCount() == 0 Always. Here is some code that shows loading photos successfully. Note, for context, this code was built inside the Android Studio Google Maps template app, to make it easier to get all the API Key configuration correctly inserted in the application, with the bonus of having a map for displaying results.
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private final String placeId = "ChIJhSxoJzyuEmsR9gBDBR09ZrE";
private final static String TAG = "MapsActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId).setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
if (places.getStatus().isSuccess() && places.getCount() > 0) {
final Place myPlace = places.get(0);
Log.i(TAG, "Place found: " + myPlace.getName());
mMap.addMarker(new MarkerOptions()
.position(myPlace.getLatLng())
.title(myPlace.getName().toString())
.snippet(myPlace.getAddress().toString()));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPlace.getLatLng()));
}
places.release();
}
});
Places.GeoDataApi.getPlacePhotos(mGoogleApiClient, placeId).setResultCallback(new ResultCallback<PlacePhotoMetadataResult>() {
#Override
public void onResult(PlacePhotoMetadataResult placePhotoMetadataResult) {
if (placePhotoMetadataResult.getStatus().isSuccess()) {
PlacePhotoMetadataBuffer photoMetadata = placePhotoMetadataResult.getPhotoMetadata();
int photoCount = photoMetadata.getCount();
for (int i = 0; i<photoCount; i++) {
PlacePhotoMetadata placePhotoMetadata = photoMetadata.get(i);
final String photoDetail = placePhotoMetadata.toString();
placePhotoMetadata.getScaledPhoto(mGoogleApiClient, 500, 500).setResultCallback(new ResultCallback<PlacePhotoResult>() {
#Override
public void onResult(PlacePhotoResult placePhotoResult) {
if (placePhotoResult.getStatus().isSuccess()) {
Log.i(TAG, "Photo "+photoDetail+" loaded");
} else {
Log.e(TAG, "Photo "+photoDetail+" failed to load");
}
}
});
}
photoMetadata.release();
} else {
Log.e(TAG, "No photos returned");
}
}
});
}

Android Wear disconnection notification

I have an Android Wear app which communicates accelerometer values to an Handheld app.
I want to be notified in the Handheld app when connection with the android wear app has just been lost (when the Android Wear app is closed, for instance).
How must I implement that ?
Thank you for your help
Devices connected in the wear-to-device network are called Nodes. You can use the Node API to determine when devices enter or leave the network (e.g. when a wear device becomes disconnected from a phone).
https://developers.google.com/android/reference/com/google/android/gms/wearable/NodeApi.NodeListener
You can also use the Node API to get a list of all connected devices (e.g all wear devices connected to a phone) at any given time
https://developers.google.com/android/reference/com/google/android/gms/wearable/NodeApi
You can easily do this by extends the WearableListenerService and override onConnectedNodes() method.
Wearable Side
public class DisconnectListenerService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks {
/* the capability that the phone app would provide */
private static final String CONNECTION_STATUS_CAPABILITY_NAME = "is_connection_lost";
private GoogleApiClient mGoogleApiClient;
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.build();
}
#Override
public void onConnectedNodes(List<Node> connectedNodes) {
if (mGoogleApiClient.isConnected()) {
updateStatus();
} else if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
private void updateStatus() {
Wearable.CapabilityApi.getCapability(
mGoogleApiClient, CONNECTION_STATUS_CAPABILITY_NAME,
CapabilityApi.FILTER_REACHABLE).setResultCallback(
new ResultCallback<CapabilityApi.GetCapabilityResult>() {
#Override
public void onResult(CapabilityApi.GetCapabilityResult result) {
if (result.getStatus().isSuccess()) {
updateConnectionCapability(result.getCapability());
} else {
Log.e(TAG, "Failed to get capabilities, " + "status: " + result.getStatus().getStatusMessage());
}
}
});
}
private void updateConnectionCapability(CapabilityInfo capabilityInfo) {
Set<Node> connectedNodes = capabilityInfo.getNodes();
if (connectedNodes.isEmpty()) {
// The connection is lost !
} else {
for (Node node : connectedNodes) {
if (node.isNearby()) {
// The connection is OK !
}
}
}
}
#Override
public void onConnected(Bundle bundle) {
updateStatus();
}
#Override
public void onConnectionSuspended(int cause) {
}
#Override
public void onDestroy() {
if (mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting()) {
mGoogleApiClient.disconnect();
}
super.onDestroy();
}
}
Phone Side
create a xml file in values/ directory named wear.xml
<resources>
<string-array name="android_wear_capabilities">
<item>is_connection_lost</item>
</string-array>
</resources>

onConnectionFailed: ConnectionResult.getErrorCode() = 4

Here i am doing google + integartion.i am using the following code but i am facing the error which is : onConnectionFailed: ConnectionResult.getErrorCode() = 4.So please anybody help me and tell me what i am doing wrong in this code and provide me the solution for this.i will be very thankful to you.I searched a lot but found nothing.I am using the quick sample of Google plus.There is also another problem i am not able to personal information like birthday etc in this code.
public class GooglePlus extends FragmentActivity implements
ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener {
String fb_userId, fb_username;
SharedPreferences pref;
SharedPreferences.Editor editor;
private static final int STATE_DEFAULT = 0;
private static final int STATE_SIGN_IN = 1;
private static final int STATE_IN_PROGRESS = 2;
private static final int RC_SIGN_IN = 0;
private static final int DIALOG_PLAY_SERVICES_ERROR = 0;
private static final String SAVED_PROGRESS = "sign_in_progress";
// GoogleApiClient wraps our service connection to Google Play services and
// provides access to the users sign in state and Google's APIs.
private GoogleApiClient mGoogleApiClient;
// We use mSignInProgress to track whether user has clicked sign in.
// mSignInProgress can be one of three values:
//
// STATE_DEFAULT: The default state of the application before the user
// has clicked 'sign in', or after they have clicked
// 'sign out'. In this state we will not attempt to
// resolve sign in errors and so will display our
// Activity in a signed out state.
// STATE_SIGN_IN: This state indicates that the user has clicked 'sign
// in', so resolve successive errors preventing sign in
// until the user has successfully authorized an account
// for our app.
// STATE_IN_PROGRESS: This state indicates that we have started an intent to
// resolve an error, and so we should not start further
// intents until the current intent completes.
private int mSignInProgress;
// Used to store the PendingIntent most recently returned by Google Play
// services until the user clicks 'sign in'.
private PendingIntent mSignInIntent;
// Used to store the error code most recently returned by Google Play
// services
// until the user clicks 'sign in'.
private int mSignInError;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_plus);
pref = PreferenceManager.getDefaultSharedPreferences(this);
if (savedInstanceState != null) {
mSignInProgress = savedInstanceState.getInt(SAVED_PROGRESS,
STATE_DEFAULT);
}
mGoogleApiClient = buildGoogleApiClient();
Handler handle = new Handler();
handle.postDelayed(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// resolveSignInError();
}
});
}
}, 1500);
}
private GoogleApiClient buildGoogleApiClient() {
// When we build the GoogleApiClient we specify where connected and
// connection failed callbacks should be returned, which Google APIs our
// app uses and which OAuth 2.0 scopes our app requests.
return new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SAVED_PROGRESS, mSignInProgress);
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes
// might
// be returned in onConnectionFailed.
Log.i("", "onConnectionFailed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
if (mSignInProgress != STATE_IN_PROGRESS) {
// We do not have an intent in progress so we should store the
// latest
// error resolution intent for use when the sign in button is
// clicked.
mSignInIntent = result.getResolution();
mSignInError = result.getErrorCode();
if (mSignInProgress == STATE_SIGN_IN) {
// STATE_SIGN_IN indicates the user already clicked the sign in
// button
// so we should continue processing errors until the user is
// signed in
// or they click cancel.
resolveSignInError();
}
}
// In this sample we consider the user signed out whenever they do not
// have
// a connection to Google Play services.
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
/*
* Starts an appropriate intent or dialog for user interaction to resolve
* the current error preventing the user from being signed in. This could be
* a dialog allowing the user to select an account, an activity allowing the
* user to consent to the permissions being requested by your app, a setting
* to enable device networking, etc.
*/
private void resolveSignInError() {
if (mSignInIntent != null) {
// We have an intent which will allow our user to sign in or
// resolve an error. For example if the user needs to
// select an account to sign in with, or if they need to consent
// to the permissions your app is requesting.
try {
// Send the pending intent that we stored on the most recent
// OnConnectionFailed callback. This will allow the user to
// resolve the error currently preventing our connection to
// Google Play services.
mSignInProgress = STATE_IN_PROGRESS;
startIntentSenderForResult(mSignInIntent.getIntentSender(),
RC_SIGN_IN, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.i("",
"Sign in intent could not be sent: "
+ e.getLocalizedMessage());
// The intent was canceled before it was sent. Attempt to
// connect to
// get an updated ConnectionResult.
mSignInProgress = STATE_SIGN_IN;
mGoogleApiClient.connect();
}
} else {
// Google Play services wasn't able to provide an intent for some
// error types, so we show the default Google Play services error
// dialog which may still start an intent on our behalf if the
// user can resolve the issue.
showDialog(DIALOG_PLAY_SERVICES_ERROR);
}
}
#SuppressWarnings("unused")
#Override
public void onConnected(Bundle arg0) {
// Reaching onConnected means we consider the user signed in.
Log.i("onConnected", "onConnected");
// Retrieve some profile information to personalize our app for the
// user.
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentUser.getDisplayName();
String personPhotoUrl = currentUser.getImage().getUrl();
String personGooglePlusProfile = currentUser.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.i("personName", personName);
Log.i("email", email);
Log.i("Gender", "" + currentUser.getGender());
Log.i("Birthday", "" + currentUser.getBirthday());
// Indicate that the sign in process is complete.
mSignInProgress = STATE_DEFAULT;
/*
* fb_userId = currentUser.getId(); fb_username =
* currentUser.getDisplayName(); editor = pref.edit();
* editor.putString("fb_userId", fb_userId);
* editor.putString("fb_username", fb_username);
* editor.putString("social_provider", "google +");
*
* editor.putString("gender", currentUser.getGender());
* editor.putString("birthday", currentUser.getBirthday());
*
* editor.putString("device_name", "android");
*
* editor.putString("email",
* Plus.AccountApi.getAccountName(mGoogleApiClient)); editor.commit();
*/
}
#Override
public void onConnectionSuspended(int arg0) {
// The connection to Google Play services was lost for some reason.
// We call connect() to attempt to re-establish the connection or get a
// ConnectionResult that we can attempt to resolve.
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RC_SIGN_IN:
if (resultCode == RESULT_OK) {
// If the error resolution was successful we should continue
// processing errors.
mSignInProgress = STATE_SIGN_IN;
} else {
// If the error resolution was not successful or the user
// canceled,
// we should stop processing errors.
mSignInProgress = STATE_DEFAULT;
}
if (!mGoogleApiClient.isConnecting()) {
// If Google Play services resolved the issue with a dialog then
// onStart is not called so we need to re-attempt connection
// here.
mGoogleApiClient.connect();
}
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_PLAY_SERVICES_ERROR:
if (GooglePlayServicesUtil.isUserRecoverableError(mSignInError)) {
return GooglePlayServicesUtil.getErrorDialog(mSignInError,
this, RC_SIGN_IN,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
Log.e("",
"Google Play services resolution cancelled");
mSignInProgress = STATE_DEFAULT;
}
});
} else {
return new AlertDialog.Builder(this)
.setMessage(R.string.play_services_error)
.setPositiveButton(R.string.close,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Log.e("",
"Google Play services error could not be "
+ "resolved: "
+ mSignInError);
mSignInProgress = STATE_DEFAULT;
// mStatus.setText(R.string.status_signed_out);
}
}).create();
}
default:
return super.onCreateDialog(id);
}
}
}
I had the same problem. I solved in google api console >> consent screen, and adding a Product Name.
I try this tutorial: http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/
In the main activity you need change .addApi(Plus.API, null) by .addApi(Plus.API, Plus.PlusOptions.builder().build())
For me the problem was that I had not created the credentials for the app.
Went to Google Developers Console > Credentials > Create New Client ID
filled the corresponding package name and SHA1 for my app, reran the app and then it worked!
In case you are using MapView, make sure you are following the guidelines
i.e.
"When using the API in fully interactive mode, users of this class must forward all the activity life cycle methods to the corresponding methods in the MapView class. Examples of the life cycle methods include onCreate(), onDestroy(), onResume(), and onPause(). When using the API in lite mode, forwarding lifecycle events is optional. For details, see the lite mode documentation."
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}

Android Google plus login button doesn't work

I'm trying to implement the login with Google+ in my firt activity of my application. I followed the google dev tutorial but when I click on the SignIn button nothing happens. I think I've made some mistakes, here the code:
public class MainActivity extends FragmentActivity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
public static final String mAPP_ID = "xxxx";
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private static final String TAG = "MainActivity";
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
private ImageButton googleSignOutButton;
AssetsExtracter mTask;
private MainFragment mainFragment;
static {
IMetaioSDKAndroid.loadNativeLibs();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
mPlusClient = new PlusClient.Builder(this, this, this)
.setActions("http://schemas.google.com/AddActivity")
.setScopes(Scopes.PLUS_LOGIN)
.build();
// Progress bar to be displayed if the connection failure is not
// resolved.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
mTask = new AssetsExtracter();
mTask.execute(0);
findViewById(R.id.sign_in_button).setOnClickListener(this);
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(this,
REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the intent so that we can start an activity when the user clicks
// the sign-in button.
mConnectionResult = result;
}
#Override
public void onConnected(Bundle connectionHint) {
// We've resolved any connection errors.
mConnectionProgressDialog.dismiss();
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
}
#Override
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
if (requestCode == REQUEST_CODE_RESOLVE_ERR
&& responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
#Override
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.sign_in_button
&& !mPlusClient.isConnected()) {
if (mConnectionResult == null) {
mConnectionProgressDialog.show();
} else {
try {
mConnectionResult.startResolutionForResult(
getParent(), REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Try connecting again.
mConnectionResult = null;
mPlusClient.connect();
}
}
}
}
}
EDIT:
I've discovered that in the onConncectionFailed() method, if I remove the first "if()" that checks if the processDialog is showing, when the application starts, without clicking anything, a dialog of google+ appears asking me to login. this is strange
EDIT:
I resolved my problem using a normal Button and implementing onClick on it, following the tutorial of Google Dev
Have you registered your application on the Google developers console? You need to make sure your Android application has an associated client ID with the Google+ API enabled.
https://developers.google.com/+/mobile/android/getting-started#step_1_enable_the_google_api
After doing some digging I realised that providing the release SHA-1 to the console only gave me the ability to run my project with a working sign-in button if and only I generated a signed APK and installed the APK manually and not through Android Studio.
I figured changing the SHA-1 to debug was the solution but I wasn't able to change it until now.
To change your SHA-1 from the release version to the debug version so you can install a working/testable apk through Android Studio:
Open Google Cloud Console > Open API Manager > Click on Credentials.
Under OAuth2.0 Client IDs > click Android Client for your app and change the SHA-1 to your debug version (following these instructions should help you to retrieve your debug SHA-1: https://developer.android.com/studio/publish/app-signing.html)
After doing so, save your new credentials in the Cloud Console and return to the screen to generate your configuration file. You should notice your changed SHA-1. Now generate the config file and paste it into app/.. project directory. Clean, rebuild, and run your project and your signin button should now work as expected.

How to add google +1 button in android app

I am having problem while implementing Google +1 button in my android application.
I followed instruction on this link and my activity is showing g+ button successfully but after clicking on button, it is showing a progress bar on the button only, please tell me how +1 button works in android it should open a login internet or what?
I am not implementing signin with google just +1 button in my app. Hhere is my code, this is part of my code so it is not that proper.
public class as {
private static final String URL = "www.app.in";
private static final int PLUS_ONE_REQUEST_CODE = 10;
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
private PlusOneButton mPlusOneButton;
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.product_details);
setCurrentContext(this);
super.onCreate(savedInstanceState);
mPlusOneButton = (PlusOneButton) findViewById(R.id.googleplus);
mPlusClient = new PlusClient.Builder(this, this, this).clearScopes()
.build();
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "OnStart");
mPlusClient.connect();
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop");
mPlusClient.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "onConnectionFailed");
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(this,
REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the result and resolve the connection failure upon a user click.
mConnectionResult = result;
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
Log.d(TAG, "onActivityResult");
if (requestCode == REQUEST_CODE_RESOLVE_ERR
&& responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
#Override
public void onConnected(Bundle connectionHint) {
// String accountName = mPlusClient.getAccountName();
// Toast.makeText(this, accountName + " is connected.",
// Toast.LENGTH_LONG)
// .show();
Log.d(TAG, "onConnected");
}
#Override
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
}
You need to be signed in for this to work, but you do not have to have a sign in button on your app.
If it is enabled (you can click on it) then you are already signed in and I suggest you check that you have specified a valid url.
Your code looks different to mine (I use a GameHelperListener) but as long as you have followed the documentation accurately it should be fine.
If you want to see it work, just download an app that has a +1 button on it, and try it.
Change url like
url="https://market.android.com/details?id=xxx.xxx.xxx";
Also implement methods
ConnectionCallbacks, OnConnectionFailedListener and extends activity

Categories

Resources