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

HashMap 관련 질문 있습니다.

0 추천
private double[] pointY =null;
    private double[] pointX = null;
    ArrayList<HashMap<String, String>> personList;

    String myJSON;
    private static final String TAG_RESULTS = "result";
    private static final String TAG_latitude = "latitude";
    private static final String TAG_longitude = "longitude";
    private double[] pointY =null;
    private double[] pointX = null;

    JSONArray peoples = null;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        list = (ListView) findViewById(R.id.listView);
        personList = new ArrayList<HashMap<String, String>>();

        Button btnMove = (Button) findViewById(R.id.btnMove);
        btnMove.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                getData("http://223.xxx.xxx.xxx/PHP_connection.php"); //수정 필요
            }
        });

    }

protected void showList() {
                try {
                    JSONObject jsonObj = new JSONObject(myJSON);
                    peoples = jsonObj.getJSONArray(TAG_RESULTS);

                    int j =0;
                    for (int i = 0; i < peoples.length(); i++) {
                        JSONObject c = peoples.getJSONObject(i);
                        String latitude = c.getString(TAG_latitude);
                        String longitude = c.getString(TAG_longitude);

                        HashMap<String, String> persons = new HashMap<String, String>();

                        persons.put(TAG_latitude,latitude);
                        persons.put(TAG_longitude,longitude);

                        personList.add(persons);

                        // 키로 값을 가져오기

                        String lat = persons.get(TAG_latitude).toString();
                        double latitudee = Double.parseDouble(lat);
                        String lng = persons.get(TAG_latitude).toString();
                        double longitudee = Double.parseDouble(lng);

 

                        pointX[i] = latitudee;
                        pointY[i] = longitudee;

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            public void getData(String url) {
                class GetDataJSON extends AsyncTask<String, Void, String> {

                    @Override
                    protected String doInBackground(String... params) {

                        String uri = params[0];

                        BufferedReader bufferedReader = null;
                        try {
                            URL url = new URL(uri);
                            HttpURLConnection con = (HttpURLConnection) url.openConnection();
                            StringBuilder sb = new StringBuilder();

                            bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                            String json;
                            while ((json = bufferedReader.readLine()) != null) {
                                sb.append(json + "\n");
                            }

                            return sb.toString().trim();

                        } catch (Exception e) {
                            return null;
                        }

                    }

                    protected void onPostExecute(String result) {
                        myJSON = result;
                        showList();
                    }
                }
                GetDataJSON g = new GetDataJSON();
                g.execute(url);
            }
        });

 

대략적인 코드입니다.

제가 하려는건 서버에서 위도 경도 값을 받아와서 각각 배열 pointX, pointY에 순차적으로 저장하고 싶습니다.

궁금한건 HashMap  persons에 데이터를 저장하고 키값을 이용하여

String lat = persons.get(TAG_latitude).toString();
double latitudee = Double.parseDouble(lat);
String lng = persons.get(TAG_latitude).toString();
double longitudee = Double.parseDouble(lng);

위도와 경도 값을 각각 변수에 저장합니다. 문제는 배열 pointX, pointY에 순차적으로 데이터를 저장해야 하는데 이게 잘 안되네요 ㅠㅠ

문제는 for문에서의 i가 배열 pointX와 pointY의 범위보다 많거나 적은거 같은데 조언 부탁드립니다 ㅠㅠ

또 궁금한게

ArrayList<HashMap<String, String>> personList; 의 형태인 배열 personList는 어떤식으로 데이터가 저장 되는건가요 ? 조언부탁드립니다...
해리케인 (210 포인트) 님이 2018년 5월 15일 질문
String lng = persons.get(TAG_latitude).toString(); 는

String lng = persons.get(TAG_longitude).toString(); 아닌가요?

personList는 Arraylist = [ {위도: x, 경도:y},{위도: x, 경도:y},{위도: x, 경도:y},{위도: x, 경도:y}, ... ] 이런식으로 저장되어 있겠죠
혹시 personList에서
위도경도 별로
pointX ={xx.xxxxxxxx , xx.xxxxxxx, xx.xxxxxxx}
pointY = {xxx.xxxxxxx, xxx.xxxxxxx, xxx.xxxxxxx}
이런식으로 따로 저장할 방법은 없는건가요 ??

1개의 답변

0 추천
자료구조를 다시 생각해 보셔야겠어요.

하고 싶은게...사람별로 위도/경도 정보를 입력하고 싶은거라면

그냥 위도/경도 정보를 가진 구조체(클래스)를 만드시고 해당 클래스를 ArrayList 로 만드세요

HashMap은 Array 에 들어갈 놈이 아니에요
부르스리 (1,620 포인트) 님이 2018년 5월 15일 답변
사람별이 아니라 단순히 위도 경도 값을 각각 배열에 순차적으로 저장하려고 합니다 ㅠㅠ
HashMap 은 Hash 값으로 저장되다 보니, 어떤 순서로 저장되는지 알 수 없습니다.
정렬해서 순차적으로 저장 하시려면 TreeMap, 입력 되는 순서대로 저장하시려면 LinkedHashMap 를 사용 하셔야 합니다.
답변 감사합니다!!
마지막으로 궁금한게
for (int i = 0; i < peoples.length(); i++)
이부분인데
peoples = jsonObj.getJSONArray(TAG_RESULTS);
에서 peaples.length()의 크기의 개념(?) 자체를 잘 모르겠어요....
i가 어디까지 증가하는지 알려주실수 없나요? ㅠㅠㅠ

또한 값이 저장된 personList 자체에서 그냥 배열 pointX,pointY로 각각 위도 경도를 저장할수 있는 방법은 없을까요??
죄송합니다 ㅠㅠ
...