Disable a button when an event occure in main activity - android

I have two activities named Main activity and Second Activity. Main activity has an event handler. I need to disable a button in second activity when an event occurs.
Main activity
public void myEventListener(int eventID){
switch (eventID) {
case : 0
// disable button of second activity here
break;
}
}

This is an easy one.
Use SharedPreference of changing data(boolean maybe) in MainAcitivity
Use SharedPreference.OnSharedPreferenceChangeListener in SecondActivity for listening to that specific data and changing button state at runtime in.
MainActivity.java
public class MainActivity extends AppCompatActivity {
SharedPreferences.Editor editor;
public void myEventListener(int eventID){
switch (eventID) {
case 0:
editor = getSharedPreferences("pref",MODE_PRIVATE).edit();
editor.putBoolean("event",true);
break;
}
}
}
SecondActivity
public class SecondActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
#Override
protected void onStart() {
super.onStart();
sharedPreferences=getSharedPreferences("pref",MODE_PRIVATE);
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStop() {
super.onStop();
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("event") && sharedPreferences.getBoolean(key,false))
{
//add your code to disable your button or any action you want
}
}
}

It's very simple to disable a button. Follow the below steps to achieve your problem.
Define a global boolean value as "false"
In onClickEvent override, the boolean value as "true".
Then check with the boolean value as follows
private boolean isClicked = false;
if(isClicked){
button.disabled(true);
} else {
button.disabled(false);
}
Please let me know if you have any issues while applying.

In you First Activity make Boolean static variable.
Example:
FirstActivity
create a Boolean static global variable
public static Boolean clicked = false;
onFirstActivity if Event occurs.
event occurred => clicked = true; otherwise it is false
SecondActivity
in second activity get the value to static boolean from FirstActivity
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (FirstActivity.clicked){
//Do Nothing
}else{
//Perform action
}
}
});

first make reference of second activity and set button visibility GONE or INVISIBLE It's Work
SeconActivity sa; //reference of second activity
public void myEventListener(int eventID){
switch (eventID) {
case : 0
sa.btnofsecondactivity.setVisibilty(View.GONE);
break;
}
}

You can go with LocalBroadCastManager.
in MainActivity wherever you want to trigger the method
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("event-occured"));
in SecondActivity register the LocalBroadcastManager and receive it.
public class SecondActivity extends AppCompatActivity {
private BroadcastReceiver mainActivityReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mainActivityReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do whatever you want to do
Log.d("TAG", "broadcast received");
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(mainActivityReceiver, new IntentFilter("main-activity-initialized"));
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mainActivityReceiver);
}
Don't forget to unregister the listener in SecondActivity's onDestroy method. Taken reference from here.

Related

EventBus does not register event on new activity

