如何从mlab上托管的mongoDB中检索数据

时间:2017-04-06 13:25:02

标签: android mongodb rest

REST API code complete displayfitactivity code 1。这是我从mlab检索数据并在android应用程序中显示它的代码。 2.我使用RESTful api将其连接到mlab ref-&gt; youtube.com/watch?v = pI9FSrP2Fyo&amp; t = 954s 我的收藏中有4列  &#34;书名&#34;:&#34; spcc&#34;,     &#34;作者&#34;:&#34; john&#34;,     &#34;价格&#34;:1234,     &#34; stock&#34;:5,// ref mlab 我想过滤数据,如作者姓名或价格&gt; 50和价格<200等 我将从android app中的用户那里获取数据(过滤条件)。我如何用这种方法编写只获得那些满足用户过滤条件的文件?//对不起,如果它太基本的问题

     private String getData(String urlPath) throws IOException {
        //  n.setText("GET Data");
        StringBuilder result = new StringBuilder();
        BufferedReader bufferedReader =null;

        try {
            //Initialize and config request, then connect to server
            URL url = new URL(urlPath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(10000 /* milliseconds */);
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Content-Type", "application/json");// set header
            urlConnection.connect();

            //Read data response from server
            InputStream inputStream = urlConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {

                result.append(line).append("\n"); }
          }
         catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }   
       return result.toString();
    }

并将此字符串结果传递给postExecute以显示数据

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        List<Books> data=new ArrayList<>();

        JSONArray obj ;
        try {
            obj = new JSONArray(result);
            //obj = new JSONObject(result);
            cN = new String[obj.length()];

            Books[] bookData = new Books[obj.length()];
            for (int i = 0; i < obj.length(); i++) {
                JSONObject jsonobj = obj.getJSONObject(i);
                // Books bookData = new Books();
                String N1;
                bookData[i] = new Books();
                bookData[i].id = jsonobj.getString("_id");
                bookData[i].bookName = jsonobj.getString("bookname");
                bookData[i].authorName = jsonobj.getString("author");
                bookData[i].price = Integer.parseInt(jsonobj.getString("price"));
                bookData[i].stock = Integer.parseInt(jsonobj.getString("stock"));
                data.add(bookData[i]);
                if (i == obj.length() - 1) {
                    n.setText("total row = " + obj.length());
                }

0 个答案:

没有答案