본문 바로가기

캡스톤

MySQL에서 Android로 데이터 불러오기 (리뷰)

https://cocoaaa.tistory.com/10

Android에서 MySQL로 데이터 불러오기 (카페 정보 불러오기)

https://cocoaaa.tistory.com/9 Android에서 MySQL 데이터 수정 (CafeMoA 좌석 수 변경) MySQL에 미리 등록되어있는 데이터 정보를 수정해보자. 우선 데이터 테이블은 이렇게 구성 하였다. 카페에 대한 기초 정보.

cocoaaa.tistory.com

방법은 이 포스팅과 비슷하다.

 

https://cocoaaa.tistory.com/10

Android에서 MySQL로 데이터 불러오기 (카페 정보 불러오기)

https://cocoaaa.tistory.com/9 Android에서 MySQL 데이터 수정 (CafeMoA 좌석 수 변경) MySQL에 미리 등록되어있는 데이터 정보를 수정해보자. 우선 데이터 테이블은 이렇게 구성 하였다. 카페에 대한 기초 정보.

cocoaaa.tistory.com

리뷰를 볼 카페이름은 여기서 받아온다.

 

https://cocoaaa.tistory.com/11

Android에서 MySQL로 데이터 저장하기 (리뷰)

https://cocoaaa.tistory.com/7 Android에서 MySQL로 데이터 저장하기 (회원가입) Android에서 MySQL로 회원가입을 위해 데이터 저장을 해보자. 그 전에 이전 포스팅에서 했던 서버 구축을 꼭 해주어야 하고 만약

cocoaaa.tistory.com

리뷰를 작성한 후 내용이다.

 

 

 

php코드를 작성한다.

 

reviewdownload.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
 
<?php
  error_reporting(E_ALL);
  ini_set('display_errors',1);
 
  include('dbcon.php');
 
  $name=isset($_POST['name']) ? $_POST['name'] : '';
 
  $android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");
 
  if ($name != "" ){
 
    $sql="select * from review where name='$name'";
    $stmt = $con->prepare($sql);
    $stmt->execute();
 
    if ($stmt->rowCount() == 0){
 
      echo "'";
      echo $name;
      echo "' have not reviews.";
    }
    else{
      $data = array();
 
      while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
 
        extract($row);
 
        array_push($data,
          array('list'=>$row["list"],
          'name'=>$row["name"],
          'rate'=>$row["rate"],
          'userID'=>$row["userID"],
          'title'=>$row["title"],
          'review'=>$row["review"]
        ));
     }
 
 
      if (!$android) {
          echo "<pre>";
          print_r($data);
          echo '</pre>';
      }else
      {
          header('Content-Type: application/json; charset=utf8');
          $json = json_encode(array("user"=>$data), JSON_PRETTY_PRINT+JSON_UNESCAPED_UNICODE);
          echo $json;
      }
    }
  }
  else {
    echo " download. ";
  }
 
 
?>
 
 
 
<?php
 
$android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");
 
if (!$android){
?>
 
<html>
   <body>
 
      <form action="<?php $_PHP_SELF ?>" method="POST">
         ID: <input type = "text" name = "name" />
         <input type = "submit" />
      </form>
 
   </body>
</html>
<?php
}
 
 
?>
 

 

 

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

 

 

제대로 불러오는것을 확인했다.

 

 

앱으로 옮기기 위해 레이아웃을 작성한다.

로그인 하지 않았을 때의 리뷰 불러오기로 예를 들어보겠다.

 

 

activity_review3.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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/informText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
 
        android:text=".,"
        >
    </TextView>
 
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:id="@+id/listView_main_list" />
 
 
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:id="@+id/textView_main_result" />
 
 
</LinearLayout>

 

 

Review3Activity.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package com.example.cafemoa;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
 
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.widget.TextView;
import android.os.Bundle;
 
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
 
public class Review3Activity extends AppCompatActivity {
 
    String name;
 
