How can I get username and password from SharedPreferences in Android? - java

I am trying to recover the username and password to be able to start a session.
These are the users of the sharedPreferences.
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="admin">1234</string>
<string name="user">user0987</string>
</map>
And this is the method
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sp1 = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
String user = sp1.getString(userInput.getText().toString(), "User not found");
String pass = sp1.getString(passwordInput.getText().toString(), "Password is not correct");
if(user.equals(userInput.getText().toString()){
Toast.makeText(MainActivity.this, "User Exists", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this, "User not found", Toast.LENGTH_SHORT).show();
}
}
});
This is the code that puts data in SharedPreferences
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user = userInput.getText().toString();
String pass = passwordInput.getText().toString();
if(user.isEmpty()){
error.show();
} else if (pass.isEmpty()){
error2.show();
} else{
SharedPreferences sp=getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor Ed=sp.edit();
Ed.putString(user,pass);
Ed.commit();
Toast.makeText(MainActivity.this, "Register completed", Toast.LENGTH_SHORT).show();
}
}
});

Please try to use next code when you retrieve data from SP:
SharedPreferences sp1 = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
String pass = sp1.getString(userInput.getText().toString(), null);
if (pass != null) {
Toast.makeText(MainActivity.this, "User Exists", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this, "User not found", Toast.LENGTH_SHORT).show();
}
You are saving data in form of "user:pasword", so you need to get it the same way, using user name as the key.

You need to add keys for saving for data in SharedPreferences editor.
Currently you are using entered username as key, It can be change according to entered data in edittext, because user will not enter same username every time, but for saving and getting data to/from SharedPreferences we need a specific key.
You can add keys for saving user name and password like following code:
SharedPreferences sp=getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor ed=sp.edit();
ed.putString("user",user);
ed.putString("pass",pass);
ed.commit();
For getting data
SharedPreferences sp1 = getSharedPreferences("data", Context.MODE_PRIVATE);
String userName = sp1.getString("user", "User not found");
String password = sp1.getString("pass", "Password is not correct");
For more info regarding Sharedpref check Official documentation for Save key-value data using SharedPreferences

Related

Firebase Auth: getCurrentUser from different Activities?

I have an app with a login screen. Now, i just want to get the DisplayName of the user which is signed in in another Activity. How can I get this name?
Use getCurrentUser():
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, getEmail or etc
String name = user.getDisplayName();
Log.d("TAG" + name) // the name ...
}
https://firebase.google.com/docs/auth/android/manage-users#get_the_currently_signed-in_user
Using SharedPreferences or Bundle you can get it.
private void onAuthSuccess(FirebaseUser currentUser) {
userId = currentUser.getUid();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
if (currentUser.getDisplayName() != null){
editor.putString("userName", currentUser.getDisplayName());
} else if (currentUser.getEmail() != null){
editor.putString("useremail", currentUser.getEmail());
}
editor.putString("userId", currentUser.getUid());
editor.commit();
}
Another Activity you can get it below
SharedPreferences sharedPref =
PreferenceManager.getDefaultSharedPreferences(this);
String displayUser = sharedPref.getString("userName",null);
String displayEmail = sharedPref.getString("useremail",null);

How to use SharedPreferences from differents activities? [duplicate]

This question already has answers here:
sharedpreferences between activities
(3 answers)
Android Shared preferences with multiple activities
(3 answers)
Closed 4 years ago.
I have searched how to use SharedPreferences in Android and ran into a problem.
I save some Strings in the SP and I save the data in Main Activity this way:
in OnCrete function I define:
sp = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = sp.edit();
and then I save the strings to SharedPreferences in the following way:
mail = edmail.getText().toString();
pass = edpass.getText().toString();
color = edcolor.getText().toString();
phone = edphone.getText().toString();
SharedPreferences.Editor editor = sp.edit();
if (mail.equals("") || pass.equals("") || color.equals("") || phone.equals("")||img.getDrawable() == null
)
Toast.makeText(getApplicationContext(), "you have to fill all the fields", Toast.LENGTH_SHORT).show();
else {
editor.putString("mail", mail);
editor.putString("phone", phone);
editor.putString("color", color);
editor.putString("password", pass);
editor.apply();
Toast.makeText(getApplicationContext(), "Signed up", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, Main2Activity.class);
intent.putExtra("img",bitmap);
startActivity(intent);
}
In the second activity I am trying to retrieve the data:
#Override
public void onClick(View v) {
Intent intent=getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("img");
imgv.setImageBitmap(bitmap);
LoadPreferences();
//txtmail.setText(value);
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString("mail", null) ;
Toast.makeText(this,data, Toast.LENGTH_LONG).show();
}
The toast presents the default value instead the real value.
You saved your data in MyPref file which is a different shared preference file as compared to PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
so use
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", 0);
instead of
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
getSharedPreferences("MyPref", 0); will always creates a new file if does not exist whereas the getDefaultSharedPreferences gives you a pref file which is can be used by whole app whit mentioning any name
Change your loading declaration:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
To:
SharedPreferences sp = getApplicationContext().getSharedPreferences("MyPref", 0);

