check if activity is the first since launch - java

I want my main activity to show a popup the on launch, this activity is the first activity that is created, but multiple instances of this activity could be created and I only want the first since launch to display this popup, so I would like to know if there how I can check this.

The most simplest way of doing it is use a static variable
How do you use it:
Define a static boolean flag and assign it false value, once the activity is created for the first time, make the flag true, and now you do your task with simple if/else condition
public static boolean flag=false;
then in onCreate
if(flag==true)
{
//Activity is not calling for first time now
}
if(flag==false)
{
//first time calling activity
flag=true;
}

Store flag in SharedPreferences which indicate is application is launched first time or not. Use Activity Oncreate method as:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create and check SharedPreferences if fist time launch
SharedPreferences settings = getSharedPreferences("showpopup", 0);
SharedPreferences.Editor editor = settings.edit();
if(settings.contains("firsttime")){
// means activity not launched first time
}else{
// means activity launched first time
//store value in SharedPreferences as true
editor.putBoolean("firsttime", true);
editor.commit();
//show popup
}
}

I would use selvins approach. Unless you have a backend to your application setup and user registration, there will be no way for you to get this type of information for a specific application instance unless you use SharedPreferences
int activityLaunchCount = 0;
SharedPreferences preferences = getBaseContext().getSharedPreferences("MyPreferences", SharedPreferences.MODE_PRIVATE);
activityLaunchCount = preferences.getInt("ActivityLaunchCount", 0);
if(activityLaunchCount < 1)
{
// ** This is where you would launch you popup **
// ......
// Then you will want to do this:
// Get the SharedPreferences.Editor Object used to make changes to shared preferences
SharedPreferences.Editor editor = preferences.edit();
// Then I would Increment this counter by 1, so if will never popup again.
activityLaunchCount += 1;
// Store the New Value
editor.putInt("ActivityLaunchCount", activityLaunchCount);
// You Must call this to make the changes
editor.commit();
}else{
// If you application is run one time, this will continue to execute each subsequent time.
// TODO: Normal Behavior without showing a popup of some sort before proceeding.
}
Then when you want to Close the application
Override the Activity finish() method
#Override public void finish()
{
super.finish();
// Get the SharedPreferences.Editor Object used to make changes to shared preferences
SharedPreferences.Editor editor = preferences.edit();
// Store the New Value
editor.putInt("ActivityLaunchCount", 0);
// You Must call this to make the changes
editor.commit();
}

Related

Save state of Button in activity Android

I have two buttons(button1, button2) in my activty. botton1 is 'Enabled'(true) , while the other one isn't.
When I click on button1, button2 becomes 'Enabled'. I want to record this activity in this state for the next utilization of my application.
You can save state in sharedPrefrences, try this
SharedPreferences prefs = getSharedPreferences("Your preference name here", MODE_PRIVATE)
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
b2.setEnabled(true);
prefs.edit().putBoolean("b2enabled", true).commit();//saving State here
}
});
And now where you want to use this state simple get the state as.
Boolean b2state= prefs.getBoolean("b2enabled", false); //false is the default value
And if you want to enable or disable button on result do
if (b2state){
b2.enabled(true);
}
else{
b2.enabled(false);
}
Well, you can use the help of a data storage option. For a simple task like this,
shared preference is enough.
use something like this to store the state change.
function setState(boolean state){
SharedPreferences sharedPref =this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("state",state);
}
you can retrieve the data at anytime (usually in in the beginning) like this. Note that the second argument serves the default value.
int state=this.getPreferences(Context.MODE_PRIVATE).getBoolean("state",false);
Hope this helps.

Store boolean using sharedpreferences in android [duplicate]

I want to run a piece of code once only after the application is installed. After it has been executed, that particular piece of code should not be called again, even for an upgrade.
Check if boolean X is True in shared preferences
If not:
a. Run the special code
b. Save x as true in shared preferences
For example:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false)) {
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
I've used a shared preference in the past, but if you are wanting to do something onInstall you could also look at a install receiver. MyInstallReciever implements BroadcastReciever
<receiver
android:name="com.MyInstallReciever"
android:exported="true">
<intent-filter>
<action
android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
use this simple code
if (getPreferences(MODE_PRIVATE).getBoolean("is_first_run", true)) {
/*
* your code here
*/
getPreferences(MODE_PRIVATE).edit().putBoolean("is_first_run", false).commit();
}
Use a boolean value to check if its first execution of code or not.
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedpreferences.edit();
if(sharedpreferences.getBoolean("is_first_exec",false))
{
editor.putBoolean("is_first_exec",false);
//your code here ...
}
The getBoolean() like every other get method of SharedPreference, takes a second default parameter which will return null the first time (as there is nothing in the SharedPreference file). Thus, the code inside the if(){...} block will execute only once.
Footnotes: SharedPreferences
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// Initialize SharedPreferences
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
// Create a new boolean and preference and set it to true
boolean isFirstStart = getPrefs.getBoolean("firstStart", true);
// If the activity has never started before...
if (isFirstStart) {
// Launch app intro
final Intent i = new Intent(MainActivity.this, DefaultIntro.class);
runOnUiThread(new Runnable() {
#Override public void run() {
startActivity(i);
}
});
// Make a new preferences editor
SharedPreferences.Editor e = getPrefs.edit();
// Edit preference to make it false because we don't want this to run again
e.putBoolean("firstStart", false);
// Apply changes
e.apply();
}
}
});
// Start the thread
t.start();

