마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

JSON 파싱시 IF문 사용 질문입니다!

0 추천
package com.ko.kov;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class bt1 extends MainActivity {

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "json 가져올 주소.php";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bt1_main);

        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        {
            new GetContacts().execute();
        }
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(bt1.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            bt1_HttpHandler sh = new bt1_HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("result");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString("u_id");
                        String name = c.getString("u_pw");

                        // Phone node is JSON Object


                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                            contact.put("u_id", id);
                            contact.put("u_pw", name);
                            // adding contact to contact list
                            contactList.add(contact);
                        }


                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
                ListAdapter adapter = new SimpleAdapter(
                        bt1.this, contactList,
                        R.layout.bt1_list_item, new String[]{"u_id", "u_pw"
                }, new int[]{R.id.name,
                        R.id.email
                });

                lv.setAdapter(adapter);
            }
        }
    }

위 소스를 예제로

데이터베이스에서 특정 조건의 열 만 리스트로 가져오는 것을 구현하고싶습니다.

위에서는 id 값을 갖고 테스트 해보았는데 if문을 왠만한데 다넣어봤는데 제대로 구현이 안됩니다

어느부분에 어떻게 if문을 적용해야지 정상적으로 활용을 할 수 있을까요?

도움 주시면 감사하겠습니다!

크로로롱 (120 포인트) 님이 2017년 3월 27일 질문
제이슨 어레이중에서 필요한 오브젝트만 가져오시겠다는건가여?
포문돌리실때 얻은 id로 분기해서 처리하시면 될것같은데

1개의 답변

0 추천
이상이 없어 보이는데 비정상동작을 하면 의심 가는 곳이 로그를 찍으세요. 거기서도 안 나오면 그 윗 줄에 또 찍으시고요.

계속 위로 올라가다보면 어디서 잘못 됐는지 나옵니다.
쎄미 (162,410 포인트) 님이 2017년 3월 27일 답변
...