Android Studio: 2 different activities in 1 button

I want to make the login button to dispatch into 2 different activities using the flag column on the database??
if the tenant logged in it will redirect to the tenant activity
and when the landlord is logged in it will redirect to the other activity?
public void onResponse(String response) {
Log.e(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);
// Check for error node in json
if (success == 1) {
String username = jObj.getString(TAG_USERNAME);
String id = jObj.getString(TAG_ID);
Log.e("Successfully Login!", jObj.toString());
Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id);
editor.putString(TAG_USERNAME, username);
editor.commit();
// go to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
Inside the onClickListener() method of your log in button,you can put a if() statement.
Steps To Do this
1. Get the data from the username and password field and use that in your query to retrieve the data from the database
2. Store the data you retrieved in a String like below because you will get only one row:
String flag = cursor.getString(7); //skipping the cursor and other database part
3. Now you can put the if() statement in the onClickListener of login button after getting the String flag value like:
if(flag.equals(landlord)){
Intent intent = new Intent(this,Landlord.class);
startActivity(intent);
}
else{
Intent intent = new Intent(this,Tenant.class);
startActivity(intent);
}
Anyhow you will be querying to verify username & password, at the same time you could also fetch the flag information and store it in locally(reduces the database calls).
Store those data in a map with key as username (Assumption username will be unique) and flag as value.
Map<String,String> mapToRouting = new Map<String,String>();
Now for routing different activities, inside the button click method try like
public static void buttonClickMethod(){
//textFieldUserName is the username of user trying to login
if(isLanlord(textFieldUserName)){
//this means user is Landlord & put code to redirect to corresponding screen
}
else{
//put code to which redirects to tenants screen!
}
}
Method to find whether the user is landlor or not.
public static void isLandlord(String userName){
boolean result = false;
if(mapToRouting.get(userName).equalsIgnorecase("Landlord"))
result = true;
return result;
}
Hope this will be helpful.

How to keep login user on an application in Android

I have an app that requires user to register.
User opens the app, registers and logs in.
Does some stuff with the app and closes it.
Opens the app again, the user is recognized so he doesn't need to login again.
This is the code used for login:
ArrayList<ArrayList<Object>> data = dm.getAllRowsAsArrays();
for (int position=0;position<data.size();position++)
{
ArrayList<Object> row = data.get(position);
mail1=row.get(0).toString();
pass1=row.get(2).toString();
if((mail1.equals(mail))&&(pass1.equals(pass)))
{
Toast.makeText(getApplicationContext(),"Login Success",Toast.LENGTH_LONG).show();
Intent i=new Intent(getApplicationContext(),usermain.class);
startActivity(i);
}
}
After login goto usermain activity, but if I press the emulator back button then I can see the login page with the details I typed for login.
How can I remove it?
You can use startActivityForResult instead of startActivity and then use this sample onActivityResult method in your login activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == LOGIN_CODE) { // this code you should provide in startActivityForResult
this.finish();
}
}
This will prevent you from going back to login activity. If you'd like to persist user's data, use also SharedPreferences as described by others.
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean(PREF_USER_NAME, userName);
editor.commit();
}
public static boolean getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
in your main activity check this first:
if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
{
// call Login Activity
}
else
{
// Call Next Activity
}
Use SharedPreference for that in your onCreate() methos like..
SharedPreferences sp=getSharedPreferences("pref",0);
if(sp.getInt("PREFERENCES_LOGIN", 99)==0)
{
setContentView(R.layout.activity_login_screen);
}else if(sp.getInt("PREFERENCES_LOGIN", 99)==1)
{
Intent intent=new Intent(GetLoginDetailsScreen.this,MenuScreen.class);
startActivity(intent);
finish();
super.onBackPressed();
}else{
setContentView(R.layout.activity_login_screen);
}
after login Successful add this..
sp=getSharedPreferences("pref",0);
SharedPreferences.Editor edit= sp.edit();
edit.putInt("PREFERENCES_LOGIN", 1);
edit.commit();
try this
if((mail1.equals(mail))&&(pass1.equals(pass)))
{
Toast.makeText(getApplicationContext(),"Login Success",Toast.LENGTH_LONG).show();
Intent i=new Intent(getApplicationContext(),usermain.class);
finish();
startActivity(i);
}
so here is your solution when the user successfully logged in set the shared preferences in your login class class like this
//declare pref editor
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefsEditor = prefs.edit();
//paste below peace of code when the loginwill be success
prefsEditor.putString("remember", "yes");
prefsEditor.commit();
//now in your first activity you just check the shared pref value to know the user is logged in or not
SharedPreferences prefs;
String Log;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
Log=prefs.getString("remember", "");
//now check the value of shared pref and apply the condition like this
Intent intent ;
if(register.equalsIgnoreCase("yes"))
{
intent = new Intent(this, Home.class);
startActivity(intent);
finish();
}
else
{
intent = new Intent(this, Login.class);
startActivity(intent);
finish();
}

