JSON retrive很好,但也有JSONException错误

时间:2017-05-10 01:18:00

标签: php android mysql json

我尝试用php保存MySQL数据库中的用户电话号码和随机4位数。一切都很好,两者:电话号码和随机数都保存在我的数据库中,我可以检索“SUCCESS”json详细信息。但是活动也会使这个问题“解析JSON数据时出错”。我在{catch(JSONException e)}中发现了这条消息.....我知道忘了在某处添加一些东西,如果有人可以帮助我,我将不胜感激。

public class SignUpActivity extends AsyncTask<String, Void, String> {

private Context context;

public SignUpActivity(Context context) {
    this.context = context;
}

protected void onPreExecute() {

}

@Override
protected String doInBackground(String... arg0) {
    String phoneNumber = arg0[0];


    String link;
    String data;
    BufferedReader bufferedReader;
    String result;

    try {
        data = "?phonenumber=" + URLEncoder.encode(phoneNumber, "UTF-8");

        link = "https://androidtest22.000webhostapp.com/bubble/signupbubble.php" + data;
        URL url = new URL(link);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        result = bufferedReader.readLine();
        return result;
    } catch (Exception e) {
        return new String("Exception: " + e.getMessage());
    }
}

@Override
protected void onPostExecute(String result) {
    String jsonStr = result;
    //Toast.makeText(context,jsonStr, Toast.LENGTH_SHORT).show();
    if (jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);
            String query_result = jsonObj.getString("query_result");
            if (query_result.equals("SUCCESS")) {
                Toast.makeText(context, "Data inserted successfully. Signup successful.", Toast.LENGTH_SHORT).show();
            } else if (query_result.equals("FAILURE")) {
                Toast.makeText(context, "Data could not be inserted. Signup failed.", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
        }
    } else {
        Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
    }
}

}

3 个答案:

答案 0 :(得分:0)

这里应该注意以下几点:

  1. 即使抛出异常,也会返回一个String,因此如果出现错误,您将尝试将生成的String转换为JSON,这会抛出JSONException异常。
  2. 您没有关闭连接流。
  3. 您正在传递上下文作为参数,这不是一个好习惯,因为它很容易导致内存泄漏,或类似幻像对象,而是使用自定义接口。
  4. 如果您有:Unable to resolve host "androidtest22.000webhostapp.com": No address associated with hostname。检查您的WiFi连接和设备连接。
  5. 你的web服务在JSON之前返回一个整数,你可以看到here,这使解析不可能。
  6. 最后,代码:

    SignUpTask.java

    public class SignUpTask extends AsyncTask<String, Void, String> {
    
        private static final String TAG = SignUpTask.class.getSimpleName();
    
        private final OnResponse onResponse;
    
        public SignUpTask(final OnResponse onResponse) {
            this.onResponse = onResponse;
        }
    
        @Override
        protected String doInBackground(final String... phones) {
            if (phones == null || phones.length < 1) {
                throw new IllegalArgumentException("You must pass a phone to this task");
            }
    
            final String phone = phones[0];
            HttpURLConnection connection = null;
    
            try {
                final String url = "https://androidtest22.000webhostapp.com/bubble/signupbubble.php" +
                    "?phonenumber=" + URLEncoder.encode(phone, "UTF-8");
    
                connection = (HttpURLConnection) new URL(url).openConnection();
                return new Scanner(connection.getInputStream(), "UTF-8").next();
                } catch (final IOException e) {
                    Log.e(TAG, "Error - Phone Number: " + phone, e);
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
    
            return null;
        }
    
        @Override
        protected void onPostExecute(final String result) {
            if (result == null || result.isEmpty()) {
                onResponse.onFailure(new RuntimeException("Invalid result"));
                return;
            }
    
            try {
                onResponse.onSuccess(new JSONObject(result));
            } catch (final JSONException e) {
                onResponse.onFailure(e);
            }
        }
    
        public interface OnResponse {
    
            void onSuccess(JSONObject result);
    
            void onFailure(Throwable throwable);
        }
    }
    

    YourActivity.java

    private void request() {
        new SignUpTask(new SignUpTask.OnResponse() {
            @Override
            public void onSuccess(final JSONObject result) {
                String queryResult = null;
                try {
                    queryResult = result.getString("query_result");
                } catch (final JSONException e) {
                    Log.e(TAG, "Error", e);
                }
    
                if ("SUCCESS".equals(queryResult)) {
                    showToast("Data inserted successfully.");
                } else if ("FAILURE".equals(queryResult)) {
                    showToast("Data could not be inserted.");
                } else {
                    showToast("Couldn't connect to remote database.");
                }
            }
    
            @Override
            public void onFailure(final Throwable throwable) {
                Log.e(TAG, "Error", throwable);
                showToast("Couldn't get any JSON data.");
            }
        }).execute("999999999");
    }
    
    private void showToast(final String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
    

答案 1 :(得分:0)

如果尝试使用新的JSONObject(jsonStr.trim());

答案 2 :(得分:0)

它会抛出JSONException,因为它会打印无效的JSON字符串。我已检查过网址:https://androidtest22.000webhostapp.com/bubble/signupbubble.php?phonenumber=1265,并显示

的输出
83{"query_result":"SUCCESS"}

您必须从结果中删除该号码。在上面的例子中它是83.可能你忘记删除调试程序时使用的echo

SOLUTION:从结果中删除数字,然后重试。