일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
- Rxjava Observable
- rxjava cold observable
- android retrofit login
- 안드로이드 라이선스
- ar vr 차이
- 객체
- 서비스 쓰레드 차이
- android ar 개발
- 안드로이드 os 구조
- 스택 큐 차이
- rxjava hot observable
- 안드로이드 유닛 테스트 예시
- jvm이란
- 안드로이드 라이선스 종류
- 안드로이드 레트로핏 사용법
- 안드로이드 유닛테스트란
- 2022 플러터 안드로이드 스튜디오
- 스택 자바 코드
- 안드로이드 유닛 테스트
- ANR이란
- 큐 자바 코드
- 안드로이드 레트로핏 crud
- 클래스
- rxjava disposable
- jvm 작동 원리
- 자바 다형성
- 서비스 vs 쓰레드
- 2022 플러터 설치
- 플러터 설치 2022
- 멤버변수
- Today
- Total
나만을 위한 블로그
[Android] Volley를 이용한 회원가입, 로그인 기능 구현 2편(with MySQL, PHP) 본문
참고한 사이트 : https://www.simplifiedcoding.net/android-volley-tutorial/
이전 게시글 : https://onlyfor-me-blog.tistory.com/119
예전에 올렸던 Volley를 사용한 회원가입, 로그인은 기능은 작동하지만 내가 어떤 아이디로 로그인했는지 알 수 있는 방법이 없었다.
이 예제는 그 단점이 없는 예제로, 회원가입 후 로그인하면 테이블의 id값, 이름, 아이디, 비밀번호, 성별 값들을 가져와 텍스트뷰에 set한다. 비밀번호는 php의 md5()를 써서 비밀번호를 이상한 글자들로 바꾼다.
먼저 테이블 설정이다. DB 이름은 android다.
phpmyadmin을 쓴다면 DB명을 android로 하고 아래 SQL문을 붙여넣으면 만들어진다.
CREATE TABLE `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(200) NOT NULL,
`email` VARCHAR(200) NOT NULL,
`password` TEXT NOT NULL,
`gender` VARCHAR(6) NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
다음은 php 코드들이다.
// DbConnect.php
<?php
$servername = "IP주소";
$username = "root";
$password = "";
$database = "android";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error)
{
die("Connection Failed : " .$conn->connect_error);
}
?>
// Api.php
<?php
require_once 'DbConnect.php';
$response = array();
if (isset($_GET['apicall']))
{
switch($_GET['apicall'])
{
case 'signup' :
if (isTheseParametersAvailable(array('username', 'email', 'password', 'gender')))
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = md5($_POST['password']);
$gender = $_POST['gender'];
$stmt = $conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
$stmt->bind_param("ss", $username, $email);
$stmt->execute();
$stmt->store_result();
//if the user already exist in the database
if ($stmt->num_rows > 0)
{
$response['error'] = true;
$response['message'] = 'User Already Registered';
$stmt->close();
}
else
{
$stmt = $conn->prepare("INSERT INTO users(username, email, password, gender)
VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $username, $email, $password, $gender);
if ($stmt->execute())
{
$stmt = $conn->prepare("SELECT id, username, email, gender FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($userid, $id, $username, $email, $gender);
$stmt->fetch();
$user = array(
'id'=>$id,
'username'=>$username,
'email'=>$email,
'gender'=>$gender
);
$stmt->close();
$response['error'] = false;
$response['message'] = 'User Registered Successfully';
$response['user'] = $user;
}
}
}
else
{
$response['error'] = true;
$response['message'] = 'Required Parameters are not available';
}
break;
case 'login' :
if (isTheseParametersAvailable(array('username', 'password')))
{
$username = $_POST['username'];
$password = md5($_POST['password']);
$stmt = $conn->prepare("SELECT id, username, email, gender FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss",$username, $password);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0)
{
$stmt->bind_result($id, $username, $email, $gender);
$stmt->fetch();
$user = array(
'id'=>$id,
'username'=>$username,
'email'=>$email,
'gender'=>$gender
);
$response['error'] = false;
$response['message'] = 'Login successful';
$response['user'] = $user;
}
else
{
$response['error'] = false;
$response['message'] = 'Invalid username or password';
}
}
break;
default :
$response['error'] = true;
$response['message'] = 'Invalid Operation Called';
}
}
else
{
$response['error'] = true;
$response['message'] = 'Invalid Api Call';
}
echo json_encode($response);
function isTheseParametersAvailable($params)
{
foreach ($params as $param)
{
if (!isset($_POST[$param]))
{
return false;
}
}
return true;
}
?>
다음은 안드로이드 코드들이다. 액티비티는 MainActivity, LoginActivity, ProfileScreenActivity 3개고 나머지는 자바 클래스들이다.
// activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
android:padding="10dp">
<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:hint="Username"
android:inputType="text" />
<EditText
android:id="@+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:hint="Email"
android:inputType="textEmailAddress" />
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:fontFamily="sans-serif"
android:hint="Password"
android:inputType="textPassword" />
<RadioGroup
android:id="@+id/radioGender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radioButtonMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Male" />
<RadioButton
android:id="@+id/radioButtonFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
<Button
android:id="@+id/buttonRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Register" />
<TextView
android:id="@+id/textViewLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Already Registered?\nLogin Here"
android:textAlignment="center"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
</LinearLayout>
<ProgressBar
android:visibility="gone"
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
// activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
android:padding="10dp">
<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:hint="Username"
android:inputType="text" />
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:fontFamily="sans-serif"
android:hint="Password"
android:inputType="textPassword" />
<Button
android:id="@+id/buttonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Login" />
<TextView
android:id="@+id/textViewRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Dont' have an account?\nRegister Here"
android:textAlignment="center"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
</LinearLayout>
<ProgressBar
android:visibility="gone"
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
// activity_profile_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ProfileScreenActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Id"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
<TextView
android:id="@+id/textViewId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="1"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Username"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
<TextView
android:id="@+id/textViewUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="probelalkhan"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Email"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
<TextView
android:id="@+id/textViewEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="probelalkhan@gmail.com"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Gender"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
<TextView
android:id="@+id/textViewGender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Male"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</TableRow>
</TableLayout>
<Button
android:id="@+id/buttonLogout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout" />
</LinearLayout>
</RelativeLayout>
// MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
EditText editTextUsername, editTextEmail, editTextPassword;
RadioGroup radioGroupGender;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
//if the user is already logged in we will directly start the profile activity
if (SharedPrefManager.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, ProfileScreenActivity.class));
return;
}
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
radioGroupGender = (RadioGroup) findViewById(R.id.radioGender);
findViewById(R.id.buttonRegister).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
//if user pressed on button register
//here we will register the user to server
registerUser();
}
});
findViewById(R.id.textViewLogin).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
//if user pressed on login
//we will open the login screen
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
});
}
private void registerUser()
{
final String username = editTextUsername.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
final String gender = ((RadioButton) findViewById(radioGroupGender.getCheckedRadioButtonId())).getText().toString();
//first we will do the validations
if (TextUtils.isEmpty(username)) {
editTextUsername.setError("Please enter username");
editTextUsername.requestFocus();
return;
}
if (TextUtils.isEmpty(email)) {
editTextEmail.setError("Please enter your email");
editTextEmail.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
editTextEmail.setError("Enter a valid email");
editTextEmail.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
editTextPassword.setError("Enter a password");
editTextPassword.requestFocus();
return;
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_REGISTER,
new Response.Listener<String>() {
@Override
public void onResponse(String response)
{
progressBar.setVisibility(View.GONE);
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getInt("id"),
userJson.getString("username"),
userJson.getString("email"),
userJson.getString("gender")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), ProfileScreenActivity.class));
}
else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
params.put("gender", gender);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
}
// LoginActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {
EditText editTextUsername, editTextPassword;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (SharedPrefManager.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, ProfileScreenActivity.class));
}
progressBar = (ProgressBar) findViewById(R.id.progressBar);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
//if user presses on login
//calling the method login
findViewById(R.id.buttonLogin).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
userLogin();
}
});
//if user presses on not registered
findViewById(R.id.textViewRegister).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//open register screen
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
private void userLogin() {
//first getting the values
final String username = editTextUsername.getText().toString();
final String password = editTextPassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(username)) {
editTextUsername.setError("Please enter your username");
editTextUsername.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
editTextPassword.setError("Please enter your password");
editTextPassword.requestFocus();
return;
}
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getInt("id"),
userJson.getString("username"),
userJson.getString("email"),
userJson.getString("gender")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), ProfileScreenActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
}
// ProfileScreenActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class ProfileScreenActivity extends AppCompatActivity {
TextView textViewId, textViewUsername, textViewEmail, textViewGender;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_screen);
if (!SharedPrefManager.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, LoginActivity.class));
}
textViewId = (TextView) findViewById(R.id.textViewId);
textViewUsername = (TextView) findViewById(R.id.textViewUsername);
textViewEmail = (TextView) findViewById(R.id.textViewEmail);
textViewGender = (TextView) findViewById(R.id.textViewGender);
//getting the current user
User user = SharedPrefManager.getInstance(this).getUser();
//setting the values to the textviews
textViewId.setText(String.valueOf(user.getId()));
textViewUsername.setText(user.getUsername());
textViewEmail.setText(user.getEmail());
textViewGender.setText(user.getGender());
//when the user presses logout button
//calling the logout method
findViewById(R.id.buttonLogout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
SharedPrefManager.getInstance(getApplicationContext()).logout();
}
});
}
}
다음은 일반 자바 클래스 코드들이다.
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}
// User.java
public class User {
private int id;
private String username, email, gender;
public User(int id, String username, String email, String gender) {
this.id = id;
this.username = username;
this.email = email;
this.gender = gender;
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}
public String getGender() {
return gender;
}
}
// SharedPrefManager.java
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class SharedPrefManager {
private static final String SHARED_PREF_NAME = "simplifiedcodingsharedpref";
private static final String KEY_USERNAME = "keyusername";
private static final String KEY_EMAIL = "keyemail";
private static final String KEY_GENDER = "keygender";
private static final String KEY_ID = "keyid";
private static SharedPrefManager mInstance;
private static Context mCtx;
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
//method to let the user login
//this method will store the user data in shared preferences
public void userLogin(User user) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_ID, user.getId());
editor.putString(KEY_USERNAME, user.getUsername());
editor.putString(KEY_EMAIL, user.getEmail());
editor.putString(KEY_GENDER, user.getGender());
editor.apply();
}
//this method will checker whether user is already logged in or not
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USERNAME, null) != null;
}
//this method will give the logged in user
public User getUser() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new User(
sharedPreferences.getInt(KEY_ID, -1),
sharedPreferences.getString(KEY_USERNAME, null),
sharedPreferences.getString(KEY_EMAIL, null),
sharedPreferences.getString(KEY_GENDER, null)
);
}
//this method will logout the user
public void logout() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
mCtx.startActivity(new Intent(mCtx, LoginActivity.class));
}
}
// URLs.java
public class URLs {
private static final String ROOT_URL = "http://IP주소/Api.php?apicall=";
public static final String URL_REGISTER = ROOT_URL + "signup";
public static final String URL_LOGIN= ROOT_URL + "login";
}
맨 마지막 URLs.java 파일의 ROOT_URL 부분의 IP주소는 AWS를 사용중인 경우 퍼블릭 IPv4 주소를 써주면 된다.
php 파일이 다른 폴더 안에 있는 경우 'IP주소/' 다음 공간에 '폴더이름/'을 써주면 된다.
위 코드들을 붙여넣고 앱을 빌드하면 회원가입 성공 시 토스트가 나오고 이 정보로 로그인할 수 있으며, 로그인 성공 시 액티비티가 이동하며 어떤 아이디로 이동했는지 볼 수 있다.
아래는 빌드 후 앱이 작동하는 과정을 보여주는 움짤이다. 하이디 SQL을 통해 입력한 정보들이 들어오는 걸 확인했고, 값들은 된다는 걸 보여주기 위해 간단하게 넣었다.
이미 가입된 아이디로 가입 시 이미 있는 아이디라는 토스트가 나오는 것도 확인할 수 있다.
'Android' 카테고리의 다른 글
[Android] 레트로핏 사용 중 end of input at line 1 column 1 path $ 에러 해결 (코틀린 버전 첨부) (0) | 2020.05.19 |
---|---|
[Android] Resources$NotFoundException: String resource ID #0x1 에러 해결 (0) | 2020.05.13 |
[Android] TCP/IP 일대다 채팅 소스코드 (0) | 2020.04.28 |
[Android] TCP/IP 1:1 채팅 소스코드 (0) | 2020.04.27 |
[Android] More than one file was found with OS independent path 'META-INF/INDEX.LIST' 에러 해결 (0) | 2020.04.23 |