Open file using Google Drive API's for Android | INTERNAL_ERROR - android

I am trying to use the Google Drive API for Android to open a file. From the following official tutorial, I have the following:
GoogleDriveActivity.class
public class GoogleDriveActivity extends Activity implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private GoogleApiClient mGoogleApiClient;
private int REQUEST_CODE_RESOLUTION = 1;
private int REQUEST_CODE_OPENER = 2;
private ListView filesLv;
private DataBufferAdapter<Metadata> mResultsAdapter;
private String mNextPageToken;
private boolean hasMore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_drive);
filesLv = (ListView) findViewById(R.id.listViewResults);
hasMore = true;
mResultsAdapter = new ResultsAdapter(this);
filesLv.setAdapter(mResultsAdapter);
filesLv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int first, int visible, int total) {
if (mNextPageToken != null && first + visible + 5 < total) {
retrieveNextPage();
}
}
});
}
private void retrieveNextPage() {
// retrieve the results for the next page.
Query query = new Query.Builder()
.setPageToken(mNextPageToken)
.build();
Drive.DriveApi.query(mGoogleApiClient, query)
.setResultCallback(metadataBufferCallback);
}
private final ResultCallback<DriveApi.MetadataBufferResult> metadataBufferCallback = new
ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(DriveApi.MetadataBufferResult result) {
if (!result.getStatus().isSuccess()) {
return;
}
mResultsAdapter.clear();
mResultsAdapter.append(result.getMetadataBuffer());
mNextPageToken = result.getMetadataBuffer().getNextPageToken();
hasMore = mNextPageToken != null;
}
};
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!connectionResult.hasResolution()) {
return;
}
try {
connectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (IntentSender.SendIntentException e) {
}
}
#Override
public void onConnected(Bundle bundle) {
retrieveNextPage();
}
#Override
public void onConnectionSuspended(int i) {
}
}
The ResultsAdapter.class:
public class ResultsAdapter extends DataBufferAdapter<Metadata> {
public ResultsAdapter(Context context) {
super(context, android.R.layout.simple_list_item_1);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(getContext(),
android.R.layout.simple_list_item_1, null);
}
Metadata metadata = getItem(position);
TextView titleTextView =
(TextView) convertView.findViewById(android.R.id.text1);
titleTextView.setText(metadata.getTitle());
return convertView;
}
}
I am including the dependency in the Gradle file like this:
compile 'com.google.android.gms:play-services-drive:7.8.0'
The Activity in the Manifest.xml looks like the following:
<activity
android:name="com.myproject.GoogleDriveActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<meta-data android:name="com.google.android.apps.drive.APP_ID" android:value="id=<google project number>"/>
</activity>
Please note that I have added the SHA1 to the Google API condole with the package name. Also, the fields in the content screen are filled out as explained here.
When I try to run this code, I keep getting the following error message in the onConnectionFailed callback:
{statusCode=INTERNAL_ERROR, resolution=null}
Any idea on what could be going wrong? I am not able to figure out what the problem is.

I found an answer. The problem was the debug key. Essentially, I ran the keytool command and generated the SHA1 which I then added to the API console on Google. I then ran the project from Android Studio. This was giving me the error.
I then created a new keystore from Android Studio -> Menu -> Build -> Generate signed apk. Ran the same command to generate SHA1 which I uploaded to the API console. Then with the updated apk file, I was able to get the contents of the file.
The problem was that the key could not be authenticated by Google.

Related

Getting Google Cast v3 to work on unsupported devices

