관리 메뉴

웹개발자의 기지개

[안드로이드] Volley 로 웹요청하고 응답받기3 - Get방식 , json 읽기 (php,mysql) 본문

안드로이드

[안드로이드] Volley 로 웹요청하고 응답받기3 - Get방식 , json 읽기 (php,mysql)

http://portfolio.wonpaper.net 2020. 6. 11. 06:43

이번에는 Spinner 을 이용하는데, 

시도와 구군항목이 각각 Spinner 로 되어 있고, 

해당 시도를 클릭하면 그에 따른 구군 내용을 mysql 상에서 자동 읽어 와서 구군 Spinner 가 자동 업데이트 되도록 해보자.

 

mysql 상의 zipcode1 테이블 정보

 

 

[ json형태로 읽을 수 있는 php파일 - json_area2.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
<?
header("Content-Type:application/json;charset=utf-8");
include "../inc/config.php";
 
$sido        = $_GET[sido];
 
$query  = "select gu from zipcode1 where si='$sido' order by gu ASC";
$res    = mysqli_query($conn,$query) or die("Selection Failure !");
 
if ($res) {
 
    $arr2 = array();
        
        $arr = array();
        $arr[] = "전체";
 
        while ($row = mysqli_fetch_object($res)) {
/*            
            $t = new stdClass();
            $t->gugun = $row->gu;
            $arr[] = $t;
            unset($t);
 
*/            $arr[] = $row->gu;
        }
 
    $arr2['area2'= $arr;
 
else {
    $arr2 = array(0 => 'empty');
}
 
echo json_encode($arr2,JSON_PRETTY_PRINT+JSON_UNESCAPED_UNICODE);
?>
cs

 

위의 php 파일을 실제로 읽어서 json 형태의 내용물을 테스트해보자.

http://도메인/json_area2.php?sido=대구

{
    "area2": [
        "전체",
        "남구",
        "달서구",
        "달성군",
        "동구",
        "북구",
        "서구",
        "수성구",
        "중구"
    ]
}

 

[ Fragment1.java ] - 프레그먼트로 해당 소스가 되어 있느나 실제 내용부분은 Activity에 그대로 적용해도 된다.

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
public class Fragment1 extends Fragment {
    public static final String TAG = "Fragment1";
    private Context context;
 
    Spinner spinner1;
    ArrayAdapter<String> spinner1Adapter;
    Spinner spinner2;
    ArrayAdapter<String> spinner2Adapter;
 
 
    String[] spinner1Items = {"전체","서울","경기","인천","대전","광주","울산","대구","부산","세종","강원","충북","충남","전북","전남","경북","경남","제주"};
    ArrayList<String> spinner2Items = new ArrayList<String>();
 
    static RequestQueue requestQueue;
 
    public Fragment1() { }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
 
        context = container.getContext();
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
 
        // RequestQueue 객체생성
        if (requestQueue == null) {
 
            // 구군 스피너 데이터 초기화
            spinner2Items.add("전체");
            requestQueue = Volley.newRequestQueue(context);
        }
 
        // 시도
        spinner1 = (Spinner) rootView.findViewById(R.id.spinner1);
        spinner1Adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_dropdown_item,spinner1Items);
        spinner1.setAdapter(spinner1Adapter);
        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
               String sido = spinner1.getSelectedItem().toString();
               String uri = String.format("http://도메인/json_area2.php?sido=%s",sido);
               StringRequest request = new StringRequest(
                        Request.Method.GET,
                        uri,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
 
                                // 구군 스피너 데이터 리셋
                                spinner2Items.clear();
 
                                try {
 
                                    JSONObject jsonObject = new JSONObject(response);
                                    JSONArray area2Arr   = jsonObject.getJSONArray("area2");
 
                                    for (int i=0;i<area2Arr.length();i++) {
                                        spinner2Items.add(area2Arr.getString(i));
                                    }
                                    spinner2Adapter.notifyDataSetChanged(); // 구군 스피너 내용 업데이트
 
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
 
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                println("spinner1 에러 : " + error.getMessage());
                            }
                        }
                ) {
                    @Override //response를 UTF8로 변경해주는 소스코드
                    protected Response<String> parseNetworkResponse(NetworkResponse response) {
                        try {
                            String utf8String = new String(response.data, "UTF-8");
                            return Response.success(utf8String, HttpHeaderParser.parseCacheHeaders(response));
                        } catch (UnsupportedEncodingException e) {
                            // log error
                            return Response.error(new ParseError(e));
                        } catch (Exception e) {
                            // log error
                            return Response.error(new ParseError(e));
                        }
                    }
 
                    // POST 방식으로 요청할 경우에 전달하는 파라미터값들 지정
                    @Override
                    protected Map<StringString> getParams() throws AuthFailureError {
                        //return super.getParams();
                        Map<String,String> params = new HashMap<String,String>();
                        return params;
                    }
                };
 
                // StringRequest 객체의 태그값을 지정
                request.setTag(TAG);
 
                // 캐쉬기능을 끊다. 바로바로 내용처리되도록
                request.setShouldCache(false);
                requestQueue.add(request);
            }
 
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
 
            }
        });
 
        // 구군
        spinner2 = (Spinner) rootView.findViewById(R.id.spinner2);
        spinner2Adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_dropdown_item,spinner2Items);
        spinner2.setAdapter(spinner2Adapter);
 
 
    }
 
}
cs

 

 

 

Comments