Accessing username from all classes: Android - java

Background Information:
I am developing a small application. The way it works right now is the moment the app is launched, the user is prompted with the main activity. Then from there, the user clicks on the login button which prompts the login activity. Now in my login activity, I have set an Intent that gets the user's username and then stores it in the Shared Preferences. If the login is successful then the user goes to the mainloggedinpage where the user sees: [Welcome back {username}]
The problem is the following:
If the user is accessing the mainloggedinpage via loginactivity then you can easily see his username which is exactly what I want. But the thing is that on the main page, I have other buttons which goes to other activities. The moment the user click on any of those activities and then returns to the mainloggedin page, then all you see is: [Welcome Back {}]. His username is not displayed anymore.
My question:
Can anyone suggest a quick fix that will allow me to display the username so even when the user goes to another activity from the mainloggedinpage and then comes back to the mainloggedinpage, the user will still see: [Welcome Back {username}]?
My Code for Login Activity [This is where I am getting the username]:
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
Intent i = new Intent(Login.this, mainpage.class);
i.putExtra("Welcome back, username", username);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
My Code for mainloggedinActivity [This is where the username is displayed]:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage);
msuggestions = (Button) findViewById(R.id.btn_suggestions);
msuggestions.setOnClickListener(this);
mprayertimes = (Button)findViewById(R.id.btn_activityone);
mprayertimes.setOnClickListener(this);
mqibladirection =(Button)findViewById(R.id.btn_activitytwo);
mqibladirection.setOnClickListener(this);
mnewsboard = (Button) findViewById(R.id.newsboard);
mnewsboard.setOnClickListener(this);
mhadiths = (Button) findViewById(R.id.btn_activitythree);
mhadiths.setOnClickListener(this);
mchat = (Button) findViewById(R.id.btn_discussion);
mchat.setOnClickListener(this);
mallahnames = (Button) findViewById(R.id.btn_activityfour);
mallahnames.setOnClickListener(this);
// Get Username Start
TextView txt_loggedName = (TextView) findViewById(R.id.txt_loggedName);
Intent intent = getIntent();
String username = intent.getStringExtra("Welcome back, username");
txt_loggedName.setText(username);
// Get Username End
buttonLogout = (Button) findViewById(R.id.logout);
buttonLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
SharedPreferences.Editor editor=mPreferences.edit();
editor.remove("username");
editor.remove("password");
editor.commit();
Message myMessage=new Message();
myMessage.obj="NOTSUCCESS";
handler.sendMessage(myMessage);
finish();
}
});
Can anyone help me out so then when a user goes to the mainpage and click on one of the button and then comes back to the mainpage, it still displays his username? :)

Don't rely on an Intent extra for storing the username, since that will only be populated directly after the user logs in.
Replace this:
Intent intent = getIntent();
String username = intent.getStringExtra("Welcome back, username");
txt_loggedName.setText(username);
With:
String username = PreferenceManager.getDefaultSharedPreferences(this).getString("username", "guest");
txt_loggedName.setText("Welcome back, " + username);

Instead of getting the username from the intent, You should get it from the SharedPreferences since you already saved it there.

Related

Login Page shared preference not working as expected

