Run code on first OnCreate only - android

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?

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.

use static variable.
static boolean checkFirstTime;

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();
}

Related

Call another class and getText

public class ustawienia extends MainActivity {
EditText kryptonim;
public String test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ustawienia);
kryptonim = (EditText) findViewById(R.id.edit_kryptonim);
test = kryptonim.getText().toString();
}
public String call_back(){
return test;
}
}
When call call_back() from another class I've got error: Unable to start activity ComponentInfo. What's wrong with that?
When you close an activity all data from it is lost, so unless both activities are runing at the same time you can't retrieve data. You could use shared prefrences instead.
// IN ORDER TO WRITE TO A FILE
SharedPreferences.Editor prefs = getSharedPreferences("PrefsName", MODE_PRIVATE).edit();
prefs.putString("test", kryptonim.getText().toString());
prefs.apply(); // use prefs.commit(); if this doesn't work
In order to read data
SharedPreferences prefsR = getSharedPreferences("PrefsName", MODE_PRIVATE); // you could also write 0 instead MODE_PRIVATE
String restoredText = prefsR.getString("test", null);
Ofcourse you need to import SharedPrefs , and put this in oncreate or wherever you want... let me now if it works :)

How to implement permanent splash screen and 1 time tutorial both in one app [duplicate]

This question already has answers here:
Determine if Android app is being used for the first time
(15 answers)
Closed 6 years ago.
I am new to android development and and I want to setup some of application's attributes based on Application first run after installation. Is there any way to find that the application is running for the first time and then to setup its first run attributes?
The following is an example of using SharedPreferences to achieve a 'first run' check.
public class MyActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firstrun", false).commit();
}
}
}
When the code runs prefs.getBoolean(...) if there isn't a boolean saved in SharedPreferences with the key "firstrun" then that indicates the app has never been run (because nothing has ever saved a boolean with that key or the user has cleared the app data in order to force a 'first run' scenario). If this isn't the first run then the line prefs.edit().putBoolean("firstrun", false).commit(); will have been executed and therefore prefs.getBoolean("firstrun", true) will actually return false as it overrides the default true provided as the second parameter.
The accepted answer doesn't differentiate between a first run and subsequent upgrades. Just setting a boolean in shared preferences will only tell you if it is the first run after the app is first installed. Later if you want to upgrade your app and make some changes on the first run of that upgrade, you won't be able to use that boolean any more because shared preferences are saved across upgrades.
This method uses shared preferences to save the version code rather than a boolean.
import com.yourpackage.BuildConfig;
...
private void checkFirstRun() {
final String PREFS_NAME = "MyPrefsFile";
final String PREF_VERSION_CODE_KEY = "version_code";
final int DOESNT_EXIST = -1;
// Get current version code
int currentVersionCode = BuildConfig.VERSION_CODE;
// Get saved version code
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
int savedVersionCode = prefs.getInt(PREF_VERSION_CODE_KEY, DOESNT_EXIST);
// Check for first run or upgrade
if (currentVersionCode == savedVersionCode) {
// This is just a normal run
return;
} else if (savedVersionCode == DOESNT_EXIST) {
// TODO This is a new install (or the user cleared the shared preferences)
} else if (currentVersionCode > savedVersionCode) {
// TODO This is an upgrade
}
// Update the shared preferences with the current version code
prefs.edit().putInt(PREF_VERSION_CODE_KEY, currentVersionCode).apply();
}
You would probably call this method from onCreate in your main activity so that it is checked every time your app starts.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkFirstRun();
}
private void checkFirstRun() {
// ...
}
}
If you needed to, you could adjust the code to do specific things depending on what version the user previously had installed.
Idea came from this answer. These also helpful:
How can you get the Manifest Version number from the App's (Layout) XML variables?
User versionName value of AndroidManifest.xml in code
If you are having trouble getting the version code, see the following Q&A:
How to get the build/version number of your Android application?
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
import android.content.Context;
public class Util {
// ===========================================================
//
// ===========================================================
private static final String INSTALLATION = "INSTALLATION";
public synchronized static boolean isFirstLaunch(Context context) {
String sID = null;
boolean launchFlag = false;
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists()) {
launchFlag = true;
writeInstallationFile(installation);
}
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return launchFlag;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");// read only mode
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
> Usage (in class extending android.app.Activity)
Util.isFirstLaunch(this);
There is no way to know that through the Android API. You have to store some flag by yourself and make it persist either in a SharedPreferenceEditor or using a database.
If you want to base some licence related stuff on this flag, I suggest you use an obfuscated preference editor provided by the LVL library. It's simple and clean.
Regards,
Stephane
I'm not sure it's good way to check it. What about case when user uses button "clear data" from settings? SharedPreferences will be cleared and you catch "first run" again. And it's a problem. I guess it's better idea to use InstallReferrerReceiver.
Just check for some preference with default value indicating that it's a first run. So if you get default value, do your initialization and set this preference to different value to indicate that the app is initialized already.
The following is an example of using SharedPreferences to achieve a 'forWhat' check.
preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferencesEditor = preferences.edit();
public static boolean isFirstRun(String forWhat) {
if (preferences.getBoolean(forWhat, true)) {
preferencesEditor.putBoolean(forWhat, false).commit();
return true;
} else {
return false;
}
}
There's no reliable way to detect first run, as the shared preferences way is not always safe, the user can delete the shared preferences data from the settings!
a better way is to use the answers here Is there a unique Android device ID? to get the device's unique ID and store it somewhere in your server, so whenever the user launches the app you request the server and check if it's there in your database or it is new.
This might help you
public class FirstActivity extends Activity {
SharedPreferences sharedPreferences = null;
Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedPreferences = getSharedPreferences("com.myAppName", MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (sharedPreferences.getBoolean("firstRun", true)) {
//You can perform anything over here. This will call only first time
editor = sharedPreferences.edit();
editor.putBoolean("firstRun", false)
editor.commit();
}
}
}
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
// here you can launch another activity if you like
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference
}
}