I have implemented an otto bus example. It works fine, but ONLY on the second time I visit the activity.
For example, when I load the app and hit the secret message button I am taken to the activity but the toast does not show. Then I hit the back button to return to the MainActivity and hit the show secret message button again and when I am taken to the secret message activity the toast is displayed. I realize it works the second time because I have created a leak by not unregistering the event.
Is there something I am missing about the logic?
MainActivity:
public class MainActivity extends AppCompatActivity {
Button buttonSecretMessage;
Intent intentToMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentToMessage = new Intent(MainActivity.this, SecretMessageActivity.class);
buttonSecretMessage = (Button) findViewById(R.id.buttonSecretMessage);
buttonSecretMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EventBus.getInstance().post(new MakeMySecretMessageEvent());
startActivity(intentToMessage);
}
});
}
}
Secret Message Activity:
public class SecretMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secret_message);
}
#Subscribe
public void getMySecretMessage(MakeMySecretMessageEvent event){
Toast.makeText(this, event.getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
protected void onStart(){
super.onStart();
EventBus.getInstance().register(this);
}
#Override
protected void onStop() {
super.onStop();
//EventBus.getInstance().unregister(this);
}
}
MakeMySecretMessageEvent:
public class MakeMySecretMessageEvent {
public MakeMySecretMessageEvent() {
}
public String getMessage() {
String message = "YOU ARE AWESOME!";
return message;
}
}
EventBus:
public final class EventBus extends Bus{
private static final EventBus Bus = new EventBus();
public static Bus getInstance() {
return Bus;
}
private EventBus() {
}
}
You can send sticky event using EventBus library. It allows you to send events to component which is not created yet.
You`ll find more info here.
Here EventBus has applied in wrong scenario, when you can simply send data via intent or bundle. Which is more reliable in communication with one activity with another. You will never ever receive event on first click, as event fire is instant and your activity creation will take some time accordingly.
So try to use bundle or intent to setup communication b/w to activity one after another.
Thanks to contributors I now have a better understanding of the activity life cycle and how it fits in with event bus. That is you cannot send an event from the MainActivity to its children, but the other way around instead. Below reflects how to implement an otto event bus to pass a simple object from an activity back to the main activity. Hopefully someone else can find this useful :) And if this can be improved upon please comment. Thanks.
Main Activity:
public class MainActivity extends AppCompatActivity {
Button buttonSecretMessage;
Intent intentToMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getInstance().register(this);
intentToMessage = new Intent(MainActivity.this, SecretMessageActivity.class);
buttonSecretMessage = (Button) findViewById(R.id.buttonSecretMessage);
buttonSecretMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intentToMessage);
}
});
}
public MakeMySecretMessageEvent event;
#Subscribe
public void getMySecretMessage(MakeMySecretMessageEvent event) {
Toast.makeText(this, event.getMessage(), Toast.LENGTH_SHORT).show();
}
protected void onStop() {
super.onStop();
if(event != null ){
EventBus.getInstance().unregister(this);
}
}
}
SecretMessageActivity (this is where the secret message is created)
public class SecretMessageActivity extends AppCompatActivity {
Button buttonClickToMeToSeeMessage;
Intent intentToMain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secret_message);
intentToMain = new Intent(SecretMessageActivity.this, MainActivity.class);
buttonClickToMeToSeeMessage = (Button) findViewById(R.id.buttonClickToMeToSeeMessage);
buttonClickToMeToSeeMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MakeMySecretMessageEvent makeMySecretMessageEvent = new MakeMySecretMessageEvent();
EventBus.getInstance().post(makeMySecretMessageEvent);
startActivity(intentToMain);
}
});
}
}
MakeMySecretMessageEvent
public class MakeMySecretMessageEvent {
public MakeMySecretMessageEvent() {
}
public String getMessage() {
String message = "YOU ARE AWESOME!";
return message;
}
}
EventBus:
public final class EventBus extends Bus{
private static final EventBus Bus = new EventBus();
public static Bus getInstance() {
return Bus;
}
private EventBus() {
}
}

how to disable a button on restart of an activity android

I have activity flow
Activity 1-> Activity 2->Activity 3
If the user performs certain action in Activity 3, shared preferences boolean variable "performed" stores true. Now if the user presses back button to load Activity 2, it doesn't (i used finish()) and loads Activity 1. This is fine and as per the need.
What I want now is, when Activity 1 restarts this way, based on the value of the shared preferences boolean variable "performed" value true the button in Activity should be hidden.
I am using,
if (preferences.getBoolean("performed",false)){
button.setVisibility(View.Gone);
}
I have written this code in onRestart method of the Activity 1.
What am I missing?
The button does not hides.
I have done it in following way
- wrote a singalton class has variable IsVisited.
- check if it is visited in onResume() method
- if visited then set visibility of the button gone
Main Activity
Controller c;
Button bu ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bu = (Button)findViewById(R.id.button1);
c = Controller.getController();
bu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
c.setIsVisited(true);
Intent i = new Intent(MainActivity.this, mainactivity2.class);
startActivity(i);
}
});
}
protected void onResume() {
super.onResume();
if(c.getIsVisited())
{
bu.setVisibility(View.GONE);
}
Another Activity
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Controller c = Controller.getController();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
Controller Class (Singleton Class)
public class Controller {
private static final Controller controller = new Controller();
private Boolean isVisited = false;
private Controller()
{
}
public static Controller getController()
{
return controller;
}
public Boolean getIsVisited() {
return isVisited;
}
public void setIsVisited(Boolean isVisited) {
this.isVisited = isVisited;
}}
![enter image description here][1]

Android - does defining a button static leak my activity? Can I avoid it?

I need the button to be static so I can enable it/ disable it form my services in case the activity is shown. Still I setOnClickListener and anyway static views are considered dangerous. Do I leak ? Can I avoid it ?
public class MonitorActivity extends FragmentActivity implements
OnClickListener {
private static Button updateButton; // static??
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitor);
// button
updateButton = (Button) findViewById(R.id.update_data_button);
updateButton.setOnClickListener(this); // oops ?
}
public static void onDataUpdated(Context ctx) {
if (updateButton != null) { //that's why I need it static
updateButton.setEnabled(true); // + set the text etc
}
}
public static void onUpdating() {
if (updateButton != null) {
updateButton.setEnabled(false);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.update_data_button:
serviceIntent.putExtra(MANUAL_UPDATE_INTENT_KEY, true);
this.startService(serviceIntent);
}
}
#Override
protected void onResume() {
super.onResume();
Boolean isUpdating = AccessPreferences.get(this, updateInProgressKey,
false);
// set the button right
updateButton.setText((isUpdating) ? defaultUpdatingText
: getResources().getString(R.string.update_button_text));
updateButton.setEnabled(!isUpdating);
}
}
I think You can create BroadcastReceiver in MonitorActivity. And send extras message from Service to enable/disable button.
I suggest you use LocalBroadcastManager
In your Activity define a BroadcastReceiver and register the Broadcast in onStart()onResume() and unregister it in onStop()onPause().
From your Service send the Broadcast to the Activity if the Activity is active it will receive the Broadcast and update the UI, if not nothing will happen.
Define another BroadcastReceiver in your Service, Register the Broadcast in onCreate() and Unregister it in onDestroy().
When your Activity is started send a Broadcast to the Service and let the Service reply to the Activity using the first Broadcast to update the UI.
UPDATE
After doing some investigation I found you're correct "sticky broadcasts are discouraged", but if you check the date of that post it's on 2008 - before Google implemented the LocalBroadcastManager.
And I have checked the source code of LocalBroadcastManager, it's not a real Broadcast it's an interface, Singleton with a list of BroadcastReceivers (not global and no IPC communication).
I really hate public static and I always avoid them. every body should.
So yes - the static button would leak my activity. I came up with callback below but it is ugly. I finally solved it by making the Activity extend OnSharedPreferenceChangeListener
public final class MonitorActivity extends FragmentActivity implements
OnClickListener, OnSharedPreferenceChangeListener {
private Button updateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateButton = (Button) findViewById(R.id.update_data_button);
updateButton.setOnClickListener(this); //no need to unregister methinks
}
#Override
public synchronized void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
if (updateInProgressKey.equals(key)) {
final Boolean isUpdating = AccessPreferences.get(this,
updateInProgressKey, false);
// set the button right
updateButton.setText((isUpdating) ? sDefaultUpdatingText
: sUpdateButtonTxt);
updateButton.setEnabled(!isUpdating);
}
}
#Override
protected void onStart() {
super.onStart();
AccessPreferences.registerListener(this, this);
AccessPreferences.callListener(this, this, updateInProgressKey);
}
#Override
protected void onStop() {
// may not be called (as onStop() is killable), but no leak,
// see: http://stackoverflow.com/a/20493608/281545
AccessPreferences.unregisterListener(this, this);
super.onStop();
}
}
Callback
onPause() is guaranteed to run - so I null the static fields there and populate them on onResume(). I only do a read from default shared preferences so it should not take long in the synchronized blocks (I have to synchronize cause the service might call onUpdating() or onDataUpdated() any odd time). Not sure about unregistering the listener though
public class MonitorActivity extends FragmentActivity implements
OnClickListener {
private static TextView dataTextView; //null this onPause() to avoid a leak
private static Button updateButton; // null this onPause() to avoid a leak
// ...
public static synchronized void onDataUpdated(Context ctx) {
if (updateButton != null) {
updateButton.setEnabled(true); // + set the text etc
}
}
public static synchronized void onUpdating() {
if (updateButton != null) {
updateButton.setEnabled(false);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.update_data_button:
serviceIntent.putExtra(MANUAL_UPDATE_INTENT_KEY, true);
this.startService(serviceIntent);
}
}
#Override
protected void onResume() {
super.onResume();
synchronized (MonitorActivity.class) {
Boolean isUpdating = AccessPreferences.get(this,
updateInProgressKey, false);
updateButton = (Button) findViewById(R.id.update_data_button);
updateButton.setOnClickListener(this);
// set the button right
updateButton.setText((isUpdating) ? defaultUpdatingText
: getResources().getString(R.string.update_button_text));
updateButton.setEnabled(!isUpdating);
}
}
#Override
protected void onPause() {
synchronized (MonitorActivity.class) {
updateButton.setOnClickListener(null); // TODO : needed ??
dataTextView = updateButton = null; // to avoid leaking my activity
}
super.onPause();
}
}
There are 3 solutions for you:
Set button = null when context is destroyed(onStop);
Use WeakReference for button field, Example:
private static WeakReference<Button> updateButton;
Not creating static button. It's always hold the context.

What is wrong with this use of Application context in Android?

I abstract my model like this:first there is a class UserInfo which holds user information:
public class UserInfo extends Application{
private int userid;
public void setUserId(int id)
{
userid=id;
}
public int getUserId()
{
return userid;
}
}
Then in MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
userinfo=(UserInfo)getApplication();
userinfo.setUserId(1354);
....
Intent intent=new Intent(MainActivity.this,VoteActivity.class);
startActivity(intent);
}
public
#Override void onResume()
{
super.onResume();
TextView text=(TextView)MainActivity.this.findViewById(R.id.usernameText);
text.setText(userinfo.getUserId()+" ");
}
And in VoteActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vote);
userinfo=(UserInfo)getApplication();
Button back=(Button)findViewById(R.id.backButton);
back.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
userinfo.setUserId(-100);
Intent intent=new Intent(VoteActivity.this,MainActivity.class);
startActivity(intent);
}});
}
The result is: when MainActivity first run, userid in UserInfo is 1354 ; And when VoteActivity first run, userid in UserInfo is 1354 too.However when back to MainActivity from VoteAcitivy userid remains 1354 which should be -100.What is wrong with this use of Application context?
You're starting a new activity in your onClick method :
Intent intent=new Intent(VoteActivity.this,MainActivity.class);
startActivity(intent);
And you direct set your id in the MainActivity :
userinfo.setUserId(1354);
That's why you get (1354). You should call finish in your on click (instead of starting the MainActivity).
The activity's stack look like this : MainActivity - VoteActivity - MainActivity and I think you want it to look like this : MainActivity after pressed on your Button
#Override
public void onClick(View arg0) {
userinfo.setUserId(-100);
finish();
}});
How you do you get back for your MainActivity? Pressing the device's back button or clicking on your button? If you press the device's back button your onClickListener won't be called, so that's why id remains the same.
#Override
public void onClick(View arg0) {
userinfo.setUserId(-100);
Intent intent=new Intent(VoteActivity.this,MainActivity.class);
startActivity(intent);
}});
when you click on your back button you restart MainActivity. The MainActivity onCreate will be excuted again. Is MainActivity flagged as singleInstance?

Android object value changed when resume

I got a VERY STRANGE situation...(to me)
For example, 2 objects,
1 is an activity member boolean called isInPage,
2 is a static bitmap object called bmpPhoto.
When I get into my own activity called FacebookShareActivity
isInPage will be true until I quit this activity,
bmpPhoto will be given a picture.
After onCreare() and onResume(), there is no any code running, until user click some GUI.
What I did is close screen by press hardware power button, and maybe wait 5 or 10 minutes.
OK, now I press porwe again to wake phone up, unlock screen,
and my FacebookShareActivity goes back to front.
And I click my GUI button to check variable value via Logcat, it says:
isInPage=false;
And I forget bmpPhoto's value, but on my GUI, the photo just gone,
not displayed anymore...
How is this happen ?
And it just not happen every time after I do that......
What if I override onSaveInstanceState(Bundle savedInstanceState) and
onRestoreInstanceState(Bundle savedInstanceState) ?
Will it help ?
And what about the bitmap object ?
Still don't know how is that happen...
Did I miss something ?
I really need your help, please everyone~
Following is part of my code, quite long...
The "isPageRunning" and "bmp" changed sometime when back from desktop, but not everytime.
public class FacebookShareActivity extends Activity
{
private Bundle b=null;
private Bitmap bmp=null;
private boolean isFacebookWorking=false;
private boolean isPageRunning=true; //This value sometime changed when back from desktop, but not every time
protected void onCreate(Bundle savedInstanceState)
{
Log.i(Constants.TAG, "ON Facebook Share create......");
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_share);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
private void initUI()
{
btnBack=(Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new ButtonClickHandler());
formImage=(RelativeLayout)findViewById(R.id.form_image);
formImage.setDrawingCacheEnabled(true);
btnShare=(Button)findViewById(R.id.btnShare);
btnShare.setOnClickListener(new ButtonClickHandler());
txtIntroText=(TextView)findViewById(R.id.txtIntroText);
txtIntroText.setOnClickListener(new ButtonClickHandler());
txtIntroText.setText(getUploadInImageText());
photo=(ImageView)findViewById(R.id.photo);
bmp=Constants.PROFILE.getName().getPhoto();
if(bmp!=null)
{photo.setImageBitmap(bmp);} //bmp wouldn't be null, it filled by some other activity before
}
#Override
protected void onResume()
{
super.onResume();
Log.i(Constants.TAG, "Trying to set UI on resume...");
b=getIntent().getExtras();
// ...
// ... Get some String value passed from prev activity
facebook=new Facebook("123456789012345"); //Test
asyncFacebook=new AsyncFacebookRunner(facebook);
initUI();
System.gc();
}
#Override
public void onBackPressed()
{
Log.d(Constants.TAG, "Activity receive back key...");
lockButtons(false);
return;
}
private void lockButtons(boolean b)
{
if(isPageRunning)
{
btnBack.setClickable(!b);
btnShare.setClickable(!b);
}
}
private class DelayReleaseKey implements Runnable
{
public void run()
{
try{Thread.sleep(10000);}
catch(InterruptedException ie){}
handler.sendEmptyMessage(0);
}
}
private class ButtonClickHandler implements OnClickListener
{
public void onClick(View v)
{
if(v==btnBack)
{
if(isFacebookWorking)
{ShowAlertDialog(Constants.MESSAGE_FACEBOOK_WORK);}
else
{
lockButtons(true);
formImage=null;
photo=null;
b=null;
facebook=null;
isPageRunning=false;
Intent intent=new Intent(FacebookShareActivity.this, PracticeListActivity.class);
startActivity(intent);
FacebookShareActivity.this.finish();
overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
}
}
if(v==btnShare)
{
lockButtons(true);
facebookLogin();
}
}
}
}
Now I know i must override onSaveInstanceState, onRestoreInstanceState.
They can help me to save variable like String, int, boolean...
What about Bitmap ?
And what if my variable is static ?
Now try again.
public class FacebookShareActivity extends Activity
{
private Bundle b=null;
private static Bitmap bmp=null;
private static boolean isFacebookWorking=false;
private static boolean isPageRunning=true; //This value sometime changed when back from desktop, but not every time
protected void onCreate(Bundle savedInstanceState)
{
Log.i(Constants.TAG, "ON Facebook Share create......");
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_share);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
private void initUI()
{
btnBack=(Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new ButtonClickHandler());
formImage=(RelativeLayout)findViewById(R.id.form_image);
formImage.setDrawingCacheEnabled(true);
btnShare=(Button)findViewById(R.id.btnShare);
btnShare.setOnClickListener(new ButtonClickHandler());
txtIntroText=(TextView)findViewById(R.id.txtIntroText);
txtIntroText.setOnClickListener(new ButtonClickHandler());
txtIntroText.setText(getUploadInImageText());
photo=(ImageView)findViewById(R.id.photo);
bmp=Constants.PROFILE.getName().getPhoto();
if(bmp!=null)
{photo.setImageBitmap(bmp);} //bmp wouldn't be null, it filled by some other activity before
}
#Override
protected void onResume()
{
super.onResume();
isPageRunning = true;
Log.i(Constants.TAG, "Trying to set UI on resume...");
b=getIntent().getExtras();
// ...
// ... Get some String value passed from prev activity
facebook=new Facebook("123456789012345"); //Test
asyncFacebook=new AsyncFacebookRunner(facebook);
initUI();
System.gc();
}
#Override
protected void onPause()
{
isPageRunning = false;
}
#Override
public void onBackPressed()
{
Log.d(Constants.TAG, "Activity receive back key...");
lockButtons(false);
return;
}
private void lockButtons(boolean b)
{
if(isPageRunning)
{
btnBack.setClickable(!b);
btnShare.setClickable(!b);
}
}
private class DelayReleaseKey implements Runnable
{
public void run()
{
try{Thread.sleep(10000);}
catch(InterruptedException ie){}
handler.sendEmptyMessage(0);
}
}
private class ButtonClickHandler implements OnClickListener
{
public void onClick(View v)
{
if(v==btnBack)
{
if(isFacebookWorking)
{ShowAlertDialog(Constants.MESSAGE_FACEBOOK_WORK);}
else
{
lockButtons(true);
formImage=null;
photo=null;
b=null;
facebook=null;
isPageRunning=false;
Intent intent=new Intent(FacebookShareActivity.this, PracticeListActivity.class);
startActivity(intent);
FacebookShareActivity.this.finish();
overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
}
}
if(v==btnShare)
{
lockButtons(true);
facebookLogin();
}
}
}
}
For primitive values, you should use onSaveInstanceState. For restoring you can use onRestoreInstanceState or you can some code in onCreate like this:
if(savedInstanceState != null) {
// restore old state
} else {
// a fresh start
}
Now for restoring objects like Bitmap if they are not expensive to create and doesn't make your UI sluggish, create them again on restore. If you do not want to that then use onRetainNonConfigurationInstance and code will look like this:
#Override
public Object onRetainNonConfigurationInstance () {
return bmp;
}
#Override
public void onCreate() {
if
bmp = (Bitmap)getLastNonConfigurationInstance();
}
WARNING: This api is deprecate, you might use it on old platforms. I put it here for illustration purpose. The new way to do this is more involving.
Here is detailed ref:
getLastNonConfigurationInstance
onRetainNonConfigurationInstance

Categories

Resources