I have 2 questions want to ask about android studio and sqlite.
1) I am trying to run my project in emulator or phone. When I want to return to previous activity by pressing the return button(return function for phone) but it close all my project.But I saw my friend's can return to previous activity by pressing the return button.May I know how and why??
2) I had done update function for my project.The situation is when userA go to "view profile" activity and click edit info, another activity that call "updateinfo" will come out.Then after userA update his information by clicking update button.It's successful update and go back to "view profile" activity to see his updated profile.
But the problem I faced is it does not show out the updated information.It just show a blank "view profile" activity without any information that updated or haven updated.
What should I do?
here my database update function
public boolean updateProfile(String username, String password, String email, String phone)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put (COL_2,username);
values.put(COL_3,password);
values.put(COL_4,email);
values.put(COL_5,phone);
db.update(Table_NAME,values,COL_2 + "=?",new String[]{username});
db.close();
return true;
}
here is my updateinfo activity function
public class EditProfile extends AppCompatActivity {
EditText etEmail,etPhone,etPassword,etConPassword,etUsername;
String password,conpassword,Email,Phone;
Button bUpdate;
DatabaseOperations DB = new DatabaseOperations(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
etEmail = (EditText) findViewById(R.id.etEmail);
etPhone = (EditText) findViewById(R.id.etPhone);
etPassword = (EditText) findViewById(R.id.etPassword);
etConPassword = (EditText) findViewById(R.id.etConPassword);
etUsername = (EditText) findViewById(R.id.etUsername);
bUpdate = (Button) findViewById(R.id.bUpdate);
Intent i = getIntent();
String email = i.getStringExtra("email");
etEmail.setText(email);
String phone = i.getStringExtra("phone");
etPhone.setText(phone);
String username = i.getStringExtra("username");
etUsername.setText(username);
bUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
password = etPassword.getText().toString();
conpassword = etConPassword.getText().toString();
Email = etEmail.getText().toString();
Phone = etPhone.getText().toString();
if (!(password.equals(conpassword))) {
Toast.makeText(getBaseContext(), "Passwords are not matching", Toast.LENGTH_LONG).show();
etPassword.setText("");
etConPassword.setText("");
etEmail.setText("");
etPhone.setText("");
} else if (etPassword.length() == 0 || etConPassword.length() == 0 || etEmail.length() == 0 || etPhone.length() == 0) {
etPassword.setError("Please complete all information");
etConPassword.setError("Please complete all information");
etEmail.setError("Please complete all information");
etPhone.setError("Please complete all information");
} else if (etPassword.length() < 6) {
etPassword.requestFocus();
etPassword.setError("Password at least 6 characters");
etPassword.setText("");
etConPassword.setText("");
etEmail.setText("");
etPhone.setText("");
} else {
boolean isUpdate = DB.updateProfile(etUsername.getText().toString(),etPassword.getText().toString(),etEmail.getText().toString(),etPhone.getText().toString());
if(isUpdate == true) {
Toast.makeText(getBaseContext(), "Update Success", Toast.LENGTH_LONG).show();
Intent i = new Intent(EditProfile.this, MyProfile.class);
startActivity(i);
finish();
}
else
{
Toast.makeText(getBaseContext(), "Data Not Updated", Toast.LENGTH_LONG).show();
}
}
}
});
}
and here is my viewprofile activity function
public class MyProfile extends AppCompatActivity {
EditText etName,etEmail,etPhone,etShow;
Button bEdit;
String fullname,email,phone;
DatabaseOperations db = new DatabaseOperations(this);
PersonalData profileInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etPhone = (EditText) findViewById(R.id.etPhone);
bEdit = (Button) findViewById(R.id.bEdit);
etShow = (EditText) findViewById(R.id.etShow);
fullname = etName.getText().toString();
email = etEmail.getText().toString();
phone = etPhone.getText().toString();
Intent i = getIntent();
String username = i.getStringExtra("username");
etShow.setText(username);
profileInfo = db.getAllinfo(username);
etName.setText(profileInfo.get_name());
etEmail.setText(profileInfo.get_email());
etPhone.setText(profileInfo.get_phone());
bEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyProfile.this,EditProfile.class);
i.putExtra("email", etEmail.getText().toString());;
i.putExtra("phone", etPhone.getText().toString());;
i.putExtra("username", etShow.getText().toString());
startActivity(i);
finish();
}
});
}
you always start new activity and finish the last activity
startActivity(i);
finish();
dont finish it if you want to go back later, you can go back to last activity with finish(); or pressing back in phone
you just need to call finish() when update success (you need to implement answer number 1 first)
Toast.makeText(getBaseContext(), "Update Success", Toast.LENGTH_LONG).show();
Intent i = new Intent(EditProfile.this, MyProfile.class);
startActivity(i);
finish();
in MyProfile make the username variable global
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
....
username = i.getStringExtra("username");
....
}
last,this code need to be inside onResume()
etShow.setText(username);
profileInfo = db.getAllinfo(username);
etName.setText(profileInfo.get_name());
etEmail.setText(profileInfo.get_email());
etPhone.setText(profileInfo.get_phone());
public boolean update(editProfile.EUsers eusers){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalues = new ContentValues();
String username = eusers.getUsername();
String password = eusers.getPassword();
int id = eusers.getId();
contentvalues.put(editProfile.EUsers.COL3_PASSWORD,password);
contentvalues.put(editProfile.EUsers.COL2_USERNAME,username);
int res =db.update(editProfile.EUsers.TABLE_NAME,values,editProfile.EUsers.COL1_ID+" = ?",new String[]{String.valueOf(id)});
if(res >0)
return true;
return false;
}
Related
i programmed my register activity to get my user details and store it with SharePreferences
Now , im trying to get those values stored in the data to log in in my app but it seems im missing something, when i put anything in my edittexts in my login layout it logs in without checking the user
RegisterActivity.class
public class RegistrarUsuario extends AppCompatActivity {
private Button mBtnRegistrarUsuario;
private TextView mRegistrarTxt;
private EditText mUsername,mPassword,mSecondPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrar_usuario);
mRegistrarTxt = (TextView) findViewById(R.id.titulo2);
mUsername = (EditText) findViewById(R.id.nombreUsuario);
mPassword = (EditText) findViewById(R.id.primeraContraseña);
mSecondPassword = (EditText) findViewById(R.id.segundaContraseña);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mRegistrarTxt.setTypeface(fuente);
mBtnRegistrarUsuario = (Button) findViewById(R.id.btnRegistrarUsuario);
mBtnRegistrarUsuario.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String secondpassword = mSecondPassword.getText().toString().trim();
if(username.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese un usuario.", Toast.LENGTH_SHORT).show();
}
else if(password.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese contraseña.", Toast.LENGTH_SHORT).show();
}
else if(secondpassword.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Confirme su contraseña.", Toast.LENGTH_SHORT).show();
}
else if(password.equals(secondpassword)){
SharedPreferences.Editor editor = preference.edit();
editor.putString("Username",username);
editor.putString("Password",password);
editor.putString("SecondPassword",secondpassword);
editor.commit();
finish();
Toast.makeText(RegistrarUsuario.this, "Usuario creado con exito!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegistrarUsuario.this,PantallaPrincipal.class);
startActivity(intent);
}
else{
Toast.makeText(RegistrarUsuario.this, "No coinciden las contraseñas.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
** LoginActivity.class**
public class MainActivity extends AppCompatActivity {
private EditText mUsername,mPassword;
private Button mLoginBtn,mBtnRecuperar,mBtnRegistrar;
private TextView mTextView;
private static String usuario ="admin";
private static String contraseña="123";
private final String KEY_USERNAME = "username";
private final String KEY_PASSWORD = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = (EditText) findViewById(R.id.usuario);
mPassword = (EditText) findViewById(R.id.contraseña);
mLoginBtn = (Button) findViewById(R.id.btnIngresar);
mTextView = (TextView) findViewById(R.id.titulo);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mTextView.setTypeface(fuente);
mBtnRecuperar = (Button) findViewById(R.id.btnRecuperar);
mBtnRecuperar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RecuperarContrasenia.class);
startActivity(intent);
}
});
mBtnRegistrar = (Button) findViewById(R.id.btnRegistrar);
mBtnRegistrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RegistrarUsuario.class);
startActivity(intent);
}
});
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
String userDetails = preference.getString(username + password + "data","No information on that user.");
SharedPreferences.Editor editor = preference.edit();
editor.putString("display",userDetails);
editor.commit();
if(mUsername.getText().toString().trim().length() == 0 && mPassword.getText().toString().trim().length() == 0 ){
Toast.makeText(MainActivity.this, "Los campos estan vacios", Toast.LENGTH_SHORT).show();
}else
{
if(mUsername.getText().toString().trim().equals(username) && mPassword.getText().toString().trim().equals(password)){
Toast.makeText(MainActivity.this, "Bienvenido", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this,PantallaPrincipal.class);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Los campos son incorrectos", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
i dont know what im missing that it dont verify the user if exists or login with the credentials i make in RegisterActivity.class
thanks
You are never retrieving the username and password from SharedPreferences. And at the end you are checking the information the user puts in the TextEdits against itself so the validation always returns true to any non empty value.
Change this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
To this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = preference.getString("Username", "");
String password = preference.getString("Password", "");
I have a login and reset password activity. When I enter the new updated password and try to login again, I cannot do so with the new password. Logging in with the old password works fine. Basically, the password field is not getting updated/overwritten.
There is no error in the logcat. Just that the password is not updated.
Please help as I am new to android development.
Code for update( DataRegister is the class with GET AND SET functions):
public int updatePassword(DataRegister dataregister) {
db = dbHelper.getWritableDatabase();
ContentValues updated = new ContentValues();
updated.put("PASSWORD", dataregister.getPASSWORD());
return db.update(DataRegister.TABLE, updated, "EMAIL=?" , new String[]{email});
}
Code for retrieval:
public String getPass(DataRegister dataRegister) {
db = dbHelper.getWritableDatabase();
Cursor cursor = db.query(DataRegister.TABLE, null, "EMAIL=?",
new String[]{dataRegister.getEMAIL()}, null, null, null, null);
if (cursor != null && cursor.moveToFirst())
{
pass = cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
}
return pass;
// return contact
}
Code for Login:
String email = editTextUserName.getText().toString();
dataRegister.setEMAIL(email);
String password = editTextPassword.getText().toString();
dataRegister.setPASSWORD(password);
String storedPassword = loginDataBaseAdapter.getSinlgeEntry(dataRegister);
Toast.makeText(Login.this, storedPassword,Toast.LENGTH_LONG).show();
Boolean a=loginDataBaseAdapter.isExist(dataRegister.getEMAIL());
validation = getSharedPreferences("myShaPreferences", Context.MODE_PRIVATE);
if (password.equals(storedPassword)) {
Toast.makeText(Login.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
}
else {
Toast.makeText(Login.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
}
}
});
Code for reset password:
public class ResetPassword extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset_password);
email = (EditText) findViewById(R.id.em2);
dataRegister=new DataRegister();
loginDataBaseAdapter = new DatabaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
pass = (EditText) findViewById(R.id.text12);
conpass = (EditText) findViewById(R.id.text13);
email1 = email.getText().toString();
dataRegister.setEMAIL(email1);
pass1 = pass.getText().toString();
conpass1 = conpass.getText().toString();
dataRegister.setPASSWORD(conpass1);
Button btnReset = (Button) findViewById(R.id.btnReset);
btnReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (pass1.equals(conpass1)) {
loginDataBaseAdapter.updatePassword(email1,pass1);
String newpass = loginDataBaseAdapter.getPass(dataRegister);
Toast.makeText(ResetPassword.this, newpass, Toast.LENGTH_LONG).show();
Intent intent = new Intent(ResetPassword.this, Login.class);
startActivity(intent);
finish();
}
else {
Toast.makeText(ResetPassword.this,
"Password does not match",
Toast.LENGTH_LONG).show();
}
}
});
Maybe this can help you for updating data :
public void updating( Password password) {
ContentValues value = new ContentValues();
value.put( PasswordDAO.LOGIN, password.getlogin() );
value.put( PasswordDAO.PASSWORD, password.getPassword());
this.mDb.update( PasswordDAO.NAME_TABLE, value, PasswordDAO.ID + " = ?", new String[]{String.valueOf(password.getId())} );
}
PasswordDao is the name of the class who extends the DAOBase, NAME_TABLE is "Password", and you need to create a class password with id login and password.
hope this can help you
Below is my login activity.
It has a simple layout,where user enters his username and password and click login button.
A list of username and passwords is being stored in ms sql server.
And connection is also being established.
But the problem is on different combinations of usernames and passwords i want to open different activities.
How can i do it?
Lets say I have two combinations of username and password in my database-1.username1 , password1 (should open activity 1 on login button click)
2.username2, password2 (shoud open activity 2 on login button click)
Here is the code-----
public class Login extends Activity
{
private static final String DUMMY_CREDENTIALS = "user#test.com:hello";
// private UserLoginTask userLoginTask = null;
private View loginFormView;
private View progressView;
ConnectionClass connectionClass;
private AutoCompleteTextView emailTextView;
private EditText passwordTextView;
private Button btnlogin;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
connectionClass = new ConnectionClass();
emailTextView = (AutoCompleteTextView) findViewById(R.id.email);
//loadAutoComplete();
passwordTextView = (EditText) findViewById(R.id.password);
btnlogin=(Button) findViewById(R.id.email_sign_in_button);
class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
String userid = emailTextView.getText().toString();
String password = passwordTextView.getText().toString();
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(Login.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess) {
Intent i = new Intent(Login.this, Activity1.class);//For any combination ,it will open activity1 now.
startActivity(i);
finish();
}
}
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select EmailID,Password from Login_DB where EmailID='" + userid + "' and Password='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successfull";
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions";
}
}
return z;
}
}
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();// this is the Asynctask
doLogin.execute("");
}
});
}
}
Create a table in your database that links usernames to activities, and then query it after authenticating the user.
public class Loginscreen extends Activity {
private EditText phonenumber,password;
private Button signin,joinus,supportus;
private TextView forgot_password;
String mobilenumber;
String passwordtxt;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
phonenumber = (EditText) findViewById(R.id.edt_username);
password = (EditText) findViewById(R.id.edt_password);
signin = (Button) findViewById(R.id.bt_signin);
joinus = (Button) findViewById(R.id.bt_joinus);
supportus = (Button) findViewById(R.id.bt_supportus);
forgot_password = (TextView) findViewById(R.id.txt_remember_pawd);
final String user = phonenumber.getText().toString();
final String pass = password.getText().toString();
signin.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//final Intent intent;
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
final String pasword = pref.getString("pwd", null);
final String phnenumber = pref.getString("mobilenumber", null);
if ( pass == pasword && user == phnenumber && !pass.isEmpty()){
Toast.makeText(Loginscreen.this, "correct ", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(Loginscreen.this, "Incorrect Mobile number or password", Toast.LENGTH_SHORT).show();
}
}
});
in above code how can i compare the shared preference value with current edit text value....i used shared preference in another page..
#Override
public void onPostExecute(String result) {
JSONObject jsonobject = null;
try {
jsonobject = new JSONObject(result);
JSONObject object = jsonobject.getJSONObject("data");
String id = object.getString("_id");
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
pref.getString("key_name1",null);
//final String encoded = pref.getString("key_name1",null);
String password = getIntent().getStringExtra("_password");
String mobilen = getIntent().getStringExtra("mobile");
SharedPreferences.Editor editor = pref.edit();
editor.putString("pwd",password);
editor.putString("mobilenumber",mobilen);
editor.putString("user_id",id);
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
the above code is present in another activity..how can i use that shared preference value in LoginScreen to compare both the values are equal are not
You should use equals() instead of ==.
Change this part of the code:
if ( pass == pasword && user == phnenumber && !pass.isEmpty()){
Toast.makeText(Loginscreen.this, "correct ", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(Loginscreen.this, "Incorrect Mobile number or password", Toast.LENGTH_SHORT).show();
}
to:
if ( password.getText().toString().equals(password) && phonenumber.getText().toString().equals(phnenumber) && !pass.isEmpty()){
Toast.makeText(Loginscreen.this, "correct ", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(Loginscreen.this, "Incorrect Mobile number or password", Toast.LENGTH_SHORT).show();
}
You can do this with intent.
in your first screen write below code on some button click.
Intent i=new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("editTextvalue",editText.getText().toString());
startActivity(i);
in your second screen write below code in onCreate()
String value=getIntent().getStringExtra("editTextvalue");
campare this value with your sharedPreferences value.
I have mentioned my complete code for the login and logout process to my application. Sometimes this code works but sometimes it just allows me to go to menu activity even without login. FYI: this code really worked earlier once i wanted to implement the remember me option, then only all these issues came up. can anyone check this and find me my issue or suggest me if u got any proper code for this process. when i logout and and open the application sometimes i can see the menu.
I have used shared preference and not using sessions for login and logout. is it correct. Im bit confused i would really appreciate any help. thanx in advance.
login code
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
EditText emailET;
EditText pwdET;
String email;
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String email = emailET.getText().toString();
String password = pwdET.getText().toString();
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
if (Utility.validate(email)) {
if (emailET.getText().toString().equals(email)
&& pwdET.getText().toString()
.equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password);
}
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Login process started...",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),
"Login error, invalid email",
Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(
getApplicationContext(),
"Login error, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
final TextView textView = (TextView) findViewById(R.id.link_to_landing);
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
LandingActivity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(getApplicationContext(),
LandingActivity.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
finish();
return false;
}
return super.onKeyDown(keyCode, event);
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
}
}
logout code
final RelativeLayout relativeLayout3 = (RelativeLayout) rootView
.findViewById(R.id.logoutlistview);
relativeLayout3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences pref = getActivity().getSharedPreferences(
PREFS_NAME, Context.MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null ) {
Editor editor = pref.edit();
editor.clear();
editor.commit();
email = "";
password = "";
firstname = "";
lastname = "";
// show login form
Intent intent = new Intent(getActivity(),
LActivity.class);
startActivity(intent);
intent.addFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else {
}
}
});
use this method to create a sharedPreference and then access it with this same name from any where in any activity within the same app
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
Editor e = sp.edit();
e.put(key,value);
e.commit();
and when getting the same sharedPreference in another activity use this method
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
sp.get(key,value);
Please check the below link which might help you.
http://androidapplicationdeveloper.weebly.com/login-and-logout-useing-sharedprefrences.html
In your code you have didn't set values of sharedpreference to blank while logout.
Hope it will help you.