The Cast V3 framework has features which try to make it possible to run on devices without the Google Play Services required for it to work, but I ran into some issues when testing.
On the Kindle the Google API returns SERVICE_INVALID with a isUserResolvable() true.
On devices with the onActivityResult returning ConnectionResult.SUCCESS after upgrade, the CastContext.getSharedInstance() can throw RuntimeError.
As a side-effect of 2), the XML inflate of items containing MiniControllerFragment will fail.
Some errors I found were
java.lang.RuntimeException: Unable to start activity ComponentInfo{##########.MainActivity}: android.view.InflateException: Binary XML file line #42: Error inflating class fragment
Caused by: java.lang.RuntimeException:
com.google.android.gms.dynamite.DynamiteModule$zzc: Remote load failed. No local fallback found.
at com.google.android.gms.internal.zzauj.zzan(Unknown Source)
at com.google.android.gms.internal.zzauj.zza(Unknown Source)
at com.google.android.gms.cast.framework.CastContext.<init>(Unknown Source)
at com.google.android.gms.cast.framework.CastContext.getSharedInstance(Unknown Source)
at com.google.android.gms.cast.framework.media.uicontroller.UIMediaController.<init>(Unknown Source)
at com.google.android.gms.cast.framework.media.widget.MiniControllerFragment.onCreateView(Unknown Source)
This was caused by the inflation of the MiniControllerFragment, on a device where the CastController code wasn't installed. This is similar to the question asked SO : Cast v3 is crashing on devices below 5.0. The answer provided by Kamil Ślesiński helped in my investigation.
and
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=123, result=0, data=null} to activity #####
When I had implemented my ViewStub, I was still crashing in the pre-release test machines, as they were returning SUCCESS, but didn't have the CastContext available. To fix this, I needed another test to check if the CastContext was creatable.
You need a singleton / code in the Application something like below....
boolean gCastable = false;
boolean gCastTested = false;
public boolean isCastAvailable(Activity act, int resultCode ){
if( gCastTested == true ){
return gCastable;
}
GoogleApiAvailability castApi = GoogleApiAvailability.getInstance();
int castResult = castApi.isGooglePlayServicesAvailable(act);
switch( castResult ) {
case ConnectionResult.SUCCESS:
gCastable = true;
gCastTested = true;
return true;
/* This code is needed, so that the user doesn't get a
*
* your device is incompatible "OK"
*
* message, it isn't really "user actionable"
*/
case ConnectionResult.SERVICE_INVALID: // Result from Amazon kindle - perhaps check if kindle first??
gCastable = false;
gCastTested = true;
return false;
////////////////////////////////////////////////////////////////
default:
if (castApi.isUserResolvableError(castResult)) {
castApi.getErrorDialog(act, castResult, resultCode, new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
gCastable = false;
gCastTested = false;
return;
}
}).show();
} else {
gCastTested = true;
gCastable = false;
return false;
}
}
return gCastable;
}
public void setCastOK(Activity mainActivity, boolean result ) {
gCastTested = true;
gCastable = result;
}
and a helper function to check if we know the state of the cast.
public boolean isCastAvailableKnown() {
return gCastable;
}
However to cope with devices which return SUCCESS, I also needed the following code in the App / singleton.
When the Activity receives the cast result, we create a CastContext. The "hope" is, if the Application can create the CastContext, then the framework will succeed in the same way (the cause of the crash).
public boolean onCastResultReceived( Activity act, int result ) {
boolean wasOk = false;
if( result == ConnectionResult.SUCCESS ){
try {
CastContext ctx = CastContext.getSharedInstance(act );
wasOk = true;
} catch ( RuntimeException e ){
wasOk = false;
}
}
if( wasOk ) {
setCastOK(act, true);
return true;
}else {
setCastOK(act, false );
return false;
}
}
The inflation of the mini controller is disabled by using a ViewStub and a fragment...
Fragment mini_controller_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cast_mini_controller"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:visibility="gone"
app:castShowImageThumbnail="true"
class="com.google.android.gms.cast.framework.media.widget.MiniControllerFragment" />
With usage something like this....
<ViewStub
android:id="#+id/cast_mini_controller"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout="#layout/mini_controller_fragment"
/>
Activity
An Activity's interaction with the cast components looks something like this...
/* called when we have found out that cast is compatible. */
private void onCastAvailable() {
ViewStub miniControllerStub = (ViewStub) findViewById(R.id.cast_mini_controller);
miniControllerStub.inflate(); // only inflated if Cast is compatible.
mCastStateListener = new CastStateListener() {
#Override
public void onCastStateChanged(int newState) {
if (newState != CastState.NO_DEVICES_AVAILABLE) {
showIntroductoryOverlay();
}
if (mQueueMenuItem != null) {
mQueueMenuItem.setVisible(
(mCastSession != null) && mCastSession.isConnected());
}
}
};
mCastContext = CastContext.getSharedInstance(this);
if (mCastSession == null) {
mCastSession = mCastContext.getSessionManager()
.getCurrentCastSession();
}
if (mQueueMenuItem != null) {
mQueueMenuItem.setVisible(
(mCastSession != null) && mCastSession.isConnected());
}
}
private void showIntroductoryOverlay() {
if (mOverlay != null) {
mOverlay.remove();
}
if ((mediaRouteMenuItem != null) && mediaRouteMenuItem.isVisible()) {
new Handler().post(new Runnable() {
#Override
public void run() {
mOverlay = new IntroductoryOverlay.Builder(
MainActivity.this, mediaRouteMenuItem)
.setTitleText(getString(R.string.introducing_cast))
.setOverlayColor(R.color.primary)
.setSingleTime()
.setOnOverlayDismissedListener(
new IntroductoryOverlay.OnOverlayDismissedListener() {
#Override
public void onOverlayDismissed() {
mOverlay = null;
}
})
.build();
mOverlay.show();
}
});
}
}
onCreate modified as below...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mApp = (MyApplication)getApplication();
if( mApp.isCastAvailable( (Activity)this, GPS_RESULT )) {
onCastAvailable();
}
...
}
onActivityResult needs to cope with the result from the Google Play Services upgrade...
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == GPS_RESULT ) {
if(mApp.onCastResultReceived( this, resultCode ) ){
onCastAvailable();
}
onResume
protected void onResume() {
if( mCastContext != null && mCastStateListener != null ) {
mCastContext.addCastStateListener(mCastStateListener);
mCastContext.getSessionManager().addSessionManagerListener(
mSessionManagerListener, CastSession.class);
if (mCastSession == null) {
mCastSession = CastContext.getSharedInstance(this).getSessionManager()
.getCurrentCastSession();
}
if (mQueueMenuItem != null) {
mQueueMenuItem.setVisible(
(mCastSession != null) && mCastSession.isConnected());
}
}
super.onResume();
}
onPause
protected void onPause() {
super.onPause();
if( mCastContext != null && mCastStateListener != null ) {
mCastContext.removeCastStateListener(mCastStateListener);
mCastContext.getSessionManager().removeSessionManagerListener(
mSessionManagerListener, CastSession.class);
}
}
The session Manager listener in the class...
private final SessionManagerListener<CastSession> mSessionManagerListener =
new MySessionManagerListener();
private class MySessionManagerListener implements SessionManagerListener<CastSession> {
#Override
public void onSessionEnded(CastSession session, int error) {
if (session == mCastSession) {
mCastSession = null;
}
invalidateOptionsMenu();
}
#Override
public void onSessionResumed(CastSession session, boolean wasSuspended) {
mCastSession = session;
invalidateOptionsMenu();
}
#Override
public void onSessionStarted(CastSession session, String sessionId) {
mCastSession = session;
invalidateOptionsMenu();
}
#Override
public void onSessionStarting(CastSession session) {
}
#Override
public void onSessionStartFailed(CastSession session, int error) {
}
#Override
public void onSessionEnding(CastSession session) {
}
#Override
public void onSessionResuming(CastSession session, String sessionId) {
}
#Override
public void onSessionResumeFailed(CastSession session, int error) {
}
#Override
public void onSessionSuspended(CastSession session, int reason) {
}
}
UI interaction
Finally I could change the UI when cast was available by calling the "known" function in my Application...
int visibility = View.GONE;
if( mApplication.isCastAvailableKnown( ) ) {
CastSession castSession = CastContext.getSharedInstance(mApplication).getSessionManager()
.getCurrentCastSession();
if( castSession != null && castSession.isConnected() ){
visibility = View.VISIBLE;
}
}
viewHolder.mMenu.setVisibility( visibility);

How to detect physical key click in a android wearable?

I am using sony smartwatch 3 and it has a power button which I want to control or say manipulate.
I have already tried using :
onKeyDown()
onKeyUp()
onKeyLongPress()
but with no success it doesn't even detect the press of key.
I have also tried using dispatchkeyevent(keyevent event) and shouldOverrideKeyEvent(keyevent event)but again no success.
Please guide.
You need to initialize and connect with GoogleApiClient. Once you clicks the button you have to get list of nodes and send a message to them. The last step is to read this message fron phone part of app, this can be done by registering proper WearableListenerService. Please see the sample code below.
Wearable App:
public class WearableButtonActivity extends Activity {
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wearable_button_activity);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
}
public void onButtonClicked(View target) {
if (mGoogleApiClient == null)
return;
final PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient);
nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult result) {
final List<Node> nodes = result.getNodes();
if (nodes != null) {
for (int i=0; i<nodes.size(); i++) {
final Node node = nodes.get(i);
// You can just send a message
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), "/MESSAGE", null);
// or you may want to also check check for a result:
// final PendingResult<SendMessageResult> pendingSendMessageResult = Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), "/MESSAGE", null);
// pendingSendMessageResult.setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
// public void onResult(SendMessageResult sendMessageResult) {
// if (sendMessageResult.getStatus().getStatusCode()==WearableStatusCodes.SUCCESS) {
// // do something is successed
// }
// }
// });
}
}
}
});
}
}
Listener:
findViewById(R.id.button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onButtonClicked(v);
}
});
Phone App:
public class DataLayerListenerService extends WearableListenerService {
#Override
public void onMessageReceived(MessageEvent messageEvent) {
super.onMessageReceived(messageEvent);
if("/MESSAGE".equals(messageEvent.getPath())) {
// launch some Activity or do anything you like
}
}
}

