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?
Run code on first OnCreate only
Asked Answered
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.
Tried this and for some reason savedInstanceState is always null so the hopefully-one-time code always triggers –
Cockburn
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;
}
}
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();
}
But then you have to set it back to false at some point or it'll be true with each app restart, too –
Cockburn
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-Helper –
Cannibal
© 2022 - 2024 — McMap. All rights reserved.