Temporarily disable login after failed attempts

I am trying to create a login screen for my app that disables the login button for 5 minutes after 3 failed login attempts.
However, in my app, the button can be easily enabled again by closing the app and starting it again.
How do I fix this?
Code:
public class LogIn extends Activity {
EditText username = null;
EditText password = null;
Button loginbutton = null;
int counter = 2;
String user = "admin";
String pw = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
loginbutton = (Button) findViewById(R.id.loginbutton);
loginbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{ String name = username.getText().toString();
String pass = password.getText().toString();
if (name.equals(user) && pass.equals(pw))
// Successful Login
{ Intent intent = new Intent(LogIn.this, MainApp.class);
startActivity(intent);
}
else if (name.equals("") || pass.equals(""))
// Missing username or password
{ Toast alert = Toast.makeText(LogIn.this, "Please enter a username or password", Toast.LENGTH_SHORT);
alert.show();
}
else if (counter == 0)
// Disable button after 3 failed attempts
{ loginbutton.setEnabled(false);
Toast alert = Toast.makeText(LogIn.this, "Login Disabled for 5 mins", Toast.LENGTH_SHORT);
alert.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable()
{ #Override
public void run()
{ loginbutton.setEnabled(true);
counter = 2;
}
}, 300000);
}
else
// Wrong password
{ Toast alert = Toast.makeText(LogIn.this, "Wrong Credentials", Toast.LENGTH_SHORT);
alert.show();
counter--;
};
}
});
};
}
In that case you can save the CurrentTime in the preference and check it before attempting to login again
This is how a preference works
// Initiate the preference with Preference Filename and Access Mode for other Apps
SharedPreferences pref = getSharedPreferences("LoginTrack", Context.MODE_PRIVATE); // "LoginTrack" is the preference Name
// read the preference
long l = prefs.getLong("LastLoginDateTime", new Date().getTime());
String Attempts= pref.getString("MaxAttempts", "");
//To edit and save preferences again when you try login
Date dt = new Date(); // Current Time to Track loginTime
prefs.edit().putLong("LastLoginDateTime", dt.getTime()).commit();
prefs.edit().putString("MaxAttempts", "5").commit();
After Retrieve the data compere them and validate as you wish
You can use Shared Preference to store no of failure attempts. If a user fails to login into the app you can store no of attempts and time of that attempt in shared pref.
SharedPreferences pref = this.getSharedPreferences("Sample", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("ATTEMPTs", "5");
editor.putString("ATTEMPT_Time", System.currentTimeMillis());
editor.commit();
On launch of login activity check no of attempts in shared preference and enable or disable login button accordingly.
SharedPreferences pref = this.getSharedPreferences("Sample", Context.MODE_PRIVATE);
String no_attempt = pref.getString("ATTEMPTs", "");
String time= pref.getString("ATTEMPT_Time"," ");
if(no_attempt>5 && Long.parseLong(time)>(System.currentTimeMillis()-300000))
{
btn_login.setVisibilty(View.INVISIBLE);
}
else
{
//login
}

Categories