In my application's login screen, i am fetching a JSON response into the shared preferences in my retrofit2 onResponse method. I get everything as correct from the database and putting as correctly into the shared preferences. I am getting an User_Role from db as string, then based on User_Role, i am directing the user to according activity. I need to reach that User_Role in case R.id.Login: step. In my Logcat i see my response is as i want. I check with Toast after i commit preferences, if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So the only problem i can not retrieve it. Please help.
Because of everything works correctly in my apicall(because i checked every step with Toast.makeText.show(); on screen) i am only putting my LoginActivity.class code below,
LoginActivity.class :
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button bSignUp, bLogin;
EditText etPassword, etEmail;
private ProgressDialog progressDialog;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bSignUp = (Button) findViewById(R.id.bSignUp);
bLogin = (Button) findViewById(R.id.bLogin);
bSignUp.setOnClickListener((View.OnClickListener) this);
bLogin.setOnClickListener((View.OnClickListener) this);
etPassword = (EditText) findViewById(R.id.etPassword);
etEmail = (EditText) findViewById(R.id.etEmail);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Logging in");
progressDialog.setMessage("Please wait ....");
bLogin.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bSignUp:
Intent SignUpIntent = new Intent(this, SignUpActivity.class);
startActivity(SignUpIntent);
break;
case R.id.bLogin:
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
if (!email.isEmpty() && !password.isEmpty()) {
progressDialog.show();
loginProcess(email, password);
//Here i need to obtain SharedPreferences that i filled in onResponse Method. It goes directly wrong email or password statement. Because of can't retrieve settings.getString("User_Role","")
SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
String userRole = settings.getString("User_Role","");
Toast.makeText(LoginActivity.this, userRole, Toast.LENGTH_SHORT).show();
if (userRole.equals("Organizator")) {
intent = new Intent(this, OrganizerHomeActivity.class);
startActivity(intent);
} else if(userRole.equals("Speaker") || userRole.equals("Listener")) {
intent = new Intent(this, UserHomeActivity.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
private void loginProcess(String email, String password) {
LoginAPI loginAPI = RetrofitService.getClient().create(LoginAPI.class);
retrofit2.Call<UserList> call = loginAPI.loginUser(email,password);
call.enqueue(new Callback<UserList>(){
#Override
public void onResponse(Call<UserList> call, Response<UserList> response) {
if(response.isSuccessful()){
List<User> userLists = response.body().getUser();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putBoolean(Constants.IS_LOGGED_IN, true);
prefEditor.putString("UserName", userLists.get(0).getFirstName());
prefEditor.putString("SSN", userLists.get(0).getsSN());
prefEditor.putString("User_Role", userLists.get(0).getUserRole());
prefEditor.commit();
// In my Logcat i see my respnse is as i want, and i check with below Toast if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So there is no problem.
Toast.makeText(LoginActivity.this, "response.success "+settings.getString("User_Role",""), Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<UserList> call, Throwable t) {
Toast.makeText(LoginActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
Put your SharedPreference logic after onResponse success. it's because it executes before your response get. that's why it empty. so Change code like this
private void checkMethod(){
SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
String userRole = settings.getString("User_Role","");
Toast.makeText(LoginActivity.this, userRole, Toast.LENGTH_SHORT).show();
if (userRole.equals("Organizator")) {
intent = new Intent(this, OrganizerHomeActivity.class);
startActivity(intent);
} else if(userRole.equals("Speaker") || userRole.equals("Listener")) {
intent = new Intent(this, UserHomeActivity.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
}
}
And Call this method from onResponse like below
public void onResponse(Call<UserList> call, Response<UserList> response) {
if(response.isSuccessful()){
List<User> userLists = response.body().getUser();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putBoolean(Constants.IS_LOGGED_IN, true);
prefEditor.putString("UserName", userLists.get(0).getFirstName());
prefEditor.putString("SSN", userLists.get(0).getsSN());
prefEditor.putString("User_Role", userLists.get(0).getUserRole());
prefEditor.commit();
// In my Logcat i see my respnse is as i want, and i check with below Toast if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So there is no problem.
Toast.makeText(LoginActivity.this, "response.success "+settings.getString("User_Role",""), Toast.LENGTH_SHORT).show();
checkMethod();
}
Try to start intent condition in the response method. No need to store value in shared preferences.
Related
Login using JSON with shared Preferences When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView3);
usr_number = findViewById(R.id.usr_pass);
go = findViewById(R.id.button);
signup = findViewById(R.id.signup_signup);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getjsondata();
String hhh = usr_number.getText().toString();
url = "http://readnow.flatdeal4u.com/Api/Register.aspx?mobile=" + hhh + "&choice=2";
//Toast.makeText(MainActivity.this, ""+hhh, Toast.LENGTH_SHORT).show();
if (usr_number.getText().toString().isEmpty()) {
usr_number.setError("Enter Phone Number");
Toast.makeText(MainActivity.this, "Enter Details", Toast.LENGTH_SHORT).show();
} else {
if (usr_number.getText().toString().equals("" + hhh)) {
Intent intent = new Intent(MainActivity.this, select_your_exams.class);
startActivity(intent);
pref = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
pref.getString("mobilenumber", hhh);
pref.getString("nameofuser", "");
}
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Signup.class);
startActivity(intent);
}
});
}
Here are my JSON method codes:
public void get JSON data) {
final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener < String > () {
#Override
public void onResponse(String response) {
try {
JSONObject jobj = new JSONObject(response);
JSONArray array = jobj.getJSONArray("userInfos");
//Toast.makeText(MainActivity.this, "data found"+array, Toast.LENGTH_LONG).show();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
final Phn_modal mo = new Phn_modal();
final String mobile = obj.getString("mobileNumber");
final String name = obj.getString("fullName");
final String email = obj.getString("emailId");
Toast.makeText(MainActivity.this, "Welcome You-" + name, Toast.LENGTH_LONG).show();
mo.setMobile(mobile);
mo.setName(name);
mo.setEmailId(email);
mo.getMobile(mobile);
mo.getMobile(name);
editor.putString("mobilenumber", mobile);
editor.putString("nameofuser", name);
editor.apply();
editor.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
i think your question is , you login first time, and next time you again visit application that time directly go to the activity withouth asking login,
then you can try this.
public void storeString(SharedPreferences sharedPreferences, String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
above function is used to store the specific value in our shared prefrence, with given key.
Now when we hint the login button that time if login is success then store the login success value in our prefrence.
this one is usefull for again visit in your application
storeString(mPreferences, "Login_flag", "true");
-> Now, when we again visit application check the our prefrence is true or false.
if our prefrence is true then user already login, not required to login again
Check like this,
if(mPreferences.getString(PreferenceList.LOGIN_FLAG, "false").equals("true")){
//if alredy login then access this
}else{
//if not login then access this
}
if you want to create a login session in your app then you should create an preference class in your project and save data in that class and match the data where you want to use follow this answer to maintain the login session in your app:- Preventing users to login again after closing the app
I am trying to get a user's login credentials while he signing in. I am sending to my database User_Email and User_Password then returning a Json like below. Actually the problem is simple but i dont know the solution, i am kinda new. I am %100 sure the error in my onResponse method. Because I am seeing this successfull response Toast, so i am getting successfull response but the problem here i dont know how to get this Json response into sharedpreferences. Thanks.
{
"User": [
{
"SSN": "123456789",
"FirstName": "Furkan",
"User_Role": "1"
}
]
}
And my model class for this response is :
public class UserList {
#SerializedName("User")
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
public class User {
#SerializedName("SSN")
public String sSN;
#SerializedName("FirstName")
public String firstName;
#SerializedName("User_Role")
public intuserRole;
public String getsSN() {
return sSN;
}
public void setsSN(String sSN) {
this.sSN = sSN;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getUserRoleTypeId() {
return userRoleTypeId;
}
public void setUserRoleTypeId(int userRoleTypeId) {
this.userRoleTypeId = userRoleTypeId;
}
}
I am trying to add these userRoleTypeId, firstName and sSN to SharedPreferences in my call.enqueue onResponse. But i could not figure it out.
Here is my LoginActivity.class for the login:
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button bSignUp, bLogin;
EditText etPassword, etEmail;
private int userRoleTypeId;
private SharedPreferences sharedPreferences;
private ProgressDialog progressDialog;
Intent intent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bSignUp = (Button) findViewById(R.id.bSignUp);
bLogin = (Button) findViewById(R.id.bLogin);
bSignUp.setOnClickListener((View.OnClickListener) this);
bLogin.setOnClickListener((View.OnClickListener) this);
etPassword = (EditText) findViewById(R.id.etPassword);
etEmail = (EditText) findViewById(R.id.etEmail);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Logging in");
progressDialog.setMessage("Please wait ....");
sharedPreferences = getApplicationContext().getSharedPreferences("LoginActivity",MODE_PRIVATE);
bLogin.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bSignUp:
Intent SignUpIntent = new Intent(this, SignUpActivity.class);
startActivity(SignUpIntent);
break;
case R.id.bLogin:
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
if (!email.isEmpty() && !password.isEmpty()) {
progressDialog.show();
loginProcess(email, password);
this.userRoleTypeId = sharedPreferences.getInt(Constants.USERROLE, 0);
if (userRoleTypeId == 1) {
intent = new Intent(this, OrganizerHomeActivity.class);
startActivity(intent);
} else if(userRoleTypeId == 2 || userRoleTypeId == 3) {
intent = new Intent(this, UserHomeActivity.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
private void loginProcess(String email, String password) {
LoginAPI loginAPI = RetrofitService.getClient().create(LoginAPI.class);
retrofit2.Call<UserList> call = loginAPI.loginUser(email,password);
call.enqueue(new Callback<UserList>(){
#Override
public void onResponse(Call<UserList> call, Response<UserList> response) {
//I am sure the fault in here. In below i tried to take Json response and fetch it into the Shared Preferences.
UserList userLists = response.body().getUser();
if(response.isSuccessful()){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(Constants.IS_LOGGED_IN, true);
// editor.putString(Constants.NAME, userLists.getFirstName);
//editor.putString(Constants.SSN, userLists.getsSN);
// editor.putInt(Constants.USERROLE, userLists.getuserRoleTypeId);
editor.apply();
// I am seeing this successfull response toast, so i am getting successfull response but the problem here i dont know how to get this Json response into sharedpref.
Toast.makeText(LoginActivity.this, "successfull response", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<UserList> call, Throwable t) {
Toast.makeText(LoginActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
Try this
if(response.isSuccessful()){
List<User> userLists = response.body().getUser();
SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
editor.putBoolean(Constants.IS_LOGGED_IN, true);
prefeditor.putString("UserName", userLists.getUser().getFirstName());
prefEditor.putString(Constants.SSN, userLists.getUser().getsSN());
prefEditor.putInt(Constants.USERROLE, userLists.getUser().getUserRoleTypeId());
prefEditor.commit();
}
When I'm logging in on my app my I want my login page will not show anymore if the user is already logged in before. Because everytime a user terminates the app and opens the app again the login page will show with the loading message. I want to implement it because if the user opens the app without data connection the user will still go to his page.
Well here is my code.
pref = getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
editor = pref.edit();
editor.putBoolean("hasLoggedIn", true);
editor.commit();
boolean hasLoggedIn = pref.getBoolean("hasLoggedIn", false);
if(hasLoggedIn){
String username = pref.getString("username", "");
String password = pref.getString("password", "");
if (!username.equals("") && (!password.equals(""))) {
postData.put("username", username);
postData.put("password", password);
authenticate(postData);
}
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(etUsername.getText().toString())) {
Toast.makeText(LoginActivity.this, "Username is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etPassword.getText().toString())) {
Toast.makeText(LoginActivity.this, "Password is empty", Toast.LENGTH_SHORT).show();
return;
}
editor = pref.edit();
postData.put("username", etUsername.getText().toString());
postData.put("password", MD5.encrypt(etPassword.getText().toString()));
editor.commit();
authenticate(postData);
}
});
}
authenticate
private void authenticate(final HashMap<String, String> postData){
PostResponseAsyncTask task1 = new PostResponseAsyncTask(LoginActivity.this, postData,
new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, s);
if (s.contains("renter")) {
// Login success, Save to prefs
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.putString("userlevel", s);
editor.commit();
Toast.makeText(LoginActivity.this, "Renter Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(LoginActivity.this, RenterTabs.class);
startActivity(in);
finish();
} else if (s.contains("owner")) {
// Login success, Save to prefs
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.putString("userlevel", s);
editor.commit();
Toast.makeText(LoginActivity.this, "Owner Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(LoginActivity.this, OwnerTabs.class);
startActivity(in);
finish();
} else if (s.contains("driver")) {
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.putString("userlevel", s);
editor.commit();
Toast.makeText(LoginActivity.this, "Driver Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(LoginActivity.this, DriverTabs.class);
startActivity(in);
finish();
}else if(s.contains("-1")){
Toast.makeText(LoginActivity.this, "Wrong username or password...", Toast.LENGTH_SHORT).show();
}
}
});
task1.execute("http://carkila.esy.es/carkila/authenticate.php");
I don't see why should if(hasLoggedIn) line ever be negative. You always put a true value in hasLoggedIn shared preferences and then you have an if statement on that.
So what I've understood so far is, you want to click the login button automatically when some user is already logged in your application before using the username and the password stored in the SharedPreferences. So if I'm assuming the problem correctly, here's how you can implement this.
I'm just rewriting your code. See the comments for better understanding.
pref = getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
boolean hasLoggedIn = pref.getBoolean("hasLoggedIn", false);
// Move the onClickListener outside the if statement
// Because, if the user is not already logged in
// Then you need to have a click action on this button.
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(etUsername.getText().toString())) {
Toast.makeText(LoginActivity.this, "Username is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etPassword.getText().toString())) {
Toast.makeText(LoginActivity.this, "Password is empty", Toast.LENGTH_SHORT).show();
return;
}
editor = pref.edit();
postData.put("username", etUsername.getText().toString());
postData.put("password", MD5.encrypt(etPassword.getText().toString()));
editor.commit();
authenticate(postData);
}
});
if(hasLoggedIn) {
String username = pref.getString("username", "");
String password = pref.getString("password", "");
// Remove this
// if (!username.equals("") && (!password.equals(""))) {
// postData.put("username", username);
// postData.put("password", password);
// authenticate(postData);
// }
// Simply put this in here
btnLogin.performClick();
}
And save the preference after a successful login in the authenticate function
private void authenticate(...) {
// On a successful login
editor = pref.edit();
editor.putBoolean("hasLoggedIn", true);
editor.commit();
}
My mobile app needs a feature that from the splash screen when the user is still logged in it wont show the login page any more using shared preference. Here are my codes for references.
Splash
public class Splash extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Thread myThread = new Thread(){
#Override
public void run() {
try {
sleep(2000);
Intent in = new Intent (getApplicationContext(),MainActivity.class);
startActivity(in);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
myThread.start();
}
}
Loginpage(the one that will be skipped if user doesn't logs out)
public class MainActivity extends AppCompatActivity {
final String TAG = this.getClass().getName();
Button btnLogin;
EditText etUsername, etPassword;
TextView tvRegister;
SharedPreferences pref;
SharedPreferences.Editor editor;
HashMap<String, String> postData = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etUsername = (EditText) findViewById(R.id.etFirstname);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
tvRegister = (TextView) findViewById(R.id.tvRegister);
pref = MainActivity.this.getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
String username = pref.getString("username", "");
String password = pref.getString("password", "");
if (!username.equals("") && (!password.equals(""))) {
postData.put("username", username);
postData.put("password", password);
authenticate(postData);
}
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor = pref.edit();
editor.clear();
postData.put("username", etUsername.getText().toString());
postData.put("password", MD5.encrypt(etPassword.getText().toString()));
editor.commit();
authenticate(postData);
}
});
tvRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(in);
}
});
}
private void authenticate(final HashMap<String, String> postData){
PostResponseAsyncTask task1 = new PostResponseAsyncTask(MainActivity.this, postData,
new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, s);
if (s.contains("renter")) {
// Login success, Save to prefs
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.commit();
Toast.makeText(MainActivity.this, "Renter Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this, RenterTabs.class);
startActivity(in);
finish();
} else if (s.contains("owner")) {
// Login success, Save to prefs
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.commit();
Toast.makeText(MainActivity.this, "Owner Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this, OwnerTabs.class);
startActivity(in);
finish();
} else if (s.contains("-1")) {
Toast.makeText(MainActivity.this, "Wrong username or password...", Toast.LENGTH_SHORT).show();
}
}
});
task1.execute("http://carkila.esy.es/carkila/authenticate.php");
task1.setEachExceptionsHandler(new EachExceptionsHandler() {
#Override
public void handleIOException(IOException e) {
Toast.makeText(getApplicationContext(), "Cannot Connect to Server", Toast.LENGTH_SHORT).show();
}
#Override
public void handleMalformedURLException(MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Error", Toast.LENGTH_SHORT).show();
}
#Override
public void handleProtocolException(ProtocolException e) {
Toast.makeText(getApplicationContext(), "Protocol Error", Toast.LENGTH_SHORT).show();
}
#Override
public void handleUnsupportedEncodingException(UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(), "Encoding Error", Toast.LENGTH_SHORT).show();
}
});
}
}
The classes that It'll be going are OwnerTabs.java or RenterTabs.java
Thanks guys :)
In the login class where you're saving the username and password to the sharedpreferences, you should also save a boolean value isLoggedIn- true if the login is successful, and false if not.
Then, you can then put the authenticate method in your splash activity too and call it using the saved username and password values (if the boolean is true). You should rather extract the authenticate method to a separate class and call it from login as well as the signup.
If calling the authenticate method is not important if the user is already logged in, you can simply check the isLoggedIn in your splash activity and direct the user to Owner or Renter class.
So I have two screens, a set password screen and an enter password (login) screen. I'd like it to pop up the enter password screen if there is no password (ie, the application's never been used) and upon subsequent launches go to the login screen. If the user enters a password, it compares with the value stored in sharepreferences and continues to the menu if it's correct. But the login screen seems unable to access the password after the set-password screen is used.
How do I make the login screen see the password set by the registration page?
Here's the create password code:
public class CreatePassword extends Activity {
public EditText setPass1, setPass2;
String newPass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createpassword);
setPass1 = (EditText)findViewById(R.id.editTextSetPassword);
setPass2 = (EditText)findViewById(R.id.editTextRepeatSetPassword);
}
public void btnSubmitNewPassword(View v){
if(setPass1.getText().toString() != "") {
if (setPass1.getText().toString().equals(setPass2.getText().toString())) {
newPass = setPass1.getText().toString();
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("sharedPref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putString("password", newPass);
prefEditor.apply();
Toast.makeText(getApplicationContext(), newPass, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "New Password Set", Toast.LENGTH_LONG).show();
startActivity(new Intent(CreatePassword.this, Menu.class));
} else {
Toast.makeText(getApplicationContext(), "Passwords don't match!", Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(), "Please Enter Desired Password", Toast.LENGTH_LONG).show();
}
}
}//end CreatePassword class
And the EnterPassword (login) screen that refuses to use the password just set:
public class EnterPassword extends Activity {
EditText editTextPasswordAttempt;
SharedPreferences sharedPref;
String passwordAttempt, passwordActual;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enterpassword);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
boolean passwordExists = sharedPref.contains("password");
if(passwordExists == false){
startActivity(new Intent(EnterPassword.this, CreatePassword.class));
}
editTextPasswordAttempt = (EditText)findViewById(R.id.editTextPassword);
}
public void btnSubmitToMenu(View v){
passwordActual = sharedPref.getString("password", );
Toast.makeText(getApplicationContext(), passwordActual, Toast.LENGTH_LONG).show();
passwordAttempt = editTextPasswordAttempt.getText().toString();
if(passwordAttempt.equals(passwordActual)) {
startActivity(new Intent(EnterPassword.this, Menu.class));
}
else{
Toast.makeText(getApplicationContext(), "Invalid Password", Toast.LENGTH_LONG).show();
}
}
}
You are using 2 different SharedPreferences.
In CreatePassword activity you do:
getApplicationContext().getSharedPreferences("sharedPref", MODE_PRIVATE);
But in EnterPassword activity you do:
PreferenceManager.getDefaultSharedPreferences(this);
If you use the same line in both Activities it should work.
You need to use same name of SharedPreferences while access SharedPreferences values.Access SharedPreferences in EnterPassword activity with same way using below line:
getApplicationContext().getSharedPreferences("sharedPref", MODE_PRIVATE);