How to login volley also remember checkbox using SharedPreferences android studio
When building an Android application that requires user authentication, it's important to provide a "Remember Me" feature so that users don't have to enter their credentials every time they use the app. One way to implement this feature is by using SharedPreferences and Volley, a popular networking library for Android.
To implement the "Remember Me" feature, you first need to create a checkbox in the login screen UI. Then, you need to retrieve the saved credentials and "Remember Me" state from SharedPreferences and pre-populate the login fields and checkbox accordingly. Whenever the user toggles the checkbox, you need to save or remove the credentials and "Remember Me" state in SharedPreferences.
When the user clicks the login button, you need to make the login request using Volley. If the login is successful, you can start the home activity and pass the "Remember Me" state as an extra in the intent. In the home activity, you can use the "Remember Me" state to determine whether to pre-populate the login fields and checkbox or not.
Overall, implementing the "Remember Me" feature using SharedPreferences and Volley is a simple and effective way to enhance the user experience and improve the security of your Android application.
Here's an example of how you can modify the login code to implement the "Remember Me" feature using SharedPreferences and Volley
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private EditText usernameEditText;
private EditText passwordEditText;
private CheckBox rememberMeCheckbox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameEditText = findViewById(R.id.username_edit_text);
passwordEditText = findViewById(R.id.password_edit_text);
rememberMeCheckbox = findViewById(R.id.remember_me_checkbox);
// Retrieve the saved credentials and "Remember Me" state
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
String savedUsername = sharedPreferences.getString("username", "");
String savedPassword = sharedPreferences.getString("password", "");
boolean rememberMe = sharedPreferences.getBoolean("rememberMe", false);
// Pre-populate the login fields and "Remember Me" checkbox
usernameEditText.setText(savedUsername);
passwordEditText.setText(savedPassword);
rememberMeCheckbox.setChecked(rememberMe);
rememberMeCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (isChecked) {
editor.putString("username", usernameEditText.getText().toString());
editor.putString("password", passwordEditText.getText().toString());
editor.putBoolean("rememberMe", true);
} else {
editor.remove("username");
editor.remove("password");
editor.putBoolean("rememberMe", false);
}
editor.apply();
}
});
Button loginButton = findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
boolean rememberMe = rememberMeCheckbox.isChecked();
// Make the login request using Volley
login(username, password, rememberMe);
}
});
}
private void login(String username, String password, boolean rememberMe) {
String url = "https://example.com/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Handle the login response
if (response.equals("success")) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
intent.putExtra("rememberMe", rememberMe);
startActivity(intent);
finish();
} else {
Toast.makeText(MainActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".Login_Reg.Login"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:orientation="vertical">
<soup.neumorphism.NeumorphCardView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15sp"
android:text="আপনার এ্যাকাউন্টটি ওপেন করতে মোবাইল নম্বর ও পাসওয়ার্ডটি প্রবেশ করুন।"
android:fontFamily="@font/solaimanlipi"
android:textStyle="bold"
android:textAlignment="center"
android:textColor="#870581"
android:textSize="20dp"
android:visibility="gone"/>
</soup.neumorphism.NeumorphCardView>
<soup.neumorphism.NeumorphCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:neumorph_backgroundColor="#279EFA">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:weightSum="2">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5sp"
android:text="LOG IN"
android:textAlignment="center"
android:fontFamily="@font/solaimanlipi"
android:textStyle="bold"
android:textColor="@color/white"
android:textSize="30dp" />
</LinearLayout>
</soup.neumorphism.NeumorphCardView>
<soup.neumorphism.NeumorphCardView
style="@style/Widget.Neumorph.CardView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/userPhoneNoLog"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableRight="@drawable/ic_baseline_call_24"
android:fontFamily="@font/solaimanlipi"
android:inputType="number"
android:gravity="left"
android:hint="Enter Your Phone Number"
android:maxLength="11"
android:padding="14dp"
android:paddingEnd="10dp"
android:textColor="@color/black"
android:textColorHint="@color/black" />
</soup.neumorphism.NeumorphCardView>
<soup.neumorphism.NeumorphCardView
style="@style/Widget.Neumorph.CardView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/userPassLog"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableRight="@drawable/ic_password"
android:fontFamily="@font/solaimanlipi"
android:gravity="left"
android:hint="Enter Your Phone Password"
android:padding="14dp"
android:paddingEnd="10dp"
android:inputType="textPassword"
android:textColor="@color/black"
android:textColorHint="@color/black" />
</soup.neumorphism.NeumorphCardView>
<soup.neumorphism.NeumorphCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp">
<CheckBox
android:id="@+id/rememberMe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5sp"
android:fontFamily="@font/solaimanlipi"
android:padding="10sp"
android:text="Remember"
android:textColor="@color/black" />
</soup.neumorphism.NeumorphCardView>
<soup.neumorphism.NeumorphButton
android:id="@+id/btnSignInLog"
style="@style/Widget.Neumorph.Button"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:fontFamily="@font/solaimanlipi"
android:text="Log In"
android:textColor="@color/white"
app:neumorph_backgroundColor="#279EFA"
android:textSize="16dp"
android:layout_marginBottom="25sp">
</soup.neumorphism.NeumorphButton>
</LinearLayout>
</ScrollView>
</LinearLayout>
php code:
<?php
$conn = mysqli_connect("localhost","quaintfa_dbManager","M*-R0ETqAx1W","quaintfa_dbManager");
$conn->set_charset("utf8");
mysqli_query('SET CHARACTER SET utf8');
mysqli_query("SET SESSION collation_connection ='utf8_unicode_ci'");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$PhoneNo= $_POST["PhoneNo"];
$Password = $_POST["Password"];
// $hash_password = password_hash($Password, PASSWORD_DEFAULT);
$list="";
$query="select * from tbl_jregistration where PhoneNo='".$PhoneNo."' AND Password='$Password'";
$result=mysqli_query($conn,$query);
if(mysqli_num_rows($result)>0)
{
while($row=mysqli_fetch_array($result))
{
if($list=="")
{
$JRegID=$row['JRegID'];
$UserName=$row['UserName'];
$UserNameFull=$row['UserNameFull'];
$email=$row['email'];
$PhoneNo=$row['PhoneNo'];
$UserImage=$row['UserImage'];
$UserAddress=$row['UserAddress'];
$UserActive=$row['UserActive'];
$imageUp=$row['imageUp'];
$UserType=$row['UserType'];
}
}
}
if(mysqli_num_rows($result)==0)
{
$response["success"] = "0";
$response["message"]="user is not Registered, Please Register";
echo json_encode($response);
mysqli_close($conn);
}
else
{
//response to android app
$response["success"]="1";
$response["message"]="Logged in successful";
$response["JRegID"]=$JRegID;
$response["UserName"]=$UserName;
$response["UserNameFull"]=$UserNameFull;
$response["email"]=$email;
$response["PhoneNo"]=$PhoneNo;
$response["UserAddress"]=$UserAddress;
$response["UserImage"]=$UserImage;
$response["UserActive"]=$UserActive;
$response["imageUp"]=$imageUp;
$response["UserType"]=$UserType;
//converting response data into json format
echo json_encode($response);
mysqli_close($conn);
}
?>