I have an android app in which I am using shared preferences for login.Until now I have a flow like user logs in..when login is successful the credentials are stored.And when the user opens the app again the username password appears in the edit text.I have a login button and have setonclicklistner to login and jump to the inner activities.
I am trying a flow like when the user logs in successfully..and the app is restarted the credentials are stored..it should automatically go the next activity(inner activity).
What I have tried until now..
In oncreate the onclicklistner that opens next activity if credentials are good
buttonlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etemail.getText().toString().equals("") && etpass.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(),"Enter your username and Password",Toast.LENGTH_LONG).show();
}
else
{
load_data();
}
}
});
Code of shared pref
private void savePreferences() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
// Edit and commit
UnameValue = etemail.getText().toString();
PasswordValue = etpass.getText().toString();
editor.putString(PREF_UNAME, UnameValue);
editor.putString(PREF_PASSWORD, PasswordValue);
editor.commit();
}
private void loadPreferences()
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
// Get value
UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
etemail.setText(UnameValue);
etpass.setText(PasswordValue);
}
What should I do in order to achieve this??if username password is stored automatically open next activity instead of clicking login button??
Thanks
you can use contains(String key) in SharedPreferences class
could be done in loadPreferences()
if login is only used to allow access to the next activity, then you don't need to simulate the button click, but if the click loads other data based on the provided username/password then you have to do it using performClick() in Button class.
so your code may look like this:
private void loadPreferences()
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if(settings.contains(PREF_UNAME) && settings.contains(PREF_PASSWORD)){
//you can start the 2nd activity directly here
//Intent intent = new Intent (...)
//startActivity(intent);
//finish();
//OR
//load data into edittexts and programatically click the login button
UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
etemail.setText(UnameValue);
etpass.setText(PasswordValue);
//here it will click the button as if the user did it.
btnLogin.performClick();
}//contains
}
Side note: it's not good practice (not secure) to store passwords in SharedPreferences specially plain-text, not encrypted
Open the next activity first, and then in onCreate method check if the user is logged in. If not close the first, and open the loggin activity.
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new SessionManager(getApplicationContext());
CheckLogin();
...
}
private void CheckLogin(){
if(session.checkLogin()){finish();}
}
SessionManager.java
public boolean checkLogin(){
// Check login status
if(!this.isUserLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
After storing username and password in sharedpreference editor.putBoolean("hasLoggedin", true);
So it should be like
UnameValue = etemail.getText().toString();
PasswordValue = etpass.getText().toString();
editor.putString(PREF_UNAME, UnameValue);
editor.putString(PREF_PASSWORD, PasswordValue);
editor.putBoolean("hasLoggedin", true);
editor.commit();
then check in Oncreate method like
boolean hasLoggedin = sp.getBoolean("hasLoggedin", false);
if (hasLoggedin) {
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}

Android App storing and calling Username and Passwords

I have an application that I want to create a log in activity. Ive got
1) Login (Button)
2) UserID (EditText)
3) Password (EditText)
I would like to store the username and password on the device's internal storage. How do I create the file from which the SharedPreferences pulls from and encrypt it?
login_Button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
SharedPreferences userDetails = getSharedPreferences("userdetails", MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.clear();
if(etUserID.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a User ID", Toast.LENGTH_LONG).show();
}else if (etPassword.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a password", Toast.LENGTH_LONG).show();
}else{
edit.putString("userID", txtUID.getText().toString().trim());
edit.putString("password", txtPass.getText().toString().trim());
edit.commit();
}
}
});
The txtUID and txtPass is showing up as red and when I delete it the system says that the getText is wrong.
This is my first shot at an authenticator. I found something called PasswordAuthentication from the android dev page but I haven't been able to find any tutorials or code of it being used.
SharedPreferences userDetails = getSharedPreferences("userdetails", MODE_PRIVATE);
String UID = userDetails.getString("userID", "");
String pass = userDetails.getString("password", "");
if (userDetails.contains("userID")||userDetails.contains("password")){
startActivity(new Intent(LogOn.this,CrimeMap.class));
}
Sources Ive used for my research:
http://developer.android.com/reference/java/net/PasswordAuthentication.html
how to use getSharedPreferences in android
Update:
Ok, here is my updated code. If I don't enter a User ID or password it sets off my statements. However, the program doesn't go to the next activity when I put in the correct UserID and Password. I'm going to get it running first and then Ill move on to encrypting it.
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_on);
etUserID = (EditText) findViewById(R.id.etUserID);
etPassword = (EditText) findViewById(R.id.etPassword);
login_Button = (Button) findViewById(R.id.bLogin);
login_Button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int uid = 1155;
String pass = "pass";
SharedPreferences userDetails = getSharedPreferences(User_File, MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.putInt("userID", uid);
edit.putString("password", pass);
edit.commit();
if((etUserID.getText().toString().equals("")) || (etPassword.getText().toString().equals(""))) {
Toast.makeText(getApplicationContext(),"Please enter a User ID", Toast.LENGTH_LONG).show();
}else if (etPassword.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a password", Toast.LENGTH_LONG).show();
}else{
edit.putInt("userID", Integer.parseInt(etUserID.getText().toString()));
edit.putString("password", etPassword.getText().toString());
}
}
});
SharedPreferences userDetails = getSharedPreferences(User_File, MODE_PRIVATE);
if (userDetails.equals(etUserID) && (userDetails.equals(etPassword))){
startActivity(new Intent(LogOn.this,CrimeMap.class));
}
Update:
I finally got it! Thanks for your help! Here is my complete code for this portion of the project. I still haven't encrypted it but I think I'm going to take a break and come back to it later. Thanks for all your help!
#Override
public void onClick(View v) {
int uid = 1155;
String pass = "pass";
SharedPreferences userDetails = getSharedPreferences(User_File, MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.putInt("userID", uid);
edit.putString("password", pass);
edit.commit();
if((etUserID.getText().toString().equals(""))){
Toast.makeText(getApplicationContext(),"Please enter a User ID", Toast.LENGTH_LONG).show();
}else if (etPassword.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a password", Toast.LENGTH_LONG).show();
}else{
String user_id = etUserID.getText().toString();
int user_id2 = Integer.parseInt(user_id);
String user_password = etPassword.getText().toString();
int userID = userDetails.getInt("userID", 1);
String password = userDetails.getString("password", "no name");
if (userID == user_id2 && password.equals(user_password)){
startActivity(new Intent(LogOn.this,CrimeMap.class));
}
}
Don't try to access the file. Let android do that, and encrypt the data you store to the shared preferences. I mean:
edit.putString("userID", encrypt(txtUID.getText().toString().trim()));
edit.putString("password", encrypt(txtPass.getText().toString().trim()));
You can use whatever encryption you like, though of course you'll need to decode it this way.
Another option is to store the SHA1 encrypted password, and in the authentication you compare the SHA1 encypted password that was typed in with the stored string. You could use http://mvnrepository.com/artifact/commons-codec/commons-codec for example:
String sha1Password = DigestUtils.sha1Hex(password);
edit.putString("sha1Password", encrypt(sha1Password);
To fix the "red" problem you'll need to declare txtUID, txtPass. They should be added to your layout somehow. Probably via editing the layout xml. But even programmatically you can do, like: Input text dialog Android

SharedPreferences not reading the right context

I have a problem in my code , a method always return false even if i insert true
public boolean isLoggedIn(){
return pref.getBoolean("login", false);
}
even if I add true before checking ,this code it will return false
* */
public void checkLogin(){
// Check login status
editor.putBoolean("login", true);// even if add true it will return false
if(!this.isLoggedIn()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
what I am trying to do is having a register buttom in the action bar once click it will give the user register activity . then he will insert user name and password and returns him to mainactivity. if he click register button again it should send him to another activity because his login
in my code even if he is login it is sending him to register activity because the false return that i explained above the below is my code
sessionmanager
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
// Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
//SharedPreferences.Editor editor;
SharedPreferences.Editor editor;
// Constructor
public SessionManager(Context context){
this._context = context;
// pref = PreferenceManager.getDefaultSharedPreferences(context);
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String name, String email){
// Storing login value as TRUE
Toast.makeText(_context, "Create", Toast.LENGTH_SHORT).show();
System.out.println("login1");
editor.putBoolean("login", true);
System.out.println(pref.getBoolean("login", false));
// Storing name in pref
editor.putString("name", name);
// Storing email in pref
editor.putString("email", email);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything\
* */
public void checkLogin(){
// Check login status
// editor.putBoolean("login", true);
editor.putBoolean("login", true);
if(!this.isLoggedIn()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Register.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
else {
Intent i = new Intent(_context, UserProfile.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean("login", false);
}
}
mainactivity part where I am calling the register.java
case R.id.ic_register:
// session= GlobalContext.getInstance().getSession();
// session.checkLogin();
session.checkLogin();
Toast.makeText(this, "Create a new account please", Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(this, Register.class);
//startActivity(intent);
return true;
register
SessionManager session;
Button btnLogin;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final AlertDialogManager alert = new AlertDialogManager();
session= GlobalContext.getInstance().getSession();
usernam = (EditText) findViewById(R.id.username);
passw = (EditText) findViewById(R.id.password);
email = (EditText) findViewById(R.id.email);
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
btnLogin = (Button) findViewById(R.id.login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get username, password from EditText
String username = usernam.getText().toString();
String password = passw.getText().toString();
// Check if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
// For testing puspose username, password is checked with sample data
// username = test
// password = test
if(username.equals("test") && password.equals("test")){
// Creating user login session
// For testing i am stroing name, email as follow
// Use user real data
session.createLoginSession("test", "test");
// Staring MainActivity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
}else{
// username / password doesn't match
alert.showAlertDialog(Register.this, "Login failed..", "Username/Password is incorrect", false);
}
}else{
// user didn't entered username or password
// Show alert asking him to enter the details
alert.showAlertDialog(Register.this, "Login failed..", "Please enter username and password", false);
}
}
});
}
you need to perform commit, in order to save value in preference
so just after adding anything write editor.commit(), please check updated method
public void checkLogin(){
// Check login status
editor.putBoolean("login", true);// even if add true it will return false
editor.commit();
if(!this.isLoggedIn()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();

One time Sign-in [duplicate]

This question already has answers here:
How to display a one time welcome screen?
(3 answers)
Closed 7 years ago.
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 preferences to do this?
Save the login information of the user in SharedPeference:
SharedPreferences preferences = getSharedPreferences("preference",MODE_PRIVATE);
preferences.edit().putBoolean("LoggedIn", true).apply();
And save the boolean "LoggedIn" to false when the User logs out :
preferences.edit().putBoolean("LoggedIn", false).apply();
In the SplashActivity get the value from sharedprefence and call respective activities:
boolean loggedIn = preferences.getBoolean("LoggedIn", false);
if(loggedIn){
// call main activity
}else{
//call login activity
}
First, check whether user logged in before. Use SharedPreferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
Boolean loggedIn = prefs.getBoolean("loggedIn", false);
if(loggedIn != null && loggedIn)
{
//open main activity
}else{
//open login page
}
and when user logs in, save the login information to SharedPreferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
prefs.edit().putBoolean("loggedIn", true);
That is all you need.
Try this, Working code
in your Login page
// Session Manager Class
SessionManagerFor_Signin session;
private EditText EMAIL, PASSWORD;
private Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.sign_in);
// Session Manager
session = new SessionManagerFor_Signin(getApplicationContext());
login = (Button) findViewById(R.id.loginbutton);
EMAIL = (EditText) findViewById(R.id.EmaileditText1);
PASSWORD = (EditText) findViewById(R.id.passwordeditText2);
login.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loginbutton:
email = EMAIL.getText().toString();
password = PASSWORD.getText().toString();
if (email.equals("") || password.equals(""))
{
// user didn't entered user name or password
// Show alert asking him to enter the details
alert.showAlertDialog(sign_in.this, "Login Failed...","Please Enter Email and Password", false);
}
else
{
// fetch the Password form database for respective Email
storedPassword = DB.getSinlgeEntry(email);
if (password.equals(storedPassword))
{
session.createLoginSession(email, password);
Toast.makeText(sign_in.this, "Login Successfull",Toast.LENGTH_LONG).show();
Intent intent = new Intent(sign_in.this, Page1_Landing.class);
startActivity(intent);
finish();
}
}
break;
}
SessionManagerFor_Signin.java
public class SessionManagerFor_Signin
{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "SharedPref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_EMAILID = "email";
// Email address (make variable public to access from outside)
public static final String KEY_PASSWORD = "password";
// Constructor
public SessionManagerFor_Signin(Context context)
{
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
// Create login session
public void createLoginSession(String email, String password)
{
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_EMAILID, email);
// Storing email in pref
editor.putString(KEY_PASSWORD, password);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin()
{
// Check login status
if(this.isLoggedIn())
{
Intent intent = new Intent(_context,Page1_Landing.class);
// Closing all the Activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Toast.makeText(getApplicationContext(),email, Toast.LENGTH_LONG).show();
_context.startActivity(intent);
}
else
{
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user mail
user.put(KEY_EMAILID, pref.getString(KEY_EMAILID, null));
// user password
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser()
{
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
Intent intent = new Intent(_context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
_context.startActivity(intent);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn()
{
return pref.getBoolean(IS_LOGIN, false);
}
}
Further you want Reference Find below link
Link For Reference
SIf you want to do this with shared preferences when the user log in to the app share a preference..
SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
prefs.edit().putBoolean("staylogin", true).commit();
And if you want to log out on buton click set the preference..
SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
prefs.edit().putBoolean("staylogin", false).commit();
In order to start your app without log in screen you can use a splash screen before the others and check the shared preference...
SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
Boolean state = prefs.getString("staylogin", false);
if (state) {
//Start Main Activity
} else {
//Start Log in activity
}

Create menu login but i can get in with empty password in Android Java

There is a problem with my java code, when I emptied my username and password and click login, I can still get into the main menu, if there are less with my code? where do I need to fix it? please help
LoginActivity.Java
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), info.androidhive.slidingmenu.MainActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Please write your PHP code. I think that you missed a condition !!!
Also, you can add a condition in your LoginActivity like that:
if((inputEmail.getText().toString()).isEmpty() ||
(inputPassword.getText().toString()).isEmpty())
{
Toast.makeText(LoginActivity.this,"Please fill out Username and Password !!!",
5000).show();
}
else
{
//check for login response
}

Categories

Resources