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

DB에서 데이터 가져오기 [closed]

0 추천
 

현재 데이터베이스에서 특정 사람의 운동 기록정보를 가져올려고 합니다.

그런데org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject에러가 떠서요.. 좀만 도와주시면 감사하겠습니다.

 

[hashmap을 통한 php전달]

package com.example.myhealthdiary;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

public class HealthDataRequest extends StringRequest {
    final static private String URL = 
    final static private String URL2 = 
    final static private String URL3 = 
    private Map<String, String> map;

    public HealthDataRequest(String userId, Response.Listener<String> listener) {
        super(Request.Method.POST, URL3, listener, null);
        map = new HashMap<>();
        map.put("userId",userId);
        System.out.println("3번째 메소드 실행됨");
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return map;
    }
}

 

[Volly 서버 전달 코드]

        Response.Listener<String> responseListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray results = jsonObject.getJSONArray("result");
                    System.out.println(results);
                    for(int i = 0; i < jsonObject.length(); i++) {
                        JSONObject temp = results.getJSONObject(i);
                        String time = (String) temp.get("time");
                        String memo = (String) temp.get("memo");
                        String routine = (String) temp.get("routine");
                        String date = (String) temp.get("dates");
                        String title = jsonObject.getString("title");

                        HealthLog healthLog = new HealthLog(title, date, time, memo, routine);

                        Intent intent = new Intent(HealthLogListScreen.this, HealthLogAddScreen.class);
                        intent.putExtra("log_list", log_list);
                        startActivityForResult(intent, add_request_code);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        // 서버로 데이터 전달
        userId = LoginScreen.user;
        HealthDataRequest hdr = new HealthDataRequest(userId, responseListener);
        RequestQueue queue = Volley.newRequestQueue(HealthLogListScreen.this);
        queue.add(hdr);

 

[PHP코드]

<?php
    error_reporting(E_ALL); 
    ini_set("display_errors", 1);

    $host = "localhost";
    $dbUser = "root";
    $db_pw = "";
    $db_name = "healthdiary";
    
    $connection = mysqli_connect("$host", "$dbUser", "$db_pw", "$db_name");
    mysqli_query($connection, 'SET NAMES utf8');

    $userId = $_POST["userId"];

    $statement = mysqli_prepare($connection, "SELECT * FROM healthlog WHERE userId = ?");
    mysqli_stmt_bind_param($statement, "s", $userId);
    mysqli_stmt_execute($statement);

    $response = array();
    $response["success"] = false;

    while(mysqli_stmt_fetch($statement)) {
        $response["success"] = true;
        $response["userId"] = $userId;
        $response["time"] = $time;
        $response["memo"] = $memo;
        $response["routine"] = $routine;
        $response["dates"] = $dates;
        $response["title"] = $title;
    }

    echo json_encode($response);
?>
    

 

[에러코드]

W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
        at org.json.JSON.typeMismatch(JSON.java:112)
        at org.json.JSONObject.<init>(JSONObject.java:169)
        at org.json.JSONObject.<init>(JSONObject.java:182)
        at com.example.myhealthdiary.HealthLogListScreen$1.onResponse(HealthLogListScreen.java:67)
        at com.example.myhealthdiary.HealthLogListScreen$1.onResponse(HealthLogListScreen.java:63)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

 

질문을 종료한 이유: 해결함
매력적인수박 (670 포인트) 님이 2021년 6월 22일 질문
매력적인수박님이 2021년 7월 6일 closed

1개의 답변

0 추천
이건 개인적인 의견입니다. 저라면 Volley대신 Retrofit를 사용할 것 같습니다. Volley도 라이브러이고 Retrofit도 라이브러이고 둘 다 똑같이 http call을 처리해줄 수 있다면, 사용이 쉽고 쓸데없는 코드를 덜 작성하는 쪽으로 선택할 것 같습니다. Retrofit을 사용하면 지금 님이 하고 있는 JSON 파싱같은 불필요한 과정이 필요없어요.
spark (226,380 포인트) 님이 2021년 6월 22일 답변
...