5

I have a piece of code that I only want to run the very first time a particular OnCreate() method is called (per app session), as opposed to every time the activity is created. Is there a way to do this in Android?

AJJ
  • 2,004
  • 4
  • 28
  • 42

4 Answers4

17

protected void onCreate(Bundle savedInstanceState) has all you need.

If savedInstanceState == null then it is the first time.

Hence you do not need to introduce extra -static- variables.

greenapps
  • 11,154
  • 2
  • 16
  • 19
  • 2
    Tried this and for some reason savedInstanceState is always null so the hopefully-one-time code always triggers – AJJ Mar 25 '16 at 13:27
3

use static variable.

static boolean checkFirstTime;
KDeogharkar
  • 10,939
  • 7
  • 51
  • 95
3

use static variable inside your activity as shown below

private static boolean  DpisrunOnce=false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_run_once);
    if (DpisrunOnce){
        Toast.makeText(getApplicationContext(), "already runned", Toast.LENGTH_LONG).show();
//is already run not run again
    }else{
//not run do yor work here
        Toast.makeText(getApplicationContext(), "not runned", Toast.LENGTH_LONG).show();
        DpisrunOnce =true;
    }
}
sunilkarkala
  • 92
  • 4
  • 15
2

use sharedpreference...set value to true in preference at first time...at each run check if value set to true...and based on codition execute code

For Ex.

SharedPreferences preferences = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
                if (!preferences.getBoolean("isFirstTime", false)) {
  //your code goes here
 final SharedPreferences pref = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
                    SharedPreferences.Editor editor = pref.edit();
                    editor.putBoolean("isFirstTime", true);
                    editor.commit();
}
H Raval
  • 1,903
  • 17
  • 39
  • But then you have to set it back to false at some point or it'll be true with each app restart, too – AJJ Mar 25 '16 at 06:25
  • You can simply have a static variable initialized to false check its value and if it is false do your work and set the flag to true. When user pressed presses back button on the home screen you can set it to false again. – nits.kk Mar 25 '16 at 06:34
  • Shared preferences is the way to go for this. Check this library to make it even simpler and do it in one or two lines of code : https://github.com/viralypatel/Android-SharedPreferences-Helper – Viral Patel Mar 25 '16 at 06:41