SharedPreferences for Initial User Setup

My application requires initial user setup, for the first time the app is opened by the user. He should be able to do some initial setup that will determine how the application is run. For this, I am using sharedPreferences. What Im doing is simply, setting the contentView depending on if the boolean is 'true' or false'. But the question i have is in regards to what happens after i setContentView().
//Variables
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//creating sharedpref file
PREFS_NAME = "MyPrefsFile";
shPref = getSharedPreferences(PREFS_NAME, 0);
shPref.edit().putBoolean("my_first_time", true).commit();
//checking if app's being launched for first time
if(shPref.getBoolean("my_first_time", true)) {
setContentView(R.layout.page_one);
//setting the shPref as false
shPref.edit().putBoolean("my_first_time", false).commit();
}
//checking if app has been launched before
else if(shPref.getBoolean("my_first_time", false) && shprefchecker == 1) {
setContentView(R.layout.home_page);
}
}
So what I want to do is wait for the user to finish setup before I can set the shPref as false. Im guessing that once the layout is changed in this line " setContentView(R.layout.page_one);", it will automatically set the shPref as false. I want the app to not do anything until the user has gone through the initial setup (first layout in the intial setup is page_one.xml).
I might sound confusing, but how would I do this? Please help. All answers are appreciated. Thanks!
I think it's pretty straight.
You can set the boolean to false on initial setup's Submit button click.
The set up page must have any button, right? So it will be ensured that user completes the setup first.
In your second activity, you will have to use:
shPref = getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
SharedPreferences.Editor pref_editor = shPref.edit();
pref_editor.putBoolean("first_time", false);
pref_editor.commit();
The problem I see in your code is that your code is that you put my_first_time to true always. Just dont define it, if you dont define a var in your shared pref it will return the default value you pass as the second parameter. I'll edit your code:
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//creating sharedpref file
PREFS_NAME = "MyPrefsFile";
shPref = getSharedPreferences(PREFS_NAME, 0);
//checking if app's being launched for first time
if(shPref.getBoolean("my_first_time", true)) { //my first time not defined, it will be true
setContentView(R.layout.page_one);
//setting the shPref as false
shPref.edit().putBoolean("my_first_time", false).commit(); //This line should go in your page_one activity when it ends, but when defined it will always go to home_page
}
//checking if app has been launched before
else if(shPref.getBoolean("my_first_time", false) && shprefchecker == 1) {
setContentView(R.layout.home_page);
}
}
Hope it helps :)
It is quite simple first You have to check bu getting shared preferences key value pair whether user has passed out through the setup process if not then You can start setup activity and if yes you can skip setup activity

Android: How do I create a function that will be executed only once?

How can i create a function that will be run only once, on first installation? I am trying to create an information that displays one time.
thanks in advance.
You could use a flag in the shared preferences.
Then on every startup you check this flag. If it is not set you display your first time message and then set the flag.
For example:
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean firstStart = settings.getBoolean("firstStart", true);
if(firstStart) {
//display your Message here
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstStart", false);
editor.commit();
}
}

How to skip an activity? android

i have a default activity that starts first (Activity A), and from there the user can go to another activity (Activity B). In B after some work the user sets a sharedpreference. the next time the app starts i want to check in A if sharedpreference is null to go to B. and i put this if just under
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
and it encapsulates the whole onCreate. when the app starts it skips A and on B i shows the layout and the FC with NullPointerException.
Any one got experience with this?
OR
any one got a better idea on skipping A?
Well Simon you have to use Shared prefrences. save your data in shared prefrences. Then in the activity where you want to use the data in Shared prefres again get instance of same shared prefrence. get the data and use it.
go through this code
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
probably you will get an insight
To answer my own question. i had a location listener in onDestroy an because it was not initialized because of skipping onCreate it returned NullPointer.

Categories

Resources