MySQL에서 Android로 데이터 불러오기 (적립 확인)
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
이것과 내용이 비슷하다.
역시나! 적립을 확인할 수 있는 php코드를 먼저 작성해보자.
pointcheck.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 | <?php error_reporting(E_ALL); ini_set('display_errors',1); include('dbcon.php'); $userID=isset($_POST['userID']) ? $_POST['userID'] : ''; $android = strpos($_SERVER['HTTP_USER_AGENT'], "Android"); if ($userID != "" ){ $sql="select * from accumulate where userID='$userID'"; $stmt = $con->prepare($sql); $stmt->execute(); if ($stmt->rowCount() == 0){ echo "'"; echo $userID; echo "' have not stamp."; } else{ $data = array(); while($row=$stmt->fetch(PDO::FETCH_ASSOC)){ extract($row); array_push($data, array('name'=>$row["name"], 'userID'=>$row["userID"], 'stamp'=>$row["stamp"], 'nameID'=>$row["nameID"] )); } 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 " list. "; } ?> <?php $android = strpos($_SERVER['HTTP_USER_AGENT'], "Android"); if (!$android){ ?> <html> <body> <form action="<?php $_PHP_SELF ?>" method="POST"> ID: <input type = "text" name = "userID" /> <input type = "submit" /> </form> </body> </html> <?php } ?> |
입력 받은 유저 ID로 등록되어있는 모든 카페 이름, stamp내역, 고유키를 불러온다.
웹브라우저에 http://localhost:포트번호/pointcheck.php 실행하면 이렇게 뜬다.


잘 동작한다.
이제 안드로이드로 옮겨보자.
전 포스팅들에서 잊어버려서 쓰지 못했는데 나는 모든 리스트들을 불러올 때 RecyclerView를 써서 불러온다. 그런데 이걸 쓰려면 다른 여러 연결들을 해주어야 해서 이 부분은 따로 포스팅을 하거나 아니면 다른 블로그들을 참고해주길 바란다.
activity_point2.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 | <?xml version="1.0" encoding="utf-8"?> android:orientation="vertical" android:background="#FFFFFF" 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:textSize="20dp" 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> |
pointlist.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 | <?xml version="1.0" encoding="utf-8"?> android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF" android:orientation="vertical" > <TextView android:id="@+id/cafename" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:textSize="18dp" /> <TextView android:id="@+id/cafepoint" android:layout_width="400dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" /> </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 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 | 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.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; 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 Point2Activity extends AppCompatActivity { String loginID; String loginSort; private static String IP_ADDRESS = "203.237.179.120:7003"; private static String TAG = "phppoint"; private TextView mTextViewResult; private ArrayList<PointData> mArrayList; private PointAdapter mAdapter; private RecyclerView mRecyclerView; private String mJsonString; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); loginID = intent.getExtras().getString("loginID"); loginSort = intent.getExtras().getString("loginSort"); setContentView(R.layout.activity_point2); 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 PointAdapter(this, mArrayList); mRecyclerView.setAdapter(mAdapter); Point2Activity.GetData task = new Point2Activity.GetData(); task.execute( "http://" + IP_ADDRESS + "/pointcheck.php", loginID); } private class GetData extends AsyncTask<String, Void, String> { ProgressDialog progressDialog; String errorString = null; @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = ProgressDialog.show(Point2Activity.this, "Please Wait", null, true, true); } @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 userID = params[1]; String postParameters = "userID=" + userID; 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_name = "name"; String TAG_stamp ="stamp"; 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 name = item.getString(TAG_name); String stamp = item.getString(TAG_stamp); PointData PointData = new PointData(); PointData.setCafe_name(name); PointData.setCafe_point(stamp); mArrayList.add(PointData); mAdapter.notifyDataSetChanged(); } } catch (JSONException e) { Log.d(TAG, "showResult : ", e); } } } |
PointData.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 | package com.example.cafemoa; public class PointData { private String cafe_name; private String cafe_point; public String getCafe_name() { return cafe_name; } public String getCafe_point() { return cafe_point; } public void setCafe_name(String cafe_name) { this.cafe_name = cafe_name; } public void setCafe_point(String cafe_point) { this.cafe_point = cafe_point; } } |
PointAdapter.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 | package com.example.cafemoa; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class PointAdapter extends RecyclerView.Adapter<PointAdapter.CustomViewHolder> { private ArrayList<PointData> mList = null; private Activity context = null; public PointAdapter(Activity context, ArrayList<PointData> list1) { this.context = context; this.mList = list1; } class CustomViewHolder extends RecyclerView.ViewHolder { protected TextView name; protected TextView point; public CustomViewHolder(View view) { super(view); this.name = (TextView) view.findViewById(R.id.cafename); this.point = (TextView) view.findViewById(R.id.cafepoint); } } @Override public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.pointlist, null); CustomViewHolder viewHolder = new CustomViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(@NonNull CustomViewHolder viewholder, int position) { viewholder.name.setText(mList.get(position).getCafe_name()); viewholder.point.setText(mList.get(position).getCafe_point()); } @Override public int getItemCount() { return (null != mList ? mList.size() : 0); } } |
결과물
