<?php
// 데이터베이스 접속 문자열. (db위치, 유저 이름, 비밀번호)
$link=mysqli_connect("localhost","root","inha", "project" );
if (!$link)
{
echo "MySQL 접속 에러 : ";
echo mysqli_connect_error();
exit();
}
mysqli_set_charset($link,"utf8");
$sql="select PID,astext(polygon),area_name from area_test";
$result=mysqli_query($link,$sql);
$total_record = mysqli_num_rows($result);
// JSONArray 형식으로 만들기 위해서...
echo "{\"status\":\"OK\",\"num_results\":\"$total_record\",\"results\":[";
// 반환된 각 레코드별로 JSONArray 형식으로 만들기.
for ($i=0; $i < $total_record; $i++)
{
// 가져올 레코드로 위치(포인터) 이동
mysqli_data_seek($result, $i);
$row = mysqli_fetch_array($result);
echo "{\"PID\":$row[0],\"Polygon\":\"$row[1]\",\"area_name\":\"$row[2]\"}";
// 마지막 레코드 이전엔 ,를 붙인다. 그래야 데이터 구분이 되니깐.
if($i<$total_record-1){
echo ",";
}
}
// JSONArray의 마지막 닫기
echo "]}";
?>
이렇게 PHP 코드를 구성하고 이제 안드로이드에서 포인트 값을 불러와서 사용하려고 하는데요.
JSON형태를 안드로이드 안에서 배열로 저장하여 저희가 그것을 사용하려고 하는데요.
이쪽은 너무 초보라 이해가 잘 안되네요.. 우선 JsonArray로 불러들여와서 화면을 띄우기까지는 성공을 했는데 여기서 안드로이드 내부에서 데이터를 어떻게 사용해야 하는지 감이 안오네요.
또한 Polygon을 어떻게 불러와야하는지도 아신분 있다면 알려주세요!
추가로 코드 더 붙여드립니다.
<MainActivity>
package locationmager.mainproject;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class PolygonDB extends AppCompatActivity {
private static String TAG = "MainActivity";
private static final String TAG_JSON="webnautes";
private static final String TAG_pid = "PID";
private static final String TAG_polygon = "polygon";
private static final String TAG_areaname = "area_name";
private TextView mTextViewResult;
ArrayList<HashMap<String, String>> mArrayList;
ListView mlistView;
String mJsonString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_polygon_db);
mTextViewResult = (TextView)findViewById(R.id.textView_main_result);
mlistView = (ListView) findViewById(R.id.listView_main_list);
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://192.168.0.66/Polygon/index.php"); //수정필요
}
private class GetData extends AsyncTask<String, Void, String>{
ProgressDialog progressDialog;
String errorString = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PolygonDB.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];
try {
URL url = new URL(serverURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.connect();
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 pid =item.getString(TAG_pid);
String polygon = item.getString(TAG_polygon);
String areaname = item.getString(TAG_areaname);
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put(TAG_pid, pid);
hashMap.put(TAG_polygon, polygon);
hashMap.put(TAG_areaname, areaname);
mArrayList.add(hashMap);
}
ListAdapter adapter = new SimpleAdapter(
PolygonDB.this, mArrayList, R.layout.polygon_list,
new String[]{TAG_pid, TAG_polygon, TAG_areaname},
new int[]{R.id.textView_list_pid, R.id.textView_list_polygon, R.id.textView_list_areaname}
);
mlistView.setAdapter(adapter);
} catch (JSONException e) {
Log.d(TAG, "showResult : ", e);
}
}
}