Opening a different activity once the user Logs In [duplicate] - android

This question already has an answer here:
Android: creating a "first time user" activity
(1 answer)
Closed 7 years ago.
I want that when the user opens the app for the first time after installation he gets an activity which asks him to make account. Once user makes account and he gets Homepage of his account. Now he closes the app. Opens it the next time. He should get the homepage and not the make account activity again. How can that be done?
Edit: I want to know where exactly i need to check my shared preferences. In the main activity's onCreate?

Create a preferences object and store the status of registration in it. Create an activity to register/make an account. Once account is made, store this in the preferences object and check this preferences object when the app is opened. If its true, they registered and show the home page, if its false show the 'make account' activity.' You could alternatively use a subclassed 'registration dialog' in the main activity instead of calling/writing another activity all together.

First,Store user details on SharedPrefrences
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putBoolean("logged",true)
editor.putString("username",username);
editor.commit();
Then you can choose either to make a Dispatcher Class like this
public class Dispatcher extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = getSharedPreferences("prefs",MODE_PRIVATE);
if (sharedPreferences != null) {
if (sharedPreferences.getBoolean("logged", false)) {
startActivity(new Intent(this, MainActivity.class);
}
} else {
startActivity(new Intent(this, LoginActivity.class));
}
Or just implement this on the onCreate() method in LoginActivity

Related

How do you pass value through multiple activities in Android using intents? [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 4 years ago.
The project that I'm working on right now currently has 3 screens.
Registration page, Login page and Homepage.
After you register, you are taken back to the login page then from the login page to the homepage.
I can use intents to pass the username from the login page to the home page but I don't know how to pass the String value (user type) from the registration page to the homepage.
It seems like the intent only works when you push the button, that's why I can pass the value from login page to homepage when I press the button that takes me to the homepage.
From the top of my head I recall two ways:
On button Click, when starting new activity:
public void nextFormPage(View v) {
Intent form_conclusion = new Intent(this, YOURCLASS.class); //define which class to go next
form_conclusion.putExtra("TAG", value);//passes the values to the next activity
startActivity(form_conclusion); //start the new activity
finish();
}
Use sharedpreferences to store the value, and read it when needed
Documentation
Write
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score_key), newHighScore);
editor.commit();
Read
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);
int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);

Launch an activity only once after Install

I have QR scanner app. There are 3 activities in the app.
1) Main activity - Button to open camera and start scanning
2) QR activity - Scan a QR code
3) Web Activity - On successful scanning, open a web page in the app
Here, the Main activity and QR activity should only launch once, only after the initial install. I read somewhere about using shared preferences. But I am a little confused as to where do I check the variable, as in which activity. Should I check my shared variable in the Main Activity?
This is my first app. Sorry if this is a silly doubt.
It's correct, you have to do it with SharedPreferences.
Here is a good explaination about how to use them
On the first activity shown, you have to add in the onCreate method those lines:
//this retrieve the sharedpreference element
SharedPreference myPref = this.getSharedPreferences(
"prefName", Context.MODE_PRIVATE);
//this retrieve the boolean "firstRun", if it doesn't exists, it places "true"
var firstLaunch = myPref.getBoolean("firstLaunch", true);
//so, if it's not the first run do stuffs
if(!firstLaunch){
//start the next activity
finish();
}
//else, if it's the first run, add the sharedPref
myPref.edit().putBoolean("firstLaunch", false).commit();
hope this helps
To complete #Pier Giorgio Misley answer you can put the "firstLaunch" check on your Main Activity or alternatively put it in another "splash" activity
For putting it in the main activity simply set the ui to some neutral color until you decide if you should finish the activity and launch the Web Activity or show the Main Activity logic
Alternatively, you can create a "splash" screen which can function as a bridge activity (which shows some logo or a nice background color) which check the varible and decide which activity to open Android splash
As pier mentioned, saving that it has been seen once is the way to go. However, I have found on some older devices, shared preferences is not reliable!
I recommend instead using SQLite database.
Create a table as follows
TABLE NAME: SEEN_ACTIVITY
Column 1: ID INT PRIMARY KEY
Column 2: SEEN VARCHAR
Then, once the activity has been launched, check if there is a record for id = '0' in SEEN_ACTIVITY. If not, then insert one as follows, (0, true).
Then, every time the app launches, check to see if the record exists of (0, true). If not, launch the extra activity.
My MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
SharedPreferences settings = getSharedPreferences("prefName",MODE_PRIVATE);
boolean firstLaunch = settings.getBoolean("firstLaunch", true);
if(firstLaunch == false) {
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
else {
Intent i = new Intent(SplashActivity.this, ScannerActivity.class);
startActivity(i);
finish();
}
}
}, SPLASH_TIME_OUT);
}
Wrote this code in a new Splash Activity

How to manage Splash, Login and Main activity on android?

