how to login and registration using volley and sessionManager also view data
Step 2: Create a LoginActivity and a RegisterActivity Create two activities: LoginActivity
and RegisterActivity
. In these activities, you will create a UI to allow users to log in and register.
Step 3: Implement login and registration in the activities In the LoginActivity
, you can create a loginUser
function that will be called when the user clicks the "login" button. In this function, you will use Volley to make a POST request to your server to authenticate the user's credentials. If the request is successful, you can save the user's session data in the SessionManager and start the MainActivity
.
Here's an example code for LoginActivity
:
public class LoginActivity extends AppCompatActivity {
private EditText emailEditText, passwordEditText;
private Button loginButton;
private SessionManager sessionManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
emailEditText = findViewById(R.id.emailEditText);
passwordEditText = findViewById(R.id.passwordEditText);
loginButton = findViewById(R.id.loginButton);
sessionManager = new SessionManager(getApplicationContext());
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = emailEditText.getText().toString().trim();
String password = passwordEditText.getText().toString().trim();
loginUser(email, password);
}
});
}
private void loginUser(String email, String password) {
String url = "https://your-server-url.com/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if (success) {
// User authenticated successfully
JSONObject userObject = jsonObject.getJSONObject("user");
String name = userObject.getString("name");
String email = userObject.getString("email");
String token = jsonObject.getString("token");
sessionManager.createSession(name, email, token);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
} else {
// Authentication failed
Toast.makeText(LoginActivity.this, "Authentication failed", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
}
In the RegisterActivity
, you can create a registerUser
function that will be called when the user clicks the "register" button. In this function, you will use Volley to make a POST request to your server to create a new user account
Create SessionManager Class
import android.content.Context;
import android.content.SharedPreferences;
import java.util.HashMap;
public class SessionManager {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private Context context;
private static final String PREFERENCE_NAME = "Session";
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String KEY_TOKEN = "token";
public SessionManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void createSession(String name, String email, String token) {
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
editor.putString(KEY_TOKEN, token);
editor.apply();
}
public boolean isLoggedIn() {
return sharedPreferences.getBoolean(IS_LOGIN, false);
}
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<>();
user.put(KEY_NAME, sharedPreferences.getString(KEY_NAME, ""));
user.put(KEY_EMAIL, sharedPreferences.getString(KEY_EMAIL, ""));
user.put(KEY_TOKEN, sharedPreferences.getString(KEY_TOKEN, ""));
return user;
}
public void logoutUser() {
editor.clear();
editor.apply();
}
}
Here's a brief explanation of the SessionManager class:
SharedPreferences sharedPreferences
: A reference to the shared preferences file that will be used to store session data.SharedPreferences.Editor editor
: An editor object that will be used to modify the shared preferences file.Context context
: The context of the application.PREFERENCE_NAME
: The name of the shared preferences file.IS_LOGIN
: A key to store the login status of the user.KEY_NAME
,KEY_EMAIL
,KEY_TOKEN
: Keys to store the user's name, email, and authentication token, respectively.createSession
: Method to create a new session. It takes the user's name, email, and authentication token as parameters and stores them in the shared preferences file.isLoggedIn
: Method to check if the user is currently logged in. It returnstrue
if the user is logged in,false
otherwise.getUserDetails
: Method to get the user's details from the shared preferences file. It returns a HashMap containing the user's name, email, and authentication token.logoutUser
: Method to log the user out. It clears the shared preferences file.
Show Data from SessionManager Class
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private SessionManager sessionManager;
private TextView nameTextView, emailTextView, tokenTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTextView = findViewById(R.id.name_text_view);
emailTextView = findViewById(R.id.email_text_view);
tokenTextView = findViewById(R.id.token_text_view);
sessionManager = new SessionManager(this);
if (sessionManager.isLoggedIn()) {
HashMap<String, String> user = sessionManager.getUserDetails();
String name = user.get(SessionManager.KEY_NAME);
String email = user.get(SessionManager.KEY_EMAIL);
String token = user.get(SessionManager.KEY_TOKEN);
nameTextView.setText(name);
emailTextView.setText(email);
tokenTextView.setText(token);
}
}
}