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

JSONException에러 발생(velly)

0 추천

db를 php와 연동하는중인데요 exception에러가 뜹니다.

public class HealthDataRequest extends StringRequest {
    final static private String URL = "http:///logAdd.php";
    private Map<String, String> map;

    public HealthDataRequest(String userId, String title, String date, String time, String memo, String exerciseRoutine, Response.Listener<String> listener) {
        super(Request.Method.POST, URL, listener, null);
        map = new HashMap<>();
        map.put("userId", userId);
        map.put("title", title);
        map.put("date", date);
        map.put("time", time);
        map.put("memo", memo);
        map.put("routine", exerciseRoutine);
        System.out.println("1번째 실행");
    }

    public HealthDataRequest(String date, Response.Listener<String> listener) {
        super(Request.Method.POST, URL, listener, null);

        map = new HashMap<>();
        map.put("date", date);

        System.out.println("2번째 실행");
    }

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

 

똑같지만 db테이블에 맞춰 조금만 수정된 회원가입php파일에서는 잘 동작합니다. 그런데 왜 아래php파일에서는  Exception에러가 뜰까요...?

    $connection = mysqli_connect("$host", "$dbUser", "$db_pw", "$db_name");
    if (mysqli_connect_errno()) {
        printf("Connection failed: %s \n", mysqli_connect_error());
        exit();
    }
    else {
        echo "MySql connection is completed";
    }

    $userId = $_POST["userId"];
    $time = $_POST["time"];
    $memo = $_POST["memo"];
    $routine = $_POST["routine"];
    $date = $_POST["date"];
    $title = $_POST["title"];

    // 위에 까지는 문제 없음!

    $statement = mysqli_prepare($connection, "INSERT INTO healthlog VALUE (?,?,?,?,?,?)");
    mysqli_stmt_bind_param($statement, "ssssss", $userId, $time, $memo, $routine, $date, $title);
    mysqli_stmt_execute($statement);
    
    $response = array();
    $response["success"] = true;

 

에러 코드는 다음과 같습니다. 

I/System.out: MySql connection is completedasd123123123123123
W/System.err: org.json.JSONException: Value MySql of type java.lang.String cannot be converted to JSONObject
W/System.err:     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.HealthLogAddScreen$1$1.onResponse(HealthLogAddScreen.java:75)
        at com.example.myhealthdiary.HealthLogAddScreen$1$1.onResponse(HealthLogAddScreen.java:70)
        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일 질문

1개의 답변

0 추천

HealthDataRequest의 두번째 생성자의 경우 date 필드만 존재하기 때문에 PHP에서 db 에 데이터를 저장할 경우 null값이 들어가기 때문에 null이 허용되지 않는 필드가 있다면 에러가 날 것으로 보입니다. 따라서 HealthDataRequest 에 있는 두번째 파라미터를 사용하지 않으시거나 null이 허용되지 않는 필드에 값을 전달하셔야 할 것으로 보입니다.

그리고 PHP코드는 모두 success = true 를 리턴하도록 되어 있는데, 요청값에 대한 유효성 검사도 하시고, 에러가 날 경우 catch하셔서 false 를 리턴하도록 하셔야 합니다.

 

참고로 요청값에 원시필드를 사용하기 보다는 클래스를 사용하시는 편이 더 나을 듯 합니다.
 

public class UserHealthMemo {
     private final String userId;
     private final String title;
     private final String date;
     private final String time;
     private final String memo;

     public HealtRequest(String userId, String title, String date, String time, String memo) {
         this.userId = userId;
         this.title = title;
         this.date = date;
         this.time = time;
         this.memo = memo;
     }

    public Map<String, String> toRequestMap() {
         ....
    }
}



public HealthDataRequest(UserHealthMemo healthMemo, String exerciseRoutine, Response.Listener<String> listener) {
        super(Request.Method.POST, URL, listener, null);
        this.map = healthMemo.toRequestMap();
    }
}

 

Volley를 사용하지 않아서 UserHealthMemo type이 요청 데이터 타입으로 바로 사용될 수 있는지는 잘 모르겠네요. 된다면 굳이 Map을 사용하실 필요가 없구요.

spark (226,420 포인트) 님이 2021년 6월 22일 답변
healthdatarequset의 첫번째 생성자만 사용중인데 에러가 뜹니다...
org.json.JSONException: Value MySql of type java.lang.String cannot be converted to JSONObject
네. 에러 타입이 JSONException이기 때문에 JSJON 파싱관련 에러입니다.다com.example.myhealthdiary.HealthLogAddScreen$1$1.onResponse(HealthLogAddScreen.java:70)
에러메세지는 onResponse 콜백에서 발생하고 있습니다. 원인은
Value MySql of type java.lang.String cannot be converted to JSONObject
이구요. 따라서 응답을 받고 나서 response string을 JSON object으로 변환하는 부분을 확인해 보세요. 올리신 코드에는 해당 부분은 빠져 있어서 더 자세한 건 말씀드릴 수가 없네요.
...