본문 바로가기

캡스톤

Android에서 MySQL로 데이터 저장이나 수정하기 (카페 정보 수정 및 등록)

 

https://cocoaaa.tistory.com/13

 

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

이곳에서 사용한 DB테이블을 쓸 것이다.

 

 

만약 카페 정보가 등록되어있다면 그 정보를 수정하고, 등록이 되어있지 않다면 새롭게 등록하는 기능을 만들어 볼 것이다.

 

 

항상 했던것 처럼 php코드를 작성한다.

 

insertinfo.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
93
94
95
96
97
<?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'];
        $address=$_POST['address'];
        $businessHour=$_POST['hour'];
        $instargram=$_POST['insta'];
        $phone=$_POST['phone'];
        $inform=$_POST['inform'];
        $emptySeats=0;
 
        if(empty($name)){
            $errMSG = "name";
        }
        else if(empty($address)){
            $errMSG = "address";
        }
        else if(empty($businessHour)){
            $errMSG = "businessHour";
        }
        else if(empty($phone)){
            $errMSG = "phone";
        }
 
        if(!isset($errMSG)) 
        {
            try{
                $stmt = $con->prepare("INSERT INTO info VALUES ('$name', '$address', '$businessHour', '$emptySeats', '$instargram', '$phone', '$inform') ON DUPLICATE KEY UPDATE address='$address', businessHour='$businessHour', instargram='$instargram', phone='$phone', inform='$inform'");
                $stmt->bindParam(':name'$name);
                $stmt->bindParam(':address'$address);
                $stmt->bindParam(':businessHour'$businessHour);
                $stmt->bindParam(':emptySeats'$emptySeats);
                $stmt->bindParam(':instargram'$instargram);
                $stmt->bindParam(':phone'$phone);
                $stmt->bindParam(':inform'$inform);
 
                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" />
                Address: <input type = "text" name = "address" />
                Hour: <input type = "text" name = "hour" />
                Instargram: <input type = "text" name = "insta" />
                Phone: <input type = "text" name = "phone" />
                Inform: <input type = "text" name = "inform" />
                <input type = "submit" name = "submit" />
            </form>
       
       </body>
    </html>
 
<?php 
    }
?>
 
 
 

이 DB테이블은 이전에 카페 정보 불러오기에서 사용했던 테이블을 이용했다. 따라서 주키는 카페 이름인 name이다.

 

INSERT INTO info VALUES ('$name', '$address', '$businessHour', '$emptySeats', '$instargram', '$phone', '$inform') ON DUPLICATE KEY UPDATE address='$address', businessHour='$businessHour', instargram='$instargram', phone='$phone', inform='$inform' 쿼리를 보내 주키인 name이 존재하지 않는다면 새로 등록을, 존재한다면 데이터 수정을 하게만들었다.

 

 

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

 

등록해보자.

 

등록이 되었는지 확인해본다.

 

 

이제 안드로이드로 옮겨가보자.

 

 

레이아웃을 작성해준다.

 

acrivity_inform_edit.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="#FFFFFF"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="87dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:text="카페명"
        android:textSize="20dp"
        android:textStyle="bold"></TextView>
    <EditText
        android:id="@+id/editName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="카페의 명칭을 입력해주세요"
        ></EditText>
    <TextView
        android:layout_width="87dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:text="위치"
        android:textSize="20dp"
        android:textStyle="bold"></TextView>
    <EditText
        android:id="@+id/editAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="주소를 입력해주세요"
        ></EditText>
    <TextView
        android:layout_width="87dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:text="시간"
        android:textSize="20dp"
        android:textStyle="bold"></TextView>
    <EditText
        android:id="@+id/editHour"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="영업시간을 입력해주세요"
        ></EditText>
    <TextView
        android:layout_width="87dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:text="SNS"
        android:textSize="20dp"
        android:textStyle="bold"></TextView>
    <EditText
        android:id="@+id/editInsta"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="SNS 주소를 입력해주세요"
        ></EditText>
 
    <TextView
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:text="전화번호"
        android:textSize="20dp"
        android:textStyle="bold"></TextView>
    <EditText
        android:id="@+id/editPhone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="전화번호를 입력해주세요"
        ></EditText>
 
    <TextView
        android:layout_width="133dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:text="기타 정보"
        android:textSize="20dp"
        android:textStyle="bold"></TextView>
    <EditText
        android:id="@+id/editInform"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="기타 정보를 입력해주세요"
        ></EditText>
 
    <Button
        android:id="@+id/editSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="저장"
        android:layout_gravity="right|bottom"></Button>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/textView_result" />
 
    >
</LinearLayout>

카페 이름, 주소, 영업시간, SNS, 전화번호, 기타 정보를 입력할 수 있도록 구성하였다.

 

 

ImformEditActivity.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
206
207
208
209
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 InformEditActivity extends AppCompatActivity {
 
    String loginID;
    String loginSort;
 
    private static String IP_ADDRESS = "203.237.179.120:7003";
    private static String TAG = "phpinfoadd";
 
    private EditText  mEditTextName;
    private EditText  mEditTextAddress;
    private EditText  mEditTextHour;
    private EditText  mEditTextInsta;
    private EditText  mEditTextPhone;
    private TextView  mEditTextInform;
    private TextView mTextViewResult;
    private AlertDialog dialog;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inform_edit);
 
        Intent intent = getIntent();
        loginID = intent.getExtras().getString("loginID");
        loginSort = intent.getExtras().getString("loginSort");
 
        mEditTextName = (EditText)findViewById(R.id.editName);
        mEditTextAddress = (EditText)findViewById(R.id.editAddress);
        mEditTextHour = (EditText)findViewById(R.id.editHour);
        mEditTextInsta = (EditText)findViewById(R.id.editInsta);
        mEditTextPhone = (EditText)findViewById(R.id.editPhone);
        mEditTextInform = (EditText)findViewById(R.id.editInform);
        mTextViewResult = (TextView)findViewById(R.id.textView_result);
 
        mTextViewResult.setMovementMethod(new ScrollingMovementMethod());
 
 
        Button buttonInsert = (Button)findViewById(R.id.editSave);
        buttonInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
                String Name = mEditTextName.getText().toString();
                String Address = mEditTextAddress.getText().toString();
                String Hour = mEditTextHour.getText().toString();
                String Insta = mEditTextInsta.getText().toString();
                String Phone = mEditTextPhone.getText().toString();
                String Inform = mEditTextInform.getText().toString();
 
                InsertData task = new InsertData();
                task.execute("http://" + IP_ADDRESS + "/insertinfo.php", Name,Address,Hour,Insta,Phone,Inform);
 
                mEditTextName.setText("");
                mEditTextAddress.setText("");
                mEditTextHour.setText("");
                mEditTextInsta.setText("");
                mEditTextPhone.setText("");
                mEditTextInform.setText("");
 
 
                AlertDialog.Builder builder = new AlertDialog.Builder(InformEditActivity.this);
                dialog = builder.setMessage("카페 정보를 수정하였습니다.")
                        .setCancelable(false)
                        .setPositiveButton("확인"new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(InformEditActivity.this, InformationActivity.class);
                                intent.putExtra("loginID", loginID);
                                intent.putExtra("loginSort", loginSort);
                                InformEditActivity.this.startActivity(intent);
                            }
                        })
 
 
                        .create();
                dialog.show();
 
            }
        });
 
 
    }
 
 
    class InsertData extends AsyncTask<String, Void, String> {
        ProgressDialog progressDialog;
 
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
 
            progressDialog = ProgressDialog.show(InformEditActivity.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 address = (String)params[2];
            String hour = (String)params[3];
            String insta = (String)params[4];
            String phone = (String)params[5];
            String inform = (String)params[6];
 
 
            String serverURL = (String)params[0];
            String postParameters = "name=" + name + "&address=" + address + "&hour=" + hour + "&insta=" + insta + "&phone=" + phone + "&inform" + inform;
 
 
            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());
 
 
            }
 
        }
    }
 
 
}

이곳에선 지금까지 했던 것처럼 입력 받은 값들을 DB에 저장요청하는 부분이다.

 

 

결과물