Why my button is shown and than quickly hidden onResume - android

It's probably just a silly mistake but I cannot fix it. I have a Google+ sign in a button, which is shown when the user is not logged in. I also have a sign out button, which is GONE when the user is logged in.Everything works except that when I go back to the activity (onResume) I can see the red Google+ button for about a second and than it gets hidden and the sign out button appears. How can I remove this one second during which I can still see the Google+ button ?
This is my layout:
XML code:
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/startGameView"
android:src="#drawable/play"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/startGameView"
android:layout_centerHorizontal="true"
android:layout_marginBottom="46dp">
<!-- show achievements -->
<Button
android:id="#+id/show_achievements"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Achievements"/>
<!-- show leaderboards -->
<Button
android:id="#+id/show_leaderboard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Leaderboard"/>
</LinearLayout>
Code in the activity:
public class StartActivity extends BaseGameActivity implements View.OnClickListener{
private ImageView mPlay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mPlay = (ImageView)findViewById(R.id.startGameView);
mPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//play animations
YoYo.with(Techniques.Pulse)
.duration(200)
.playOn(findViewById(R.id.startGameView));
Intent intent = new Intent(StartActivity.this, MainActivity.class);
startActivity(intent);
}
});
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
findViewById(R.id.show_achievements).setOnClickListener(this);
findViewById(R.id.show_leaderboard).setOnClickListener(this);
//mSignOutButton = (Button)findViewById(R.id.sign_out_button);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_start, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSignInFailed() {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}
#Override
public void onSignInSucceeded() {
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button) {
beginUserInitiatedSignIn();
}else if (view.getId() == R.id.sign_out_button) {
signOut();
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}else if (view.getId() == R.id.show_achievements){
Toast.makeText(StartActivity.this,"achivements",Toast.LENGTH_SHORT).show();
startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), 1);
}else if(view.getId() == R.id.show_leaderboard){
Toast.makeText(StartActivity.this,"leaderboard",Toast.LENGTH_SHORT).show();
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(
getApiClient(), getString(R.string.number_of_solved_math_problems_leaderboard)), 2);
}
}
BaseActivity code:
public abstract class BaseGameActivity extends FragmentActivity implements
GameHelper.GameHelperListener {
// The game helper object. This class is mainly a wrapper around this object.
protected GameHelper mHelper;
// We expose these constants here because we don't want users of this class
// to have to know about GameHelper at all.
public static final int CLIENT_GAMES = GameHelper.CLIENT_GAMES;
public static final int CLIENT_APPSTATE = GameHelper.CLIENT_APPSTATE;
public static final int CLIENT_PLUS = GameHelper.CLIENT_PLUS;
public static final int CLIENT_ALL = GameHelper.CLIENT_ALL;
// Requested clients. By default, that's just the games client.
protected int mRequestedClients = CLIENT_GAMES;
private final static String TAG = "BaseGameActivity";
protected boolean mDebugLog = false;
/** Constructs a BaseGameActivity with default client (GamesClient). */
protected BaseGameActivity() {
super();
}
/**
* Constructs a BaseGameActivity with the requested clients.
* #param requestedClients The requested clients (a combination of CLIENT_GAMES,
* CLIENT_PLUS and CLIENT_APPSTATE).
*/
protected BaseGameActivity(int requestedClients) {
super();
setRequestedClients(requestedClients);
}
/**
* Sets the requested clients. The preferred way to set the requested clients is
* via the constructor, but this method is available if for some reason your code
* cannot do this in the constructor. This must be called before onCreate or getGameHelper()
* in order to have any effect. If called after onCreate()/getGameHelper(), this method
* is a no-op.
*
* #param requestedClients A combination of the flags CLIENT_GAMES, CLIENT_PLUS
* and CLIENT_APPSTATE, or CLIENT_ALL to request all available clients.
*/
protected void setRequestedClients(int requestedClients) {
mRequestedClients = requestedClients;
}
public GameHelper getGameHelper() {
if (mHelper == null) {
mHelper = new GameHelper(this, mRequestedClients);
mHelper.enableDebugLog(mDebugLog);
}
return mHelper;
}
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
if (mHelper == null) {
getGameHelper();
}
mHelper.setup(this);
}
#Override
protected void onStart() {
super.onStart();
mHelper.onStart(this);
}
#Override
protected void onStop() {
super.onStop();
mHelper.onStop();
}
#Override
protected void onActivityResult(int request, int response, Intent data) {
super.onActivityResult(request, response, data);
mHelper.onActivityResult(request, response, data);
}
protected GoogleApiClient getApiClient() {
return mHelper.getApiClient();
}
protected boolean isSignedIn() {
return mHelper.isSignedIn();
}
protected void beginUserInitiatedSignIn() {
mHelper.beginUserInitiatedSignIn();
}
protected void signOut() {
mHelper.signOut();
}
protected void showAlert(String message) {
mHelper.makeSimpleDialog(message).show();
}
protected void showAlert(String title, String message) {
mHelper.makeSimpleDialog(title, message).show();
}
protected void enableDebugLog(boolean enabled) {
mDebugLog = true;
if (mHelper != null) {
mHelper.enableDebugLog(enabled);
}
}
#Deprecated
protected void enableDebugLog(boolean enabled, String tag) {
Log.w(TAG, "BaseGameActivity.enabledDebugLog(bool,String) is " +
"deprecated. Use enableDebugLog(boolean)");
enableDebugLog(enabled);
}
protected String getInvitationId() {
return mHelper.getInvitationId();
}
protected void reconnectClient() {
mHelper.reconnectClient();
}
protected boolean hasSignInError() {
return mHelper.hasSignInError();
}
protected GameHelper.SignInFailureReason getSignInError() {
return mHelper.getSignInError();
}

