I want to show a special activity on 3rd launch of my app. I've made some researches and found this Check if application is on its first run. But I still don't know how to detect if it's a 3rd time or not and also in answer on that question was described how to know if app was stopped and then resumed but I need a solution that will show my special activity when user will open it on 3rd time!!!
Can somebody help me with this?
Thank you!
In your launch activity put this code in onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
SaharedPreferences prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
int launch_count = prefs.getInt("launch_count", 0);
if(launch_count>=3){
// third time launch
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
} else {
prefs.edit()
.putInt("launch_count", launch_count+1)
.apply();
}
}
But this solution do not detect recreate activity, that will be reason to increment launch_count counter. You can solve this issue by creating "StartActivity", which increment counter and start main or specialy activity.
In your Application class in onCreate method you can add code that reads integer value from Shared Preferences. If there is no value the value is 0. Then just add to it 1 and save. Then in any activity you can read this value. If value is 3 you good to go.
Better way to store the integer value in your sharedperference. Every time have to check whether the range has been come or not.
Example:
At first time, initialize int i=0 and store the value as 0
Next step, which means on the next time retrieve the value from shared preference and store in it. Then check the value.
if(i==range)
//todo
else
//todo
keep the count in mysql db or shared preference ,and check and update on each launch of the app in splash screen or your first activity ,get the count and
if(count>=3){
// do the operations what you need to here
}else{
//first 3 opening of the app
}
Related
I intend to show four welcome screens to the user that only appear once for new users. To do so, I save a flag in the Preferences at start up and check its value to determine if the user is new or not. If not, then the welcome screens do not appear:
SharedPreferences mPrefs;
final String welcomePref = "oldUser";
#Override
public void onCreate(Bundle savedInstanceState) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Boolean welcome = mPrefs.getBoolean(welcomePref, false);
if (!welcome) {
Intent intent = new Intent(this, welcomeScreenOne.class);
startActivity(intent); //start the first welcome screen
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomePref, true); //not a new user anymore
editor.commit();
}
}
The welcomeScreenOne activity starts the second welcome screen and so on.
As you may have noticed, the error in this code is that if the user views the first welcome screen, the pref is set to true and so if he exits the application before looking at the other welcome screen (2, 3 and 4) then returning to the app will not display the remaining screens.
To solve this I thought of using startActivityForResult(Intent, int) inside each welcome screen activity so that the 4th returns to the 3rd, which returns to the 2nd which returns to the 1st welcome screen, then setting the pref to true. Is this bad coding practice?
My second solution is calling the 1st screen from the main, returning then calling the 2nd, returning then calling the 3rd and so on.
Maybe there is a way I do not know of, please advise?
Is this bad coding practice?
IMHO, yes.
Maybe there is a way I do not know of, please advise?
Have one activity, not four.
Use something else inside this one activity for your sequence of welcome screens, such as:
Four fragments, showing one at a time
Four views, showing one at a time
An existing library for such welcome screens, such as these wizards or these "showcase views"
It's possible for you to add a splashActivity to your app? if so, you can check on that activity if the user is new or not, and if is new, show the welcome screen and if not, send it to your mainActivity (or the activity you need).
It depends on the activity mode you are launching the activity if you will use launch mode Single Instance than the same activity will get reopened again and again ,if the default mode will be there every time a new instance will be created and there will be activities piled up in the stack which can create unknown results
I have 2 Fragments. 1st is for calculation while the 2nd is for settings.
I save the settings using SharedPreference.Editor.commit() on onPause() method. No problem so far with the saving. The problem I am facing is retrieving the SharedPreference value on my 1st Fragment. I retrieved the value every time I pressed the count button. For the 1st time, the values I am getting are the ones before change (which is the problem I am facing), I will only get my saved value when retrieving/pressing the count button for the 2nd time or more.
And I try to change the settings and then press home button to terminate the app from outside (which triggers onPause method) and when I reopened the settings, the values did change to my defined settings. So, I am sure the settings did saved when onPause is triggered.
I wonder what is going wrong here. Any helps is much appreciated.
As requested, this is my saving code on my SettingFragment :
#Override
public void onPause() {
super.onPause();
saveToPref();
}
public void saveToPref() {
SharedPreferences settings = getActivity().getSharedPreferences("mysettings", 0);
Editor edit = settings.edit();
edit.putString("begin", String.valueOf(ibegin)).putString("end", String.valueOf(iend)).commit();
}
Initialize your SharedPreferences object somewhere else, and do it once - maybe in onCreate. The reason why you're not seeing the change is because a different instance of SharedPreferences is opened somewhere, with the same constructor, and multiple instances of these do not automatically resolve/merge. While you're at it, initialize the Editor edit instance along with settings.
Ok, I have found my problem. The problem is that onPause() is triggered only when I start another activity (I started an activity onClick of Button count). I changed my code to trigger the saveToPref() by overriding onPageSelected of my ViewPager and on backPressed of my MainActivity.
I'd like to make a welcome screen just for 1 time. It should not be a splash screen because I'd put a TextEdit and a button to get the user's username. I need to see some examples of the code that would do it, thanks for stopping by! :D
1. First let the user insert his Username in the TextView.
2. When the user press the Button, then do the following...
- Use Intent to move to the next Activity you want to divert him after this Staring Activiy.
Eg:
Intent i = new Intent(StartActivity.this, DesiredActivity.class);
- Now after you use startActivity() method with Intent as the argument, do use finish() method, that will remove this StartActivity from the Back-Stack.
Eg:
Intent i = new Intent(StartActivity.this, DesiredActivity.class);
startActivity(i);
finish();
Now if the user press back button from the DesiredActivity( the one you went from StartActivity), the app will exit.
////////////Edited Part/////////////////
You don't want you app not to go to the First activity again, where you have already given the username.. After the first time..right ??????
- Then to do this... i will recommend you to do the below....
i. First save the username that user inputs the first time into Shared Preference or into a file, or a Database.
ii. Now when you open you app, let there be a thread which checks the existence of the username in the Shared Preference or in a file, or a Database, resp wherever u have saved it.
iii. If found let it move to the desired activity, if not prompt him to input the username, thats what happen the 1st time you open your app.
iv. Now its also about user-friendliness, so i recommend you to use a splash activity in the beginning, and fire your checking thread from here. So the user wont feel awkward looking at the blank screen while the thread checks the username
Start the activity. In OnCreate, check if the Activity already has been shown. If yes, start the next activity, if not, save that you are showing the activity now.
you can create a Activity in onCreate method check if user already enter UserName, if Yes start Another Activity immediately or show user Activity to enter user name.
Hope you are storing user name somewhere to check it if it is present or not
Have a starting activity that will decide if the next activity that should be opened is the once-off welcome screen or the other part of your app.
In the first activity:
To know if the screen has been opened before, you'll have to save a boolean value to the phone's memory:
If the read boolean value is false (screen has not been opened before), show the once-off screen.
Else the screen has been opened before and that's why you'll advance to the other part of the app.
To save boolean value:
public void writePrimitiveInternalMemory(String filename, boolean value) {
SharedPreferences preferences = game.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(filename, value);
editor.commit();
}
To read boolean value:
public boolean readPrimitiveInternalMemoryBoolean(String filename) {
SharedPreferences preferences = game.getPreferences(Activity.MODE_PRIVATE);
return preferences.getBoolean(filename, false);
}
I hope this helps.
Just a bit about my app first. Its a quiz app. It has a main screen displaying a question, which loads straight away, and arrows going previous and next which go to other quiz questions. I'm using the same layout over and over, just by passing different question data, so when I click the "next" button, it will just launch an intent to the same class, just with different data. At the start of my one single layout, I have a little check to see if the user has clicked to hide the disclaimer or not.
So my disclaimer pops up at the start of the app. It has a dismiss button and a Dont show this again checkbox. I can get the checkbox working perfect, using SharedPreferences but the problem arises when they hit the Dismiss button. Since I'm reusing the same layout, any time the user navigates to a new question, the disclaimer pops up. I only want it to popup on the first screen, e.g. when the app loads.
I have tried setting another SharedPreference to hide the disclaimer when the user hits dismiss but once I hide it, it never comes back, because when the user loads the app back up again, that shared preference is still set. My problem is knowing where to set the preference back! I tried resetting it in onPause() but that didn't work.
So, what I'm asking is, how can I determine if an activity is the first one to be loaded so I can only do the Disclaimer check then, and not in each of the subsequent screens?
Thanks.
EDIT: Here's my OnCreate() method:
final static String disclaimerShownPref = "disclaimerShown";
final static String disclaimerShownOnce = "disclaimerShownThisSession";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
//Checks to see if the boolean is set
//The second argument is the default to use if the preference can't be found
if(!mPrefs.getBoolean(disclaimerShownPref, false))
{
if(!mPrefs.getBoolean(disclaimerShownOnce, true))
{
new Disclaimer(this);
}
}
topMostLayout=buildHomeScreen();
setContentView(topMostLayout);
}
In your case I would suggest using a static variable in your activity:
private static boolean sFirstTime = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if( sFirstTime )
{
/*
* Place the disclaimer check here
*/
sFirstTime = false;
}
else
{
}
Having said that. I would consider a better approach to switch between questions in the same instance of your activity instead of creating a new one every time.
Good luck!
Instead of restarting the activity each time the user navigates between questions, you should just write a function that will repopulate the views with the new question data when previous or next are clicked. As for the disclaimer, if you want it to show up every time the app is started, then setting the variable using shared preferences is not the best way to go about it. The shared preferences are not deleted when the app closes, they are only deleted if you erase them manually or uninstall the application altogether. Instead create a variable in your activity that tracks whether or not "Dismiss" was clicked. As long as the app is running the dialog will not be displayed, but when the app is restarted all the variables including the one that keeps track of displaying the dialog will be reset and it will show up again.
Instead of using an Intent to launch a new version of your activity, why not just use an onClickListener to call setText() and change the display question? This might make the Activity lifecycle more intuitive and probably simplify your code.
I have an Android tab application. Suppose at the third tab, I exit the app. When I starts the app again, it gets restated and shows the first tab. My requirement is when aplication starts it should go to the previously selected tab. How to do this?
You'll have to override the Method "onSavedInstanceState"
Please see this question:
Saving Android Activity state using Save Instance State
it is described there in detail.
Edit: as stated in the comments this only works with the normal way you would close your app on your phone and it is not neither persistent after reboot of the phone nor after killing your apps process.
If this all you wanted then override the back button of your activity and save the value of current displaying tab using in SharedPeferences
int currentTab = mHost.getCurrentTab();
and in OnCreate after you inflate your layout get the values stored above and set that value as current tab using
TabHost mHost = new TabHost(this);
mHost.setCurrentTab(currentTab );
For that you need to save some tag in shared preference and when the application starts again you have to read it from shared preference and call that particular tab according to that tag saved in preference.
for this u can use SharedPeferences like this.
SharedPreference s readHistory = context.getSharedPreferences(className.PREFS_NAME,0);
return readHistory.getString("from", "");
set pres from all your activity.
and check when u again start your app like this.
if(frmAct.equalsIgnoreCase("activity1"))
{
\\ call here your activity
}
else if(frmAct.equalsIgnoreCase("activity2"))
{
\\ call here your activity
}
You can save the data for using in future:
1) you can save the simple data in sharedpreferences.
2) you can also save the data in database
To save the last data you have to save the data in activity's onStop() method. Because before exiting from the application the onStop() method is called of the current activity.
This link Data Storage in Android will help you a lot.