Run code on first OnCreate only
Asked Answered
C

4

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?

Cockburn answered 25/3, 2016 at 6:23 Comment(0)
A
3

use static variable.

static boolean checkFirstTime;
Anzus answered 25/3, 2016 at 6:33 Comment(0)
P
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.

Prostatectomy answered 25/3, 2016 at 7:35 Comment(1)
Tried this and for some reason savedInstanceState is always null so the hopefully-one-time code always triggersCockburn
A
3

use static variable.

static boolean checkFirstTime;
Anzus answered 25/3, 2016 at 6:33 Comment(0)
L
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;
    }
}
Lexi answered 25/3, 2016 at 7:9 Comment(0)
P
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();
}
Pantomime answered 25/3, 2016 at 6:24 Comment(3)
But then you have to set it back to false at some point or it'll be true with each app restart, tooCockburn
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.Andalusia
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 : github.com/viralypatel/Android-SharedPreferences-HelperCannibal

© 2022 - 2024 — McMap. All rights reserved.