使用Android studio从MongoDB检索数据时抛出异常

时间:2016-05-03 19:15:36

标签: android mongodb android-studio

在Android Studio中,我试图通过我的应用程序从MongoDB中检索数据。为此,我编写了这段代码(如下所示),但是应用程序会抛出异常并进入catch。那么这段代码的问题是什么呢?它是如何解决的?

代码:

@Override
protected JSONObject doInBackground(Object... params) {

    JSONObject jsonResponse = null;
    int responseCode;

    try {
        URL requestUrl = new URL("my url");
        HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setRequestProperty("Accept-Encoding", "identity");
        connection.connect();

        responseCode = connection.getResponseCode();

        if (responseCode != HttpURLConnection.HTTP_OK) {
            Log.e(TAG, "Status Code: " + responseCode);
        }

        else {
            InputStream stream = connection.getInputStream();
            Reader reader = new InputStreamReader(stream);
            int contentLength = connection.getContentLength();
            if (contentLength > 0) {
                char[] buffer = new char[contentLength ];
                reader.read(buffer);
                Log.d(TAG, buffer);
                jsonResponse = new JSONObject(String.valueOf(buffer));
            } else {
                String jsonData = isToString(stream);
                jsonResponse = new JSONObject(jsonData);
            }

            Log.d(TAG, jsonResponse.toString(2));
            connection.disconnect();
            Toast.makeText(cntx, "Done Successfully!",Toast.LENGTH_LONG).show();
        }
    }
    catch (Exception e) {
        Toast.makeText(cntx, "Error Occurred!",Toast.LENGTH_LONG).show();
        //Log.e(TAG, "Exception: ", e);
    }


    return jsonResponse;
}

0 个答案:

没有答案