Android - how to display an activity just for 1 time? - android

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.

Related

What will happen if I call startActivityForResult() recursively?

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

Detect if app has been opened for 3 times

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
}

How to display login screen only one time?

I am creating a project where I have a login screen, which is used for user to login into the
Application. This login screen should only be visible the first time, so the user can fill it and log in, but when user opens the application at the second time the application must show main.activity. How to use Shared preference.
I don't understand how to do this.
To achieve this with SharedPreferences you might do something like this:
Insert the following in any Class you see more fit. Let's suppose you insert this in class Example.
//Give your SharedPreferences file a name and save it to a static variable
public static final String PREFS_NAME = "MyPrefsFile";
Now, in the method that evaluates if the user successfully logs in, do the following. Notice the Example class, you must change this to match your code.
//User has successfully logged in, save this information
// We need an Editor object to make preference changes.
SharedPreferences settings = getSharedPreferences(Example.PREFS_NAME, 0); // 0 - for private mode
SharedPreferences.Editor editor = settings.edit();
//Set "hasLoggedIn" to true
editor.putBoolean("hasLoggedIn", true);
// Commit the edits!
editor.commit();
Finally, when your application starts you can now evaluate if the user has already logged in or not. Still notice the Example class that you must change.
SharedPreferences settings = getSharedPreferences(Example.PREFS_NAME, 0);
//Get "hasLoggedIn" value. If the value doesn't exist yet false is returned
boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);
if(hasLoggedIn)
{
//Go directly to main activity.
}
Hope this helps
EDIT: To prevent the user from using the back button to go back to the Login activity you have to finish() the activity after starting a new one.
Following code taken from Forwarding.java | Android developers
// Here we start the next activity, and then call finish()
// so that our own will stop running and be removed from the
// history stack
Intent intent = new Intent();
intent.setClass(Example.this, ForwardTarget.class);
startActivity(intent);
Example.this.finish();
So, what you have to do in your code is to call the finish() function on the Login activity, after calling startActivity().
See also: Removing an activity from the history stack
Use SharedPreferences. For example, save some value, and read it on your login Activity.
In our project we saving token and user id. So, if user is already logged in, we skip authorization Activity.
P.S. If your login Activity is the first one in your app, then don't forget to finish it, before starting another Activity, to prevent pressing "Back" key in other activities.
Use SharedPreferences. For example, have a boolean variable , and read it on your application launches.
In your case when user launches the app first time the variable in shared preference will be false, so launch login screen and after successfull login make that boolean variable to true in shared preference, so that when user comes secnd time the value in the shared preference will be true. so skip the login screen and launch your main activity.
To store boolean in SharedPreference use below code::
public static void saveBooleanInSP(Context _context, boolean value){
SharedPreferences preferences = _context.getSharedPreferences("PROJECTNAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("ISLOGGEDIN", value);
editor.commit();
}//savePWDInSP()
To getValue from SharedPreference use below code::
public static boolean getBooleanFromSP(Context _context) {
// TODO Auto-generated method stub
SharedPreferences preferences = _context.getSharedPreferences("PROJECTNAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean("ISLOGGEDIN", false);
}//getPWDFromSP()
You should add another empty activity (with no UI) that loads before anything else.
Put the logic described by #Telmo Marques in this empty activity, which is responsible to direct the user either to the LoginScreen.Activity or to Main.Activity
see here, answer by #tozka
How to Skip the first activity under a condition
Using token is also a good method to know the login status.In Oauth token based login when the user login to the application they will get back a access token on successful login and is saved in account manager in secured way.And there after when ever the user open the application first check for the availability of token and if available redirect to the main page else to the login activity.

How to start another Activity as main and launcher after Deploying the application into device

I am developing an application.
my requirement is that first time when i installing the application in to device it has to start the main and launcher activity.
After that when i am starting/opening my application in side the device it has to load another activity instead of main and launcher.
If the application is uninstalls and installs again it has to load the main and launcher again.
can you please anybody share the solution on this kind of topics.
Thanks in advance.
You can do this:
Say Activity A is the activity that you want to launch only the first time, and activity B the activity that the system will launch after the first time.
In you manifest put Activity B as your launcher activity. Then inside the oncreate or better OnResume of activity B put the following:
#Override
protected void onResume() {
super.onResume();
if(firstLaunch()){
startActivity(new Intent(this, A.class));
finish();
}else{
//Do your normal stuff
}
}
private boolean firstLaunch(){
SharedPreferences prefs = getSharedPreferences(
"Preferences",
Context.MODE_PRIVATE);
return prefs.getBoolean("firstLaunch",false);
}
Then on your A activity be sure to set a flag on your preferences to indicate that your application has run more than once. So somewhere inside activity A put this:
private void setFirsLaunchFlag(){
SharedPreferences prefs = getSharedPreferences(
"Preferences",
Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean("firstLaunch",true);
edit.commit();
}
You can use a bool value like this:
1. When application is being launched for the first time make it true.
2. Check this bool value in your launcher activity and if it is true start your desired activity and if it false then make it true and save (for the first time).
Note: You can use SharedPreference for the bool value.
I think this may help you:
If the App is first time launched android.intent.action.PACKAGE_FIRST_LAUNCH broadcast will be fired.
After receiving this broadcast maintain a flag in shared preference that is the app is launched first time.
Have a splash screen activity as your launcher activity and according to that flag redirect it to your one time activity or replacing activity.
As far as ı know you don't have a chance to launch another activity.
Instead you could keep the track of your installation inside SharedPreferences and run
different code based on that.
simply create an integer or Boolean shared preference variable.when ever the application starts at first instance display the activity which you want to be displayed just 1'c, at the same time change the value of this shared preference variable.every time from not when the app is just started you have to check this value and and if it is not the default value load another activity in main and launcher.
Here's a reference LINK
, not exactly the expected ans..but hope it helps

Loop to start activity based on condition

I'm trying to write an android application that has two main activities: login screen and display screen. Currently I'm setting it up so that if the user is already logged in, the login screen will be skipped.
In order to work out the best way to do this, I created a generic "Main" activity that looks something like this:
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
// Get preferences
SharedPreferences settings = getSharedPreferences("PREFERENCES", MODE_PRIVATE);
super.onCreate(savedInstanceState);
//setContentView(R.layout.viewusage);
//System.out.println(settings.getBoolean("LOGGEDIN", false));
if (settings.getBoolean("LOGGEDIN", false) == false)
{
Intent intent = new Intent(Main.this, Login.class);
startActivity(intent);
}
else
{
Intent intent = new Intent(Main.this, Display.class);
startActivity(intent);
}
}
}
The idea is when someone logs in successfully, the login activity will save all the details needed to the user preferences, and then finish() the activity. This will return to the Main activity. What I'm trying to do is have the main activity keep looping through the if ... else statement when there aren't any activities running: so when the login page closes, it will re-run the if ... else statement, and should launch the Display activity rather than the Login activity. The reverse will be true if the user logs out from the Display class.
I've thought of using a while (true) loop, but that just hangs the program. I've thought of putting it in a separate thread, but I don't know how to detect if there is already another activity running, so a separate thread will just keep looping and opening new activities (I presume, I haven't tried it)
Any suggestion on how I could work this out?
Thanks.
You can't do it by looping in onCreate, because the activity doesn't actually get off the ground until onCreate returns.
One possibility is to use startActivityForResult and arrange for the Login and Display activities to return a code indicating whether to quit or proceed to the other activity. Then you would place your logic in onActivityResult instead of looping in onCreate.
Another, perhaps cleaner approach is to design the Display activity to directly start the Login activity when the user logs out, and vice versa. That way, the Main activity can just call finish() after it determines which activity to display initially.
Off the top of my head.
Write a login class that timestamps the login and expires the login after a set time interval perhaps with a method isLoginStillValid() and save the login object on a soft kill in onRetainNonConfigurationState. Retrieve the login object in onCreate. Save the login fields, if applicable to preferences in onDestroy(). Set a flag isSavedInstanceState to true in onRetainNonConfigurationState and use this to determine if you need to write to prefs in onDestroy. I know this sound complicated, but this is a reusable template.
So in the end, in onCreate, look for the login object. Check to see if the login has expired. If so, post a GetLogin dialog. In each credentialed call, check to see if the login has expired before allowing access to the credentialed call. If the login has expired, consider posting the GetLogin dialog again. Remember, time may have passed since the app came to the foreground.
Finally, launch GetLoginDialog using startActivityForResult so that you can retrieve the login data and update the login object with a new timestamp.
JAL
I'm a little confused by your question, but I think you want to use startActivityForResult rather than startActivity. This will allow you to return a true/false result from your Login Activity so that you can then launch your Display Activity if the login succeeded. Similarly for your Display Activity, if the user logs out, you would finish() the Activity and return a "logout" result to Main that logs the user out.

Categories

Resources