Android에서 MySQL로 회원가입을 위해 데이터 저장을 해보자.
그 전에 이전 포스팅에서 했던 서버 구축을 꼭 해주어야 하고 만약 저장할 데이터에 한글이 있다면 언어 설정도 바꿔줘야한다.
서버 구축하기(Apache, MySQL, PHP 설치 및 연동)
저는 root권한으로 실행했기 때문에 모든 명령에 sudo를 빼고 했습니다. 먼저 저장소의 패키지 목록을 업데이트 하고 기존 설치되어 있던 패키지를 업그레이드 해줍니다. apt update && apt upgrade Apache2
cocoaaa.tistory.com
MySQL 언어 설정 한글로 바꾸기
MySQL에 데이터를 저장하려 했을 때 밑과 같이 에러가 나왔다. #1366 - Incorrect string value: '\xED\x99\x8D\xEB\x9D\xBC...' for column 'name' at row 1 찾아 보니까 이런 에러는 테이블 언어 설정이 utf-8..
cocoaaa.tistory.com
이 두 포스팅을 참고해주자.
MySQL에 미리 회원 정보를 등록 해 둘 테이블을 생성한다.
나는 아이디, 비밀번호, 이메일, 핸드폰 번호, 나중에 회원 구분에 필요한 숫자를 생성해주었다.
이중에서 아이디를 기본키로 설정해주었다.
그다음 서버에 MySQL에 데이터 저장을 요청할 php코드를 작성한다.
Singup.php
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
include('dbcon.php');
$android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");
if( (($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['submit'])) || $android )
{
$userID=$_POST['userID'];
$userPassword=$_POST['userPassword'];
$email=$_POST['email'];
$phoneNumber=$_POST['phoneNumber'];
$userSort=$_POST['userSort'];
if(empty($userID)){
$errMSG = "ID";
}
else if(empty($userPassword)){
$errMSG = "password";
}
else if(empty($email)){
$errMSG = "email";
}
else if(empty($phoneNumber)){
$errMSG = "phonenumber";
}
else if(empty($userSort)){
$errMSG = "sort";
}
if(!isset($errMSG)){
try{
$stmt = $con->prepare('INSERT INTO user(userID, userPassword, email, phoneNumber, userSort) VALUES(:userID, SHA1(:userPassword), :email, :phoneNumber, :userSort)');
$stmt->bindParam(':userPassword', $userPassword);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':phoneNumber', $phoneNumber);
$stmt->bindParam(':userSort', $userSort);
if($stmt->execute())
{
$successMSG = "SUCCESS";
}
else
{
$errMSG = "FAIL";
}
} catch(PDOException $e) {
die("Database error: " . $e->getMessage());
}
}
}
?>
<?php
if (isset($errMSG)) echo $errMSG;
if (isset($successMSG)) echo $successMSG;
$android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");
if( !$android )
{
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
ID: <input type = "text" name = "userID" />
Password: <input type = "text" name = "userPassword" />
email: <input type = "text" name = "email" />
phonenumber: <input type = "text" name = "phoneNumber" />
usersort: <input type = "text" name = "userSort" />
<input type = "submit" name = "submit" />
</form>
</body>
</html>
<?php
}
?>
|
여기서 주목해야할 부분은 'INSERT INTO user(userID, userPassword, email, phoneNumber, userSort) VALUES(:userID, SHA1(:userPassword), :email, :phoneNumber, :userSort)'
이 부분에서 회원가입 중 비밀번호를 SHA1로 단방향 암호화 처리를 해주었다.
또한 앱 상으로 옮겨가기 전에 웹에서 테스트를 해주기위해 밑에 html 코드도 적어주었다.
웹브라우저에 http://localhost:포트번호/Signup.php로 접속하면 밑 처럼 뜬다.
이곳에 저장하고싶은데로 적어주면
SUCCESS가 뜨며 DB에 저장이 된다.
이제 Android로 옮겨가보자.
Android Studio에 회원가입을 위한 코드를 작성해보자.
먼저 layout을 작성한다.
activity_signup.xml
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/registerText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="JOIN US"
android:layout_marginBottom="16dp"
android:textSize="24sp"
></TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="10"
>
<EditText
android:id="@+id/et_id"
android:layout_width="270dp"
android:hint="ID"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="16dp"
android:layout_marginRight="10dp"
></EditText>
</LinearLayout>
<EditText
android:id="@+id/et_pass"
android:layout_width="match_parent"
android:hint="Password"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="16dp"
></EditText>
<EditText
android:id="@+id/et_email"
android:layout_width="match_parent"
android:hint="email"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="16dp"
></EditText>
<EditText
android:id="@+id/et_phone"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:hint="phone number"
></EditText>
<EditText
android:id="@+id/et_sort"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:hint="sort"
></EditText>
<Button
android:id="@+id/btn_register"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="join."
android:layout_marginBottom="16dp"
>
</Button>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="@+id/textView_result" />
></LinearLayout>
|
메인 클래스 부분을 작성한다.
SignupActivity.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
|
package com.example.cafemoa;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.InputType;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.cafemoa.R;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class SignupActivity extends AppCompatActivity {
private static String IP_ADDRESS = "서버ip주소";
private static String TAG = "phpsignup";
private EditText mEditTextID;
private EditText mEditTextPassword;
private EditText mEditTextEmail;
private EditText mEditTextPhone;
private EditText mEditTextSort;
private TextView mTextViewResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
mEditTextID = (EditText)findViewById(R.id.et_id);
mEditTextPassword = (EditText)findViewById(R.id.et_pass);
mEditTextPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
mEditTextEmail = (EditText)findViewById(R.id.et_email);
mEditTextPhone = (EditText)findViewById(R.id.et_phone);
mEditTextSort = (EditText)findViewById(R.id.et_sort);
mTextViewResult = (TextView)findViewById(R.id.textView_result);
mTextViewResult.setMovementMethod(new ScrollingMovementMethod());
Button buttonInsert = (Button)findViewById(R.id.btn_register);
buttonInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String ID = mEditTextID.getText().toString();
String Password = mEditTextPassword.getText().toString();
String Email = mEditTextEmail.getText().toString();
String Phone = mEditTextPhone.getText().toString();
String Sort = mEditTextSort.getText().toString();
InsertData task = new InsertData();
task.execute("http://" + IP_ADDRESS + "/insert.php", ID,Password,Email,Phone,Sort);
mEditTextID.setText("");
mEditTextPassword.setText("");
mEditTextEmail.setText("");
mEditTextPhone.setText("");
mEditTextSort.setText("");
}
});
}
class InsertData extends AsyncTask<String, Void, String>{
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(SignupActivity.this,
"Please Wait", null, true, true);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
mTextViewResult.setText(result);
Log.d(TAG, "POST response - " + result);
}
@Override
protected String doInBackground(String... params) {
String userID = (String)params[1];
String userPassword = (String)params[2];
String email = (String)params[3];
String phoneNumber = (String)params[4];
String userSort = (String)params[5];
String serverURL = (String)params[0];
String postParameters = "userID=" + userID + "&userPassword=" + userPassword + "&email=" + email + "&phoneNumber=" + phoneNumber + "&userSort=" + userSort;
try {
URL url = new URL(serverURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(postParameters.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
int responseStatusCode = httpURLConnection.getResponseCode();
Log.d(TAG, "POST response code - " + responseStatusCode);
InputStream inputStream;
if(responseStatusCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
}
else{
inputStream = httpURLConnection.getErrorStream();
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = bufferedReader.readLine()) != null){
sb.append(line);
}
bufferedReader.close();
return sb.toString();
} catch (Exception e) {
Log.d(TAG, "InsertData: Error ", e);
return new String("Error: " + e.getMessage());
}
}
}
}
|
돌려서 입력하면 success가 뜨면 저장 성공!
내가 겪은 문제는 이런게 있었다.
이 문제는 AndroidManifest.xml에 밑과 같은 코드를 추가안해줘서 발생하였다.
1
2
3
4
5
|
<uses-permission android:name="android.permission.INTERNET" />
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
|
'캡스톤' 카테고리의 다른 글
Android에서 MySQL 데이터 수정 (CafeMoA 좌석 수 변경) (0) | 2020.06.02 |
---|---|
Android에서 MySQL로 데이터 저장하기 (로그인) (0) | 2020.06.01 |
MySQL 언어 설정 한글로 바꾸기 (0) | 2020.05.14 |
서버 구축하기 (Apache, MySQL, PHP 설치 및 연동) (0) | 2020.05.13 |
Google Places API로 주변 카페 탐색 (1) | 2020.04.29 |