본문 바로가기

캡스톤

Android에서 MySQL 데이터 수정 (CafeMoA 좌석 수 변경)

MySQL에 미리 등록되어있는 데이터 정보를 수정해보자.

 

 

우선 데이터 테이블은 이렇게 구성 하였다.

카페에 대한 기초 정보인 카페이름, 주소, 영업시간, 빈좌석, 인스타그램, 전화번호, 추가정보를 설정해두었다.

 

 

서버에 MySQL에 데이터 수정을 요청할 php코드를 작성한다.

Seats.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
<?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'];
        $seats=$_POST['seats'];
 
        if(empty($name)){
            $errMSG = "name";
        }
        else if(empty($seats)){
            $errMSG = "seats";
        }
 
        if(!isset($errMSG)) 
        {
            try{
                $stmt = $con->prepare("UPDATE info SET emptySeats='$seats' WHERE name='$name' LIMIT 1");
                $stmt->bindParam(':name'$name);
                $stmt->bindParam(':seats'$seats);
 
                if($stmt->execute())
                {
                    $successMSG = "update.";
                }
                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" />
                Seats: <input type = "text" name = "seats" />
                <input type = "submit" name = "submit" />
            </form>
       
       </body>
    </html>
 
<?php 
    }
?>

 

 

UPDATE info SET emptySeats='$seats' WHERE name='$name' LIMIT 1로 $name 이름을 가진 데이터의 emptySeats를 받아온 $seats로 바꿔준다.

 

 

웹브라우저에 http://localhost:포트번호/Login.php 실행하면 이렇게 뜬다.

 

수정하고싶은 정보를 입력해서 제출하면 update된다.

안드로이드로 옮기기 위해 레이아웃을 작성한다.

 

activity_seats.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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
    android:background="#FFFFFF"
android:layout_height="wrap_content"
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>
 
<EditText
    android:id="@+id/seatsCount"
    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
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="10"
    >
    <Button
        android:id="@+id/seatsDown"
        android:text="down"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_weight="5"/>
 
    <Button
        android:id="@+id/seatsUp"
        android:text="up"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_weight="5"/>
 
</LinearLayout>
<Button
    android:id="@+id/seatsinitial"
    android:text="초기화"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_weight="5"/>
<Button
    android:id="@+id/seatssave"
    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>
 

 

SeatsActivity.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
205
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 SeatsActivity extends AppCompatActivity {
    String name;
    String loginID;
    String loginSort;
    TextView mTextViewResult;
    EditText seatsCount;
    private AlertDialog dialog;
 
    private static String IP_ADDRESS = "203.237.179.120:7003";
    private static String TAG = "phpseats";
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seats);
 
        mTextViewResult = (TextView) findViewById(R.id.textView_result);
        seatsCount = (EditText) findViewById(R.id.seatsCount);
 
        Intent intent = getIntent();
        name = intent.getExtras().getString("name");
        loginID = intent.getExtras().getString("loginID");
        loginSort = intent.getExtras().getString("loginSort");
 
        setup();
 
        mTextViewResult.setMovementMethod(new ScrollingMovementMethod());
 
 
        Button buttonInsert = (Button) findViewById(R.id.seatssave);
        buttonInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
 
                InsertData task = new InsertData();
                task.execute("http://" + IP_ADDRESS + "/Seats.php", name, seatsCount.getText().toString());
 
                AlertDialog.Builder builder = new AlertDialog.Builder(SeatsActivity.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(SeatsActivity.this,
                    "Please Wait"nulltruetrue);
        }
 
 
        @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 count = (String) params[2];
 
 
            String serverURL = (String) params[0];
            String postParameters = "name=" + name + "&seats=" + count;
 
 
            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());
            }
 
        }
    }
 
    private void setup() {
        Button seatsUp = (Button) findViewById(R.id.seatsUp);
        Button seatsDown = (Button) findViewById(R.id.seatsDown);
        Button seatsinitial = (Button) findViewById(R.id.seatsinitial);
        final TextView seatsCount = (TextView) findViewById(R.id.seatsCount);
 
        seatsUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer count = Integer.parseInt("" + seatsCount.getText());
                count++;
                seatsCount.setText("" + count);
            }
        });
        seatsDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer count = Integer.parseInt("" + seatsCount.getText());
                count--;
                seatsCount.setText("" + count);
            }
        });
 
        seatsinitial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                seatsCount.setText("" + 0);
            }
        });
 
    }
}
 

 

 

 

 

결과물