이전 포스팅에서 테이블 구조는 보여주었다.
이번엔 미리 등록해둔 데이터 정보 중 원하는 데이터를 불러오려고 한다.
우선 마찬가지로 php코드를 작성해준다.
cafe_info.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 info where name='$name'"; $stmt = $con->prepare($sql); $stmt->execute(); if ($stmt->rowCount() == 0){ echo "'"; echo $name; echo "' incorrect name."; } else{ $data = array(); while($row=$stmt->fetch(PDO::FETCH_ASSOC)){ extract($row); array_push($data, array( 'name'=>$row["name"], 'address'=>$row["address"], 'businessHour'=>$row["businessHour"], 'emptySeats'=>$row["emptySeats"], 'instargram'=>$row["instargram"], 'phone'=>$row["phone"], 'inform'=>$row["inform"] )); } 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 "cafe name"; } ?> <?php $android = strpos($_SERVER['HTTP_USER_AGENT'], "Android"); if (!$android){ ?> <html> <body> <form action="<?php $_PHP_SELF ?>" method="POST"> cafe name: <input type = "text" name = "name" /> <input type = "submit" /> </form> </body> </html> <?php } ?> |
웹브라우저에 http://localhost:포트번호/Login.php 실행하면 이렇게 뜬다.

카페 이름을 입력하면 카페 정보를 가져온다.

안드로이드로 옮기기 위해서 레이아웃 코드를 작성한다.
activity_infomation.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 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#FFFFFF" tools:context=".InformationActivity"> <TextView android:id="@+id/textView_main_label" android:layout_width="match_parent" android:layout_height="40dp" android:text="검색할 카페 이름을 입력해주세요" android:textSize="18dp"/> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <EditText android:id="@+id/cafe_search" android:layout_width="0dp" android:layout_weight="0.35" android:hint="카페 이름" android:layout_height="match_parent" /> <Button android:id="@+id/button_main_search" android:layout_width="0dp" android:layout_weight="0.3" android:layout_height="match_parent" android:text="Search" /> </LinearLayout> <ListView android:id="@+id/listView_main_list" android:layout_width="match_parent" android:layout_height="425dp" android:layout_weight="24" /> <TextView android:id="@+id/textView_main_result" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="0" /> </LinearLayout> |
ActivityInfomation.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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | package com.example.cafemoa; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; 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; import java.util.HashMap; public class Information2Activity extends AppCompatActivity { private static String TAG = "phpinfo"; private static final String TAG_JSON="user"; private static final String TAG_NAME = "name"; private static final String TAG_address ="address"; private static final String TAG_businessHour ="businessHour"; private static final String TAG_emptySeats ="emptySeats"; private static final String TAG_instargram ="instargram"; private static final String TAG_phone ="phone"; private static final String TAG_inform ="inform"; private TextView mTextViewResult; ArrayList<HashMap<String, String>> mArrayList; ListView mListViewList; EditText mEditTextSearchKeyword1; String mJsonString; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_information2); mTextViewResult = (TextView)findViewById(R.id.textView_main_result); mListViewList = (ListView) findViewById(R.id.listView_main_list); mEditTextSearchKeyword1 = (EditText) findViewById(R.id.cafe_search); Button button_search = (Button) findViewById(R.id.button_main_search); button_search.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mArrayList.clear(); GetData task = new GetData(); task.execute( mEditTextSearchKeyword1.getText().toString()); } }); mArrayList = new ArrayList<>(); } private class GetData extends AsyncTask<String, Void, String>{ ProgressDialog progressDialog; String errorString = null; @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = ProgressDialog.show(Information2Activity.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 searchKeyword1 = params[0]; String serverURL = "http://203.237.179.120:7003/cafe_info.php"; String postParameters = "name=" + searchKeyword1; 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, "InsertData: Error ", e); errorString = e.toString(); return null; } } } private void showResult(){ 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 address = item.getString(TAG_address); String businessHour = item.getString(TAG_businessHour); String emptySeats = item.getString(TAG_emptySeats); String instargram = item.getString(TAG_instargram); String phone = item.getString(TAG_phone); String inform = item.getString(TAG_inform); HashMap<String,String> hashMap = new HashMap<>(); hashMap.put(TAG_NAME, name); hashMap.put(TAG_address,address); hashMap.put(TAG_businessHour,businessHour); hashMap.put(TAG_emptySeats,emptySeats); hashMap.put(TAG_instargram,instargram); hashMap.put(TAG_phone,phone); hashMap.put(TAG_inform,inform); mArrayList.add(hashMap); } ListAdapter adapter = new SimpleAdapter( Information2Activity.this, mArrayList, R.layout.cafe_list, new String[]{TAG_NAME,TAG_address,TAG_businessHour,TAG_emptySeats,TAG_instargram,TAG_phone,TAG_inform}, new int[]{R.id.cafename, R.id.cafeaddress, R.id.cafehour,R.id.cafeseats,R.id.cafeinsta,R.id.cafephone,R.id.cafeinform} ); mListViewList.setAdapter(adapter); } catch (JSONException e) { Log.d(TAG, "showResult : ", e); } } } |
코드가 같이 안들어가서 나눠썼다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.review2menu,menu); return true; } public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()){ case R.id.see2Review: Intent intent1=new Intent(Information2Activity.this,Review3Activity.class); intent1.putExtra("name", mEditTextSearchKeyword1.getText().toString()); Information2Activity.this.startActivity(intent1); break; } return true; } } | cs |
결과물


'캡스톤' 카테고리의 다른 글
MySQL에서 Android로 데이터 불러오기 (리뷰) (0) | 2020.06.10 |
---|---|
Android에서 MySQL로 데이터 저장하기 (리뷰) (2) | 2020.06.07 |
Android에서 MySQL 데이터 수정 (CafeMoA 좌석 수 변경) (0) | 2020.06.02 |
Android에서 MySQL로 데이터 저장하기 (로그인) (0) | 2020.06.01 |
Android에서 MySQL로 데이터 저장하기 (회원가입) (0) | 2020.05.21 |