I made a simple login activity in which I used android sqlite database to store login information i.e. username and password. When user click create account button in signup activity, s/he will be transferred to another activity where they can see what is their username and pass. In that screen I need to check if preferences are clear and then the text of the button will be changed based on the decision.
I passed the info between activities using SharedPreference, but I can not delete it or clear it when the user clicks sign out.. Below is the code of both activities..
Here's my SignUp.java
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get Refferences of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
tv=(TextView)findViewById(R.id.textView);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
// check if any of the fields are vaccant
if(userName.equals("")||password.equals("")||confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
if(password.length()<8) {
Toast.makeText(getApplicationContext(),"Password must be 8 digits longer",Toast.LENGTH_LONG).show();
}
else {
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password);
try {
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name,userName);
editor.putString(Pass,password);
editor.commit();
} catch (NullPointerException e) {
e.printStackTrace();
}
intent=new Intent(getApplicationContext(),AfterLogin.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
loginDataBaseAdapter.close();
}
And the AfterLogin.Java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.afterlogin);
username=(TextView)findViewById(R.id.Username);
name=(TextView)findViewById(R.id.Name);
user=(TextView)findViewById(R.id.User);
pass=(TextView)findViewById(R.id.Pass);
sout=(Button)findViewById(R.id.SignOut);
s= sharedPreferences.getString(Name,"");
us=sharedPreferences.getString(Pass,"");
username.setText(s);
name.setText(s);
user.setText(s);
pass.setText(us);
sout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.clear();
editor.commit();
String n=sharedPreferences.getString(Name,"");
if (n == null) {
sout.setText("Signed Out");
}
}
});
}
AfterLogin.java you have checked
n == null
but passed the default value as empty for String n
String n=sharedPreferences.getString(Name,""); //EMPTY
change
if (n==null) {
sout.setText("Signed Out");
}
to
if (n.isEmpty()) {
sout.setText("Signed Out");
}
Can you try by committing the clear and commit in a single line. Like editor.clear().commit() or editor.clear().apply(). This might help you since you are committing or applying changes on editor object after making changes.
The problem could be that you are using String n=sharedPreferences.getString(Name,""); which always returns something. Default value if preference doesn't exists or it's value if it exists.
To check if a preference has been deleted i'd better use String n=sharedPreferences.contains(Name); which returns a boolean that shows if the preference exists or not.
Hope it helps!
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
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.
I have a "save" checkbox in the login activity. If the user check it, next time, when the application going to start , skip the login activity. Although, If User wants to logout, the checkbox in the login activity going to set unchecked. This problem, what I can't solve.
Login Activity the saveing part:
saveLogin = loginPreferences.getBoolean("saveLogin", false);
if (saveLogin == true) {
etEmail.setText(loginPreferences.getString("email", ""));
etPassword.setText(loginPreferences.getString("password", ""));
saveLoginCheckBox.setChecked(true);
// editor.putBoolean("checked", true);
/* editor.putString("email", "etEmail"); // Storing string
editor.putString("password", "etPassword"); // Storing string*/
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etEmail.getWindowToken(), 0);
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
if (saveLoginCheckBox.isChecked()) {
loginPrefsEditor.putBoolean("saveLogin", true);
loginPrefsEditor.putString("email", email);
loginPrefsEditor.putString("password", password);
loginPrefsEditor.commit();
} else {
loginPrefsEditor.clear();
loginPrefsEditor.commit();
}
Backendless.UserService.login(email, password, new AsyncCallback<BackendlessUser>() {
#Override
public void handleResponse(BackendlessUser response) {
Toast.makeText(getApplicationContext(),"Sikeres bejelentlezés",Toast.LENGTH_SHORT).show();
Intent loginIntent = new Intent(LoginActivity.this, CategoryActivity.class);
LoginActivity.this.startActivity(loginIntent);
}
#Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(getApplicationContext(),"Sikertelen bejelentlezés",Toast.LENGTH_SHORT).show();
}
});
}
And the User activity.... This part, where is a logout button:
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Backendless.UserService.logout(new AsyncCallback<Void>() {
#Override
public void handleResponse(Void response) {
finish();
Intent logoutIntent = new Intent(UserAreaActivity.this, LoginActivity.class);
UserAreaActivity.this.startActivity(logoutIntent);
}
#Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(getApplicationContext(),"Nem sikerült kijelentkezni!",Toast.LENGTH_SHORT).show();
}
});
}
});
You can do it by shared preferences.. if user logged in just store the value in the sharedpreference let say
Sp.putString("userinfo","loggedin");
Sp.commit();
and whenever you comeback just check the preference if it has the value loggedin then jus go to your main activity.else show login activity
String data =SpEditor.getString("userinfo", null);
If(data!= null){
goto main}
Else goto login
Hopeit helps!!
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);
I'm trying to make a signUp activity with a profile picture, but i get an error stating: Unable to encode an unsaved parse file. I have the same code in another Class and it doesn't have any problems.
I think that the problem could be using ParseUser instead of ParseObject. Please help me, here's my code.
public class SignUpActivityStep3 extends ActionBarActivity {
public static final String YOUR_APPLICATION_ID = "kuN8ihs88AYhRR1jIWT9psCGUXxSOveJPqVVsBnq";
public static final String YOUR_CLIENT_KEY = "vC4eA9CqulpgkxJ7sTPtoPSANkMxFeiFlYXwODYK";
byte[] Image;
ParseFile photo = null;
String User, Pass, Email, Description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signupstep3);
Parse.initialize(this, YOUR_APPLICATION_ID, YOUR_CLIENT_KEY);
EditText Desc = (EditText) findViewById(R.id.txtDesc);
Button Finish = (Button) findViewById(R.id.btnFinish);
Intent intent = getIntent();
User = intent.getStringExtra("User");
Pass = intent.getStringExtra("Pass");
Email = intent.getStringExtra("Email");
Image = intent.getByteArrayExtra("Image");
photo = new ParseFile("userpicture.png", Image);
photo.saveInBackground();
savetoParse();
}
private void savetoParse() {
ParseUser user = new ParseUser();
user.setUsername(User.toString());
user.setPassword(Pass.toString());
user.put("Profile", photo);
user.setEmail(Email.toString());
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
Toast.makeText(getApplicationContext(),
"Saving user failed." + e.getMessage(), Toast.LENGTH_SHORT).show();
if (e.getCode() == 202) {
Toast.makeText(
getApplicationContext(),
"Username already taken. \n Please choose another username.",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "User Saved",
Toast.LENGTH_SHORT).show();
/*Do some things here if you want to.*/
}
}
});
}
}
You need to wait for the Parse file to finish saving before attempting to sign up the user. You need to do something like this:
photo = new ParseFile("userpicture.png", Image);
file.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
// If successful add file to user and signUpInBackground
if(null == e)
savetoParse();
}
});
I was having this same issue but then I figured that for the image to be saved we need to login first, so either login with a user and password using ParseUser.LogInBackGround method or use Parse.enableLocalDatastore(this); to enable automatic user creation and logging in.