If you cloned (or refreshed) the samples recently, you'll notice that GameHelper and BaseGameActivity are not longer used. There is an informative video about this change: Game On! - The death of BaseGameActivity. If you just implement the interfaces to get the callbacks for the state: GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener your problem should go away.
More specific details on how to use these interfaces is at https://developers.google.com/games/services/training/signin

As I see in GameHelper class, it disconnects from googleApiClient on onStop() and connect on onStart(). This is causing of blinking buttons.
If you don't want to change GameHelper implementation, make some UI improvement to make it less annoying.

Related

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.

How do I make a google plus button with a custom layout in android?

I want to create a custom layout for my google plus button, any ideas? I've tried calling the OnClickEvent of the google plus button (that doesn't work) and I've tried changing the background image. Source code:
<com.google.android.gms.plus.PlusOneButton
xmlns:plus="http://schemas.android.com/apk/lib/com.google.android.gms.plus"
android:id="#+id/plus_one_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
plus:size="standard"
plus:annotation="inline"/>
holder.mPlusOneButton = (PlusOneButton) holder.content.findViewById(R.id.plus_one_button);
holder.mPlusOneButton.initialize("http://www.xxx.xx/", 0);
Add a custom button to your layout
Set OnClickListener to your custom button
Use the PlusClient as described here to handle the login procedure
As example I can provide my controller class for handling Google Plus login:
public class GooglePlusLoginController implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {
public static final int REQUEST_CODE_SIGN_IN = 100;
private PlusClient googlePlusClient;
private ConnectionResult connectionResult;
private Activity activity;
public GooglePlusLoginController(Activity activity) {
this.activity = activity;
googlePlusClient = new PlusClient.Builder(activity, this, this)
.setActions("http://schemas.google.com/AddActivity")
.setScopes(Scopes.PLUS_LOGIN) // Space separated list of scopes
.build();
googlePlusClient.connect();
}
// call this method in your click handler
public void login() {
try {
connectionResult.startResolutionForResult(activity, REQUEST_CODE_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
googlePlusClient.connect();
}
}
// call this method in your activity's onActivityResult
public void onActivityResult() {
if(!googlePlusClient.isConnected() && !googlePlusClient.isConnecting()) {
googlePlusClient.connect();
}
}
#Override
public void onConnected(Bundle bundle) {
// connected, you can now get user's data from
// googlePlusClient.getCurrentPerson()
}
#Override
public void onDisconnected() {
}
#Override
public void onConnectionFailed(ConnectionResult result) {
connectionResult = result;
}
private void logout() {
if(googlePlusClient.isConnected()) {
googlePlusClient.clearDefaultAccount();
googlePlusClient.disconnect();
googlePlusClient.connect();
}
}
}

Using progress Dialog instead of progress bar in asyncTask

I am trying to implement this tutorial, for handling Configuration changes while running background tasks. Everything works fine, and the app does not crash after a configuration change. In the tutorial, a progress bar is used to display progress. But in my own implementation i want to use a Progress Dialog.
I have used progress Dialog's lots of times, so calling it and getting to appear is not the problem. My problem is that unlike the progress Bar, the progress dialog gets dismissed on configuration change. Just like that.
Here is my code:
My MainActivity:
private TaskFragment mTaskFragment;
private ProgressDialog mProgressDialog;
private TextView mPercent;
private Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate(Bundle)");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Initialize views
mButton = (Button) findViewById(R.id.task_button);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mTaskFragment.isRunning()) {
mTaskFragment.cancel();
} else {
mTaskFragment.start();
}
}
});
mProgressBar = new ProgressDialog(this);
FragmentManager fm = getSupportFragmentManager();
mTaskFragment = (TaskFragment) fm.findFragmentByTag("task");
// If the Fragment is non-null, then it is currently being
// retained across a configuration change.
if (mTaskFragment == null) {
mTaskFragment = new TaskFragment();
fm.beginTransaction().add(mTaskFragment, "task").commit();
}
if (mTaskFragment.isRunning()) {
mButton.setText(getString(R.string.cancel));
} else {
mButton.setText(getString(R.string.start));
}
}
/****************************/
/***** CALLBACK METHODS *****/
/****************************/
#Override
public void onPreExecute() {
Log.i(TAG, "onPreExecute()");
mProgressBar.setTitle("Wacky");
mProgressBar.setMessage("wack");
mProgressBar.setIndeterminate(true);
mProgressBar.show();
mButton.setText(getString(R.string.cancel));
mButton.setText(getString(R.string.cancel));
Toast.makeText(this, R.string.task_started_msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onProgressUpdate(int percent) {
//Log.i(TAG, "onProgressUpdate(" + percent + "%)");
}
#Override
public void onCancelled() {
Log.i(TAG, "onCancelled()");
mButton.setText(getString(R.string.start));
Toast.makeText(this, R.string.task_cancelled_msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onPostExecute() {
Log.i(TAG, "onPostExecute()");
mButton.setText(getString(R.string.start));
Toast.makeText(this, R.string.task_complete_msg, Toast.LENGTH_SHORT).show();
}
My headless Fragment that holds my asyncTask
/**
* This Fragment manages a single background task and retains itself across
* configuration changes.
*/
public class TaskFragment extends Fragment {
public static final String TAG = TaskFragment.class.getSimpleName();
/**
* Callback interface through which the fragment can report the task's
* progress and results back to the Activity.
*/
public static interface TaskCallbacks {
public void onPreExecute();
public void onProgressUpdate(int percent);
public void onCancelled();
public void onPostExecute();
}
public TaskCallbacks mCallbacks;
public DummyTask mTask;
public boolean mRunning;
/**
* Android passes us a reference to the newly created Activity by calling this
* method after each configuration change.
*/
#Override
public void onAttach(Activity activity) {
Log.i(TAG, "onAttach(Activity)");
super.onAttach(activity);
if (!(activity instanceof TaskCallbacks)) {
throw new IllegalStateException("Activity must implement the TaskCallbacks interface.");
}
// Hold a reference to the parent Activity so we can report back the task's
// current progress and results.
mCallbacks = (TaskCallbacks) activity;
}
/**
* This method is called only once when the Fragment is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate(Bundle)");
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
/**
* This method is <em>not</em> called when the Fragment is being retained
* across Activity instances.
*/
#Override
public void onDestroy() {
Log.i(TAG, "onDestroy()");
super.onDestroy();
cancel();
}
/*****************************/
/***** TASK FRAGMENT API *****/
/*****************************/
/**
* Start the background task.
*/
public void start() {
if (!mRunning) {
mTask = new DummyTask(this, mCallbacks);
mTask.execute();
mRunning = true;
}
}
/**
* Cancel the background task.
*/
public void cancel() {
if (mRunning) {
mTask.cancel(false);
mTask = null;
mRunning = false;
}
}
/**
* Returns the current state of the background task.
*/
public boolean isRunning() {
return mRunning;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i(TAG, "onActivityCreated(Bundle)");
super.onActivityCreated(savedInstanceState);
}
}
My Background Task (in a seperate outer class)
/**
* A dummy task that performs some (dumb) background work and proxies progress
* updates and results back to the Activity.
*/
public class DummyTask extends AsyncTask<Void, Integer, Void> {
private TaskFragment fragment;
private TaskCallbacks callbacks;
private ProgressDialog mProgressBar;
MainActivity activity;
public DummyTask(TaskFragment taskFragment, TaskCallbacks mCallbacks) {
// TODO Auto-generated constructor stub
this.fragment = taskFragment;
this.callbacks = mCallbacks;
}
#Override
protected void onPreExecute() {
// Proxy the call to the Activity
fragment.mCallbacks.onPreExecute();
fragment.mRunning = true;
}
#Override
protected Void doInBackground(Void... ignore) {
for (int i = 0; !isCancelled() && i < 100; i++) {
//Log.i(TAG, "publishProgress(" + i + "%)");
SystemClock.sleep(100);
publishProgress(i);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... percent) {
// Proxy the call to the Activity
fragment.mCallbacks.onProgressUpdate(percent[0]);
}
#Override
protected void onCancelled() {
// Proxy the call to the Activity
fragment.mCallbacks.onCancelled();
fragment.mRunning = false;
}
#Override
protected void onPostExecute(Void ignore) {
// Proxy the call to the Activity
fragment.mCallbacks.onPostExecute();
fragment.mRunning = false;
}
}
I am thinking it is the context which i am passing the progress dialog in the onCreate method of my Main Activity. Thanks for your help.
First, Activity is subclass of Context, you should know this already. Second, if Activity is destroyed, it is don't have a window anymore. Third, Dialog uses Context (read Activity) not because it wants so, but because it uses window associated with Activity to display itself.
It should be perfectly understandable, why after destroying activity during configuration change, Dialog no longer visible to you.
Method of preserving objects you using is good, but it can't preserve anything that would be destroyed during configuration change, such as any object that related to non-application Context, all this objects you need create manually every time Context changes.
You should use onSaveInstanceState(Bundle) to store state of ProgressDialog (shown or not) and show it again in your onCreate(Bunde) using value stored in Bundle.
Just an example
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putBoolean("SHOW_DIALOG", mProgressBar.isShowing());
}
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
if (savedInstanceState != null){
if (savedInstanceState.getBoolean("SHOW_DIALOG") && mTaskFragment.isRunning()){
mProgressBar.setTitle("Wacky");
mProgressBar.setMessage("wack");
mProgressBar.setIndeterminate(true);
mProgressBar.show();
}
}
//...

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