【问题标题】:JSON retrive fine but also have JSONException errorJSON 检索正常但也有 JSONException 错误
【发布时间】:2017-05-10 01:17:59
【问题描述】:

我尝试使用 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();
    }
}

}

【问题讨论】:

    标签: php android mysql json


    【解决方案1】:

    这里需要注意几点:

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

    最后,代码:

    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();
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        83{"query_result":"SUCCESS"}
        

        您必须从结果中删除数字。在上述情况下,它是 83。可能您忘记删除在调试程序时使用的echo

        解决方案:从结果中删除数字,然后重试。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多