Android is messing up my views by redrawing the same element without any invalidation

Due to some issue, ALL ACTIVITIES in my app are being redrawn and look something similar to the image below. A hacky workaround for me was to add an ImageView as the lowest layer, with the same height and width as parent and use it as a background, which seems to stop this issue from happening. I am attaching the code from one activity here, but please note, this happens across all activities, regardless of the activity extended the BaseActivity class.
The BaseActivityClass is as follows:
public class BaseActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener {
protected GoogleApiClient mGoogleApiClient;
protected Firebase.AuthStateListener mAuthListener;
protected Firebase mFirebaseRef;
protected FirebaseWrapper mFirebaseWrapper;
protected String mProvider;
protected String mEmail;
protected GSharedPreferences mSharedPref;
protected Location mCurrentLocation = null;
// Permission related variables
protected static final int FINE_LOCATION = 100;
protected View mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSharedPref = GSharedPreferences.getInstance();
// Allow google logins
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
// Create new Client API
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(LocationServices.API)
.build();
mFirebaseWrapper = FirebaseWrapper.getInstance(mGoogleApiClient);
mGoogleApiClient.connect();
if (!((this instanceof LoginActivity) || (this instanceof CreateAccountActivity))) {
mFirebaseRef = new Firebase(Constants.FIREBASE_URL);
mAuthListener = new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
if (authData == null) {
kickUserOut();
}
}
};
mFirebaseRef.addAuthStateListener(mAuthListener);
}
// Get the provider and email if set. A null value means the user is not yet authenticated.
mEmail = mSharedPref.getPreference(Constants.ID_SHAREDPREF_EMAIL);
mProvider = mSharedPref.getPreference(Constants.ID_SHAREDPREF_PROVIDER);
requestAllPermissions();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public void onDestroy() {
super.onDestroy();
// The Auth listener is created only when the user is not a part of the login or
// create account activity, do the cleanup only in such cases.
if (!((this instanceof LoginActivity) || (this instanceof CreateAccountActivity))) {
mFirebaseRef.removeAuthStateListener(mAuthListener);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_base, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
super.onBackPressed();
return true;
}
if (id == R.id.action_logout) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
protected void onResume() {
super.onResume();
mSharedPref.writePreference(Constants.CAN_SHOW_NOTIFICATION, Constants.NO);
// mSharedPref.writePreference(Constants.ID_SHAREDPREF_CANGOOFFLINE, Constants.NO);
}
#Override
protected void onPause() {
super.onPause();
mSharedPref.writePreference(Constants.CAN_SHOW_NOTIFICATION, Constants.YES);
}
/**
* This is called from the child activities that are not associated
* with login or account creation flows.
*/
protected void logout() {
Toast.makeText(this, "Attemping to logout.", Toast.LENGTH_LONG);
// mProvider is set only after the user logs in successfully.
if (mProvider != null) {
mFirebaseRef.unauth();
if (mProvider.equals(Constants.GOOGLE_AUTH_PROVIDER)) {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
// We do not intend to do anything after logout.
// Ignore.
}
});
}
}
}
private void kickUserOut() {
mSharedPref.clear();
// Shared prefs store data about email, clear that and kick users out by moving them
// to login screen.
Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
protected void showToast(String aText) {
Toast.makeText(this, aText, Toast.LENGTH_SHORT).show();
}
public void requestAllPermissions() {
mLayout = findViewById(R.id.main_layout);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
Log.i("MainActivity",
"Displaying location permission rationale to provide additional context.");
Snackbar.make(mLayout, R.string.permission_location_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(BaseActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
FINE_LOCATION);
}
})
.show();
} else {
// Location permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
FINE_LOCATION);
}
}
}
protected LatLng getCurrentLocation()
{
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
float lat = (float) (currentLocation == null ? -190.00: currentLocation.getLatitude());
float lon = (float) (currentLocation == null ? -190.00: currentLocation.getLongitude());
return new LatLng(lat, lon);
}
}
I have a PreferenceActivity, which has the same issue and looks like the image attached.
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.activity_settings);
}
}
}
Doing the following (adding ImageView as the first child, encompassing the whole view as background) fixes this issue.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_layout">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerCrop"
android:src="#drawable/bg2"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/list_view_actions_list"
android:drawSelectorOnTop="true"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:dividerHeight="2dp"
android:scrollbars="none" />
</LinearLayout>
</RelativeLayout>
I would appreciate any hints/leads as to what could I have done wrong and how to fix this. If I give an ImageView as a background, then everything works, but I don't want to always stick to a hacky way of fixing the issue. Moreover, the ImageView fix works only when it's a RelativeLayout.
(Incase you are interested in seeing my code it's hosted on github.
My code is hosted at https://github.com/neerajcse/dstudio/.

How to dismiss initial account manager dialog in google plus android?

Hi I am using google plus. when I click button, it need to display email and other information. But problem is if user has multiple account, without clicking button, dialog is opening. After dismissing dialog and click button, once again dialog is opening and working fine. I couldn't find this strange issue.
When i launch screen, without clicking button, choose an account dialog is opening. How to solve this?
Here is my code: I am using fragments.
public class LoginFragment extends SherlockFragment implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Common.mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
Common.mGoogleApiClient.connect();
return view;
}
public void onStop() {
super.onStop();
if (Common.mGoogleApiClient.isConnected()) {
Common.mGoogleApiClient.disconnect();
}
}
}
Common:
public class Common {
static int RC_SIGN_IN = 0;
static String TAG = "MainActivity";
static int PROFILE_PIC_SIZE = 400;
static GoogleApiClient mGoogleApiClient;
static boolean mIntentInProgress;
static boolean mSignInClicked;
static ConnectionResult mConnectionResult;
static Activity con;
public Common(Activity c) {
con = c;
}
LoginActivity:
public class LoginActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
public void resolveSignInError() {
if (Common.mConnectionResult != null) {
if (Common.mConnectionResult.hasResolution()) {
try {
Common.mIntentInProgress = true;
Common.mConnectionResult.startResolutionForResult(
Common.con, Common.RC_SIGN_IN);
} catch (SendIntentException e) {
Common.mIntentInProgress = false;
Common.mGoogleApiClient.connect();
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent data) {
super.onActivityResult(requestCode, responseCode, data);
if (requestCode == Common.RC_SIGN_IN) {
if (responseCode != Common.con.RESULT_OK) {
Common.mSignInClicked = false;
}
Common.mIntentInProgress = false;
if (!Common.mGoogleApiClient.isConnecting()) {
Common.mGoogleApiClient.connect();
}
}
}
}
Here is screenshot where without clicking google plus button, dialog pop up.

my Google+1 button is grayed out and not working?

i was trying to integrate G+ button in ma app.The G+ buttons grayed out.and its not counting.how to turns red ?
public class HomeActivity extends SherlockActivity implements ConnectionCallbacks, OnConnectionFailedListener{
private static final String URL = "https://play.google.com/store/apps/details?id=com.phoneix.allu";
private static final int PLUS_ONE_REQUEST_CODE = 0;
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
private PlusOneButton mPlusOneStandardButton;
#Override
public void onCreate(Bundle pBundle) {
super.onCreate(pBundle);
setContentView(R.layout.dashboard);
mPlusOneStandardButton = (PlusOneButton) findViewById(R.id.plus_one_standard_button);
mPlusClient = new PlusClient.Builder(this, this, this)
.build();
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
// Refresh the state of the +1 button each time we receive focus.
mPlusOneStandardButton.initialize(URL, PLUS_ONE_REQUEST_CODE);
}
#Override
public void onDisconnected() {
// Nothing to do.
}
#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;
}
public void onConnected(Bundle connectionHint) {
mPlusOneStandardButton.initialize(URL, PLUS_ONE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
}
Try out this:
In xml file:
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="92dp" >
</com.google.android.gms.common.SignInButton>
</RelativeLayout>
In your activity get that button:
#Override
public void onCreate(Bundle pBundle) {
super.onCreate(pBundle);
setContentView(R.layout.dashboard);
findViewById(R.id.sign_in_button).setOnClickListener(new OnClickListener() {
#Override
public void onClick
(View v) {
Intent i = new Intent(getApplicationContext(),YourActivity.class);
startActivity(i);
}
});
}
The problem is with the latest update of google play services.
Once I uninstalled all updates of google play services from app's settings,all +1 buttons are showing up fine.
Let's hope google will fix their update.
The new Google Play update changed the interface of the plusOne button, hence breaking all plusOne button based on the "old" Google play service SDK.
If you checkout their samples, you'll discover they have changed the interface for the plusOnButton.initialize, which no longer takes a "plusOneClient", but a URL.
To fix, download the latest (v13) Google Play Services using your "Android SDK Manager", and import it back to your project.

Categories

Resources