Non-static method 'getSharedPreferences (java.lang.String, int)' cannot be referenced from a static context

I have an app, and I am trying to limit the number of button clicks to five, and then once the user has pressed this button five times it should disable.
However I am getting the above error and I am not sure why.
Any ideas ?
buttonadd.setOnClickListener(new OnClickListener () {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
int clicks = 0;
clicks++;
if (clicks >= 5){
buttonadd.setEnabled(false);
}
SharedPreferences prefs = Context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("clicks", clicks);
editor.apply();
}
});
You are wrongly trying to use the virtual method getSharedPreferences() in a static way, that's why its giving that compile-time error.
If that code is in an Activity, replace
Context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
with
getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
If it is in a Fragment, use
getActivity().getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
EDIT:
use
if (clicks >= 5){
buttonadd.setEnabled(false);
buttonadd.setClickable(false);
buttonadd.setFocusable(false);
buttonadd.setFocusableInTouchMode(false);
}
and make clicks a class member, i.e. declare it as
private int clicks;
in the Activity.
EDIT 2:
I think I have understood the mistake you are making. In your code, replace
int clicks = 0;
with
SharedPreferences prefs = getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int clicks = prefs.getInt("clicks", 0);
Try this. This should do it.
It means that you need an instance of a Context object to call the getSharedPreferences() method. If you're inside an Activity, try this:
this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE)
As the error message says getSharedPreferences() is a non-static method. When you do Context.getSharedPreferences(...) you are trying to call it directly from the class. Instead, you need to call it from a Context instance.
If your code is inside an Activity (as Activity extends Context) you can simply do:
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);

SharedPerferences doesn't seem to be working

I'm trying to use SharedPreferences in my app but it just doesn't seem to be working.
First, I declare SharedPreferences as a global variable in the activity where I'm planning to use them:
SharedPreferences prefs;
Then I set the default SharedPreferences in onCreate:
prefs = getSharedPreferences("urnikSp", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("schudeleDownloaded", false);
editor.commit();
I then change the boolean value when a certain action is completed:
prefs.edit().putBoolean("schudeleDownloaded", true).commit();
And then in the same activity (when it is restarted), I check for the boolean value in onCreate like this:
boolean schudeleDownloaded = prefs.getBoolean("schudeleDownloaded", false);
if (!schudeleDownloaded){
new PopulateDatabase().execute();
}
And even though I clearly set the new value to "true" upon completing a certain action, the IF statement you see above still executes because the boolean value still seems to be false.
What am I doing wrong?
If you are recreating your activity, the onCreate() method will be called again, so I think you change his value back to false
Let me do a wild guess. Because when you restart, you set it to false again.... It is in onCreate function.
You have to create a separate SharedPreferences.Editor instance. So instead of doing this:
prefs.edit().putBoolean("schudeleDownloaded", true).commit();
Try this:
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("schedeleDownloaded", true);
editor.commit();

boolean won't stay on the right input when i kill my app or reboot the device

im building a app, found a java part that lets me show an activity only at first start.
this works but when i kill the app or reboot my phone it goes back, can anyone help me out with this?
im using this in my main activity (Toolz.java)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Prefs.firststart == false) {
setContentView(R.layout.toolz);
} else {
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
and i added this to First.java
Prefs.firststart=false;
and i made the Prefs.java and added this
public class Prefs {
public static boolean firststart = true;
}
you will need to use SharedPreferences instead o static variable for saving data which also available when app killed or device reboot.
you can see following tutorial how we use SharedPreferences for saving and reading data from SharedPreferences
Shared Preferences
When the app restarts all your code will start from the starting point (i.e Prefs.firststart will be set to true). Instead, you need to make a persistent variable that is saved throughout sessions. If you're using a DB you could use that, or you could use the built-in SharedPreferences, as such:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = this.getPreferences(MODE_PRIVATE);
if (prefs.contains("started")) {
setContentView(R.layout.toolz);
} else {
//Add the preference:
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("started",true);
editor.apply();
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
When you kill your app, the values are going to reset to their initial values. Your boolean will be equal to true. I suggest saving the state of the variable using SharedPreferences. Check out this other question someone asked about saving.
How to save a state of a variable in android app and use it
Try it like this
//**** First start *****
//you get the prefs for your app using a pref name
String PREFS_NAME = "myAppPrefs";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//persist the boolean value in preferences using a key-value approach
editor.putBoolean("pref_app_started", true);
//commit the changes
editor.commit();
and when you start the app you check for that pref
//**** next start *****
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//now we get the saved boolean using the key we previously uesd when setting it
//the second parameter is the default value for the flag in case it was never set
boolean wasAppStarted = settings.getBoolean("pref_app_started", false);
//now you can use your wasAppStarted flag to decide what you do further

Categories

Resources