Android에서 MySQL로 데이터 저장하기 (회원가입)
Android에서 MySQL로 회원가입을 위해 데이터 저장을 해보자. 그 전에 이전 포스팅에서 했던 서버 구축을 꼭 해주어야 하고 만약 저장할 데이터에 한글이 있다면 언어 설정도 바꿔줘야한다. https://co
cocoaaa.tistory.com
https://cocoaaa.tistory.com/11
Android에서 MySQL로 데이터 저장하기 (리뷰)
https://cocoaaa.tistory.com/7 Android에서 MySQL로 데이터 저장하기 (회원가입) Android에서 MySQL로 회원가입을 위해 데이터 저장을 해보자. 그 전에 이전 포스팅에서 했던 서버 구축을 꼭 해주어야 하고 만약
cocoaaa.tistory.com
이 두가지 포스팅에서 쓴 방법을 사용할 예정이다.
https://cocoaaa.tistory.com/10
Android에서 MySQL로 데이터 불러오기 (카페 정보 불러오기)
https://cocoaaa.tistory.com/9 Android에서 MySQL 데이터 수정 (CafeMoA 좌석 수 변경) MySQL에 미리 등록되어있는 데이터 정보를 수정해보자. 우선 데이터 테이블은 이렇게 구성 하였다. 카페에 대한 기초 정보.
cocoaaa.tistory.com
리뷰를 불러올 카페 이름은 여기서 받아온다.
맨 먼저 적립 테이블을 만든다.
나는 적립한 카페이름, 유저 아이디, 스탬프 갯수, 식별할 고유키를 넣었다.
이 테이블에 저장하는 기능을 php코드로 작성한다.
accumulate.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
|
<?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 )
{
$name=$_POST['name'];
$userID=$_POST['userID'];
$stamp=$_POST['stamp'];
$key=$_POST['name'].$_POST['userID'];
if(empty($name)){
$errMSG = "name";
}
else if(empty($userID)){
$errMSG = "userID";
}
else if(empty($stamp)){
$errMSG = "stamp";
}
if(!isset($errMSG))
{
try{
$stmt = $con->prepare("INSERT INTO accumulate VALUES ('$name', '$userID', '$stamp', '$key') ON DUPLICATE KEY UPDATE stamp=stamp+'$stamp'");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':userID', $userID);
$stmt->bindParam(':stamp', $stamp);
if($stmt->execute())
{
$successMSG = "accumulate.";
}
else
{
$errMSG = "error.";
}
} 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">
Name: <input type = "text" name = "name" />
ID: <input type = "text" name = "userID" />
Stamp: <input type = "text" name = "stamp" />
<input type = "submit" name = "submit" />
</form>
</body>
</html>
<?php
}
?>
|
여기서 지금까지와 다른 포인트는 두 가지가 있는데 첫번째는 고유키를 직접 만들어 저장한다. 고유키는 $key=$_POST['name'].$_POST['userID'] 코드를 작성하여 카페이름+유저ID를 합쳐서 생성하였다.
그리고 두번째는 데이터 저장을 요청하는 query문에서 INSERT INTO accumulate VALUES ('$name', '$userID', '$stamp', '$key') ON DUPLICATE KEY UPDATE stamp=stamp+'$stamp' 로 작성하여 만약 key부분에 들아가는 고유키가 존재하지 않는다면 새로 생성해 넣고, 존재한다면 stamp를 기존 stamp내역과 새로 받아온 stamp내역을 더해서 업데이트 한다는 내용으로 구성하였다.
웹브라우저에 http://localhost:포트번호/accumulate.php 실행하면 이렇게 뜬다.
DB에 저장된 것을 확인할 수 있다.
이제 안드로이드로 옮겨보자.
activity_point.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
|
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:orientation="vertical">
<TextView
android:id="@+id/reviewText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textSize="20dp"
android:text="적립 관리"
></TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="10"
>
<EditText
android:id="@+id/userID"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:hint="고객아이디">
</EditText>
<TextView
android:layout_width="150dp"
android:layout_height="50dp"
android:text="님의 적립점수"
android:textSize="25sp"
android:layout_gravity="center"
android:layout_marginTop="10dp">
</TextView>
<EditText
android:id="@+id/pointCount"
android:text="0"
android:textSize="50sp"
android:textColor="#000000"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:inputType="number"/>
</LinearLayout>
<Button
android:id="@+id/pointsave"
android:text="저장"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="5"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="@+id/textView_result" />
</LinearLayout>
|
PointActivity.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
|
package com.example.cafemoa;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
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 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 PointActivity extends AppCompatActivity {
String name;
String loginID;
String loginSort;
TextView userID, pointCount = null;
int count = 0;
TextView mTextViewResult;
private AlertDialog dialog;
private static String IP_ADDRESS = "203.237.179.120:7003";
private static String TAG = "phppoint";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_point);
Intent intent = getIntent();
name = intent.getExtras().getString("name");
loginID = intent.getExtras().getString("loginID");
loginSort = intent.getExtras().getString("loginSort");
mTextViewResult = (TextView) findViewById(R.id.textView_result);
pointCount = (EditText) findViewById(R.id.pointCount);
userID = (EditText) findViewById(R.id.userID);
mTextViewResult.setMovementMethod(new ScrollingMovementMethod());
Button buttonInsert = (Button) findViewById(R.id.pointsave);
buttonInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
InsertData task = new InsertData();
task.execute("http://" + IP_ADDRESS + "/accumulate.php", name, userID.getText().toString(), pointCount.getText().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(PointActivity.this);
dialog = builder.setMessage("적립되었습니다.")
.setNegativeButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create();
dialog.show();
return;
}
});
}
class InsertData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PointActivity.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 name = (String) params[1];
String userID = (String) params[2];
String stamp = (String) params[3];
String serverURL = (String) params[0];
String postParameters = "name=" + name + "&userID=" + userID + "&stamp=" + stamp;
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());
}
}
}
}
|
결과물
'캡스톤' 카테고리의 다른 글
Android에서 MySQL로 데이터 저장이나 수정하기 (카페 정보 수정 및 등록) (0) | 2020.06.18 |
---|---|
MySQL에서 Android로 데이터 불러오기 (적립 확인) (0) | 2020.06.14 |
MySQL에서 Android로 데이터 불러오기 (리뷰) (0) | 2020.06.10 |
Android에서 MySQL로 데이터 저장하기 (리뷰) (2) | 2020.06.07 |
MySQL에서 Android로 데이터 불러오기 (카페 정보 불러오기) (0) | 2020.06.04 |