I'm new on android, I have 3 activities :
SplashActivity
LoginActivity
MainActivity
I need to navigate user to LoginActivity for first time then does the authenticate and go to MainActivity but For next time which has been authenticated already, I need to navigate the user to SplashActivity and then MainActivity.
Is it good practice if I remove the splash activity and set Login activity as luncher but hide all controls to display it as Splash Activity and show controls to display it as Login Activity?
thanks
You need to save user actions locally and manage your app behavior based on previous actions of your user. For saving data locally on user device, you can use either SharedPreferences or Database based on your needs. For using these I would suggest you read some tutorials on web.
Base on your needs I suggest you to use SharedPreferences.
You can use SharedPreferences for this purpose. During login keep the user name in SharedPreferences and check the status of SharedPreferences on next login onwards.
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
In your SplashScreen check if user is already authenticated using a flag in SharedPreferences
Use a worker thread to ensure some delay at splash-screen
in onCreate() of SplashScreen
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("<Layout id>");
Thread navThread = new Thread() {
#Override
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
navigateToHomeScreen();
}
};
navThread.start();
}
void navigateToHomeScreen(){
SharedPreferences preferences=c.getSharedPreferences("<Your pref name>", Context.MODE_PRIVATE);
if(preferences.contains("isAuthenticated")){
// Navigate to Main Activity
}else{
// Navigate to login Activity
}
finish();
}
In your login Activity once User is authenticated
SharedPreferences preferences=c.getSharedPreferences("<Your pref name>", Context.MODE_PRIVATE);
preferences.edit().putBoolean("isAuthenticated", true).apply();
// Navigate to Main Activity
Hints: Declare PrefName in some Constant file and access same wherever you want to access SharedPreferences.
my pscudo code:--- Once you do first time login please same userID and password
and next time you have to check it wheather all user id and password exit or not . In this way you can resolve it.
Save:--
SharedPreferences.Editor sqliteEditor= getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
sqliteEditor.putString("userID", "chay7an");
sqliteEditor.putInt("Password", sadasdas);
sqliteEditor.commit();
Retrive :--
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("userID", "");
int idName = prefs.getInt("Password", 0);
}

Hide Intent if Default Data Inserted

I have an intent that appear only if certain data have not been inserted yet. It's like a custom form to insert some data. If the data have been inserted, in the future the apps opened, the intent will not appear anymore. It will open another intent, the default one. (Usually this might occur when the apps opened for the first time)
How do I manage the intent since the default intent could only be one?
For example: If the apps opened for the first time it will startIntent Form
next time the apps opened (assumed the data already inserted) it will startIntent MainActivity
i use sharedpreferences to insert data only once , simply use it this way, in the below code
the intent will be started only once the application is first installed, after that it will start the main activity intent.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isFirstTime()) {
// startIntent Form
}
}
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
// first time
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
}
return !ranBefore;
}
I assume you are doing something like registration thing, and want to show this form once. you have many options here.
1) As Ahmad(in the comments) says use SharedPreferences, and add some flag into it, which can tell you if the data is available or not. add a check in the very beginning of the activity/onCreate and open respective inten/activity depends on check.
2) you can use Database as well to see this value.
I would suggest you to use SPLASH screen, check this value/registration data into it. And if available start Activity A, else start Registration/default one.

How to implement a registration activity in android that works only for once?

I'm designing an application that has an activity for registration process, this activity launches on default. I want this activity to be disabled forever once the registration process has been completed successfully and then it should be replaced by a different activity as the default activity for the rest of the lifetime of the application.I've tried to search my way through this problem but I've hardly found anything.Any help will be much appreciated.
Thanks in advance.
Once registration is complete, commit some value to the SharedPreferences, then in your splash screen or some other opening Activity, check the preferences. If the value indicates that the registration is complete, start a different Activity instead of the Registration one...
Example:
public class SplashScreen extends Activity {
public void onCreate(Bundle state) {
super.onCreate(state);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean regComplete = prefs.getBoolean("registration", false);
if(regComplete) {
startActivity(new Intent(this, SomeActivity.class));
} else {
startActivity(new Intent(this, Registration.class));
}
}
Better still:
Always launch the registration, but in onCreate(), simply launch a different Activity immediately and finish() the registration Activity if the prefs indicate that registration is complete.
Edit
SharedPreferences explained:
SharedPreferences lets you persist primitive values in your app. You grab the SharedPreferences by doing:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
then you write to SharedPreferences by getting the Editor. To do this, you call
SharedPreferences.Editor editor = prefs.Edit();
then you can commit values to the editor by using key/values:
editor.putBoolean("some string as a key here", true/false);
Then to actually save that, you call editor.commit();
Then you grab values back from SharedPreferences by simply calling
prefs.getBoolean("some previously chosen string as a key here", true/false);
where true/false is the default value that will be returned if no such key exists...
This is convenient and lets you do simple things like:
editor.putInt("some important number", 55);
editor.commit();
......later
int i = prefs.getInt("some important number", -1);
if(i != -1) {
//do stuff
} else {
//do other stuff
}
Also, please see: http://developer.android.com/guide/topics/data/data-storage.html#pref
Don't have the registration Activity be the default. Instead have another Activity as the default, and then at runtime it can check to see which Activity it should send the user to. If they haven't registered then startIntent( RegistrationActivity.class ).

Categories

Resources