Android에서 MySQL로 데이터 저장하기 (회원가입)
Android에서 MySQL로 회원가입을 위해 데이터 저장을 해보자. 그 전에 이전 포스팅에서 했던 서버 구축을 꼭 해주어야 하고 만약 저장할 데이터에 한글이 있다면 언어 설정도 바꿔줘야한다. https://co
cocoaaa.tistory.com
방법은 이 포스팅과 비슷하다.
https://cocoaaa.tistory.com/10
Android에서 MySQL로 데이터 불러오기 (카페 정보 불러오기)
https://cocoaaa.tistory.com/9 Android에서 MySQL 데이터 수정 (CafeMoA 좌석 수 변경) MySQL에 미리 등록되어있는 데이터 정보를 수정해보자. 우선 데이터 테이블은 이렇게 구성 하였다. 카페에 대한 기초 정보.
cocoaaa.tistory.com
리뷰를 불러올 카페 이름은 여기서 받아온다.
먼저 MySQL에 리뷰 테이블은 만든다.
리뷰 번호, 카페이름, 별점, 리뷰를 쓴 유저아이디, 제목, 리뷰 내용 으로 구성하였다.
지금까지 해온것처럼 php코드를 먼저 작성해주자.
reviewupload.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
88
89
90
91
92
|
<?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'];
$rate=$_POST['rate'];
$title=$_POST['title'];
$userID=$_POST['userID'];
$review=$_POST['review'];
if(empty($name)){
$errMSG = "name";
}
else if(empty($userID)){
$errMSG = "userID";
}
else if(empty($rate)){
$errMSG = "rate";
}
else if(empty($title)){
$errMSG = "title";
}
else if(empty($review)){
$errMSG = "review";
}
if(!isset($errMSG))
{
try{
$stmt = $con->prepare('INSERT INTO review(name, rate, userID, title, review) VALUES(:name, :rate, :userID, :title, :review)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':rate', $rate);
$stmt->bindParam(':userID', $userID);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':review', $review);
if($stmt->execute())
{
$successMSG = "upload.";
}
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" />
Rate: <input type = "text" name = "rate" />
ID: <input type = "text" name = "userID" />
Title: <input type = "text" name = "title" />
Review: <input type = "text" name = "review" />
<input type = "submit" name = "submit" />
</form>
</body>
</html>
<?php
}
?>
|
웹브라우저에 http://localhost:포트번호/reviewupload.php 실행하면 이렇게 뜬다.
여기서 내가 원하는 기능이 제대로 작동한다면 안드로이드로 옮기자.
acrivity_review.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
|
<?xml version="1.0" encoding="utf-8"?>
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/reviewText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="리뷰작성"
>
</TextView>
<EditText
android:id="@+id/titleEdit"
android:inputType="textMultiLine"
android:layout_width="match_parent"
android:hint="제목"
android:layout_height="50dp"
android:lines="8"
android:minLines="5"
android:maxLines="10"
android:scrollbars="vertical"
android:background="@null"
></EditText>
<EditText
android:id="@+id/reviewEdit"
android:inputType="textMultiLine"
android:layout_width="match_parent"
android:hint="카페에 대한 여러분의 소중한 의견 부탁드립니다♡"
android:layout_height="400dp"
android:lines="8"
android:minLines="5"
android:maxLines="10"
android:scrollbars="vertical"
android:background="@null"
></EditText>
<RatingBar
android:id="@+id/reviewRating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:isIndicator="false"
android:numStars="5"
android:rating="3"
android:stepSize="0.5"
android:max="5"
>
</RatingBar>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="10"
>
<Button
android:id="@+id/cancelButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="5"
android:text="취소"
>
</Button>
<Button
android:id="@+id/okButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="5"
android:text="확인"
>
</Button>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="@+id/textView_result" />
</LinearLayout>
|
ReviewActivity.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
|
package com.example.cafemoa;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.content.Intent;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
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 ReviewActivity extends AppCompatActivity {
String name;
String loginID;
String loginSort;
float rate;
EditText mEditTextreview, mEditTexttitle;
TextView mTextViewResult;
private AlertDialog dialog;
private static String IP_ADDRESS = "203.237.179.120:7003";
private static String TAG = "phpreviewup";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review);
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);
mTextViewResult.setMovementMethod(new ScrollingMovementMethod());
TextView reviewText=(TextView) findViewById(R.id.reviewText);
EditText titleEdit=(EditText) findViewById(R.id.titleEdit);
EditText reviewEdit=(EditText) findViewById(R.id.reviewEdit);
Button cancelButton=(Button) findViewById(R.id.cancelButton);
Button okButton=(Button)findViewById(R.id.okButton);
RatingBar reviewRating=(RatingBar)findViewById(R.id.reviewRating);
mEditTexttitle = (EditText) findViewById(R.id.titleEdit);
mEditTextreview = (EditText) findViewById(R.id.reviewEdit);
cancelButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent( ReviewActivity.this,InformationActivity.class );
startActivity( intent );
}
});
reviewRating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rate = rating;
}
});
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ReviewActivity.InsertData task = new InsertData();
task.execute("http://" + IP_ADDRESS + "/ReviewUpload.php", name, Float.toString(rate), loginID, mEditTexttitle.getText().toString(), mEditTextreview.getText().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(ReviewActivity.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(ReviewActivity.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 rate = (String)params[2];
String userID = (String)params[3];
String title = (String)params[4];
String review = (String)params[5];
String serverURL = (String)params[0];
String postParameters = "name=" + name + "&rate=" + rate + "&userID=" + userID + "&title=" + title + "&review=" + review;
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.12 |
---|---|
MySQL에서 Android로 데이터 불러오기 (리뷰) (0) | 2020.06.10 |
MySQL에서 Android로 데이터 불러오기 (카페 정보 불러오기) (0) | 2020.06.04 |
Android에서 MySQL 데이터 수정 (CafeMoA 좌석 수 변경) (0) | 2020.06.02 |
Android에서 MySQL로 데이터 저장하기 (로그인) (0) | 2020.06.01 |