    private static String IP_ADDRESS = "203.237.179.120:7003";
    private static String TAG = "phpreviewdownload";
 
    private TextView mTextViewResult;
    private ArrayList<ReviewData> mArrayList;
    private ReviewAdapter mAdapter;
    private RecyclerView mRecyclerView;
    private String mJsonString;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_review3);
 
 
        Intent intent = getIntent();
        name = intent.getExtras().getString("name");
 
 
        mTextViewResult = (TextView)findViewById(R.id.textView_main_result);
        mRecyclerView = (RecyclerView)findViewById(R.id.listView_main_list);
 
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), 1));
 
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
 
        mTextViewResult.setMovementMethod(new ScrollingMovementMethod());
 
 
 
        mArrayList = new ArrayList<>();
 
        mAdapter = new ReviewAdapter(this, mArrayList);
        mRecyclerView.setAdapter(mAdapter);
 
 
 
 
        GetData task = new GetData();
        task.execute( "http://" + IP_ADDRESS + "/ReviewDownload.php", name);
 
 
    }
 
 
    private class GetData extends AsyncTask<String, Void, String> {
 
        ProgressDialog progressDialog;
        String errorString = null;
 
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
 
            progressDialog = ProgressDialog.show(Review3Activity.this,
                    "Please Wait"nulltruetrue);
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
 
            progressDialog.dismiss();
            mTextViewResult.setText(result);
            Log.d(TAG, "response - " + result);
 
            if (result == null){
 
                mTextViewResult.setText(errorString);
            }
            else {
 
                mJsonString = result;
                showResult();
            }
        }
 
 
        @Override
        protected String doInBackground(String... params) {
 
            String serverURL = params[0];
            String name = params[1];
 
            String postParameters = "name=" + name;
 
            try {
 
                URL url = new URL(serverURL);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
 
 
                httpURLConnection.setReadTimeout(5000);
                httpURLConnection.setConnectTimeout(5000);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoInput(true);
                httpURLConnection.connect();
 
 
                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(postParameters.getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();
 
 
                int responseStatusCode = httpURLConnection.getResponseCode();
                Log.d(TAG, "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;
 
                while((line = bufferedReader.readLine()) != null){
                    sb.append(line);
                }
 
                bufferedReader.close();
 
                return sb.toString().trim();
 
 
            } catch (Exception e) {
 
                Log.d(TAG, "GetData : Error ", e);
                errorString = e.toString();
 
                return null;
            }
 
        }
    }
 
 
    private void showResult(){
 
        String TAG_JSON="user";
        String TAG_rate = "rate";
        String TAG_userID ="userID";
        String TAG_title="title";
        String TAG_review="review";
 
 
 
        try {
            JSONObject jsonObject = new JSONObject(mJsonString);
            JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);
 
            for(int i=0;i<jsonArray.length();i++){
 
                JSONObject item = jsonArray.getJSONObject(i);
 
 
                String rate = item.getString(TAG_rate);
                String userID = item.getString(TAG_userID);
                String title =item.getString(TAG_title);
                String review =item.getString(TAG_review);
 
 
                ReviewData ReviewData = new ReviewData();
 
                ReviewData.setReview_rate(rate);
                ReviewData.setReview_userID(userID);
                ReviewData.setReview_title(title);
                ReviewData.setReview_review(review);
 
 
                mArrayList.add(ReviewData);
                mAdapter.notifyDataSetChanged();
            }
 
 
 
        } catch (JSONException e) {
 
            Log.d(TAG, "showResult : ", e);
        }
 
    }
 
 
 
}

 

 

 

결과물

 

 

 

 

 

※주의할점

나는 코드를 로그인 했을 때와 안했을 때를 구분해서 작성하였으므로 잘 나눠서 할 필요가 있다.

따라서 로그인 했을 때는 카페이름, 아이디, 유저 종류를 넘겨주어야 하고 비로그인 시 카페이름만 넘겨주면 된다.