如何在json android中返回多行并将其传递给sqlite

Posted

技术标签:

【中文标题】如何在json android中返回多行并将其传递给sqlite【英文标题】:how to get multiple rows returned in json android and pass it to sqlite 【发布时间】:2017-12-15 04:09:57 【问题描述】:

我正在尝试通过 JSON 将下面提到的 php json 结果的输出输入到我的 android 应用程序中,但我只在我的 android 应用程序 sqlite 中获得第一个条目作为获取的结果,其中可能是 php json_encode 返回的所有行.我想请求有关如何获取所有行并将其传递给 sqlite 的帮助。

"error":false,"user":"id":1,"sutdentId":1,"user_id":"1","full_name":"Mugisha John","school":"APAPER I","level":"Level 2","year":18"error":false,"user":"id":2,"sutdentId":2,"user_id":"1","full_name":"Marie Ange Karamuzi","school":"Gs.st Joseph de Gitarama","level":"Sinior 6","year":20"error":false,"user":"id":3,"sutdentId":3,"user_id":"1","full_name":"Niragire Sangano Charles","school":"Gs. shyogwe","level":"Sinior 4","year":20

我只在我的 android 应用 sqlite 中进入第一行:

"id":1,"sutdentId":1,"user_id":"1","full_name":"Mugisha John","school":"APAPER I","level":"Level 2","year":18

我用来在android中获得上述结果的主要activity.java方法:

private void GetStudentDetail(final String mobile) 
    // Tag used to cancel the request
    String tag_string_req = "req_Verfication";
    progressBarList.setVisibility(View.VISIBLE);
    //        myList.setVisibility(View.GONE);
    StringRequest strReq = new StringRequest(Request.Method.POST,
            Config.FETCH_StudentsOfParent_URL, new Response.Listener<String>
    () 
        @Override
        public void onResponse(String response) 
            Log.d(TAG, "cerfication Response: " + response.toString());
            // Parsing json
            for (int i = 0; i < response.length(); i++) 
                try 
                    JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("error");
                        // Check for error node in json
                        if (!error) 
                            // user successfully exist in database
                            JSONObject user = jObj.getJSONObject("user");
                            String id = user.getString("id");
                            String sutdentId = user.getString("sutdentId");
                            String full_name = user.getString("full_name");
                            String year = user.getString("year");
                            String school = user.getString("school");
                            String level = user.getString("level");
                               // pass id ,sutdentId, fullname ,year ,school and level 
to sqlite
                            db.addUser(id, sutdentId, full_name, year,  school, level);

                            progressBarList.setVisibility(View.GONE);
                            myList.setVisibility(View.VISIBLE);
                            
                          else
                          // Error in login. Get the error message
                      // hiding the progress bar
                        progressBarList.setVisibility(View.GONE);
                        myList.setVisibility(View.VISIBLE);

                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getActivity(), errorMsg, 
      Toast.LENGTH_LONG).show();
                       

                   catch (JSONException e) 
                    // JSON error
                    e.printStackTrace();
                        Toast.makeText(getActivity(), "Json error: " + 
              e.getMessage(), Toast.LENGTH_LONG).show();                         
                   
                 
              
        , new Response.ErrorListener() 
            @Override
             public void onErrorResponse(VolleyError error) 
            Log.e(TAG, "Verfication error Error: " + error.getMessage());
            Toast.makeText(getActivity(),
                      "response error", Toast.LENGTH_LONG).show();
  //                Toast.makeText(getApplicationContext(),
//                        error.getMessage(), Toast.LENGTH_LONG).show();
                 // hiding the progress bar
                progressBarList.setVisibility(View.GONE);
                 myList.setVisibility(View.VISIBLE);
           
         ) 
          @Override
            protected Map<String, String> getParams() 
              // Posting parameters to verfication url
            Map<String, String> params = new HashMap<String, String>();
            params.put("mobile", mobile);
            return params;
          
         ;
   //        // Adding request to request queue
      MyApplication.getInstance().addToRequestQueue(strReq,tag_string_req);
  

【问题讨论】:

【参考方案1】:

您需要将您的 JSON 数据包装在一个数组中,然后在 Android 中使用 JSONArray 对其进行解析

["error":false,"user":"id":1,"sutdentId":1,"user_id":"1","full_name":"Mugisha John","school":"APAPER I","level":"Level 2","year":18"error":false,"user":"id":2,"sutdentId":2,"user_id":"1","full_name":"Marie Ange Karamuzi","school":"Gs.st Joseph de Gitarama","level":"Sinior 6","year":20"error":false,"user":"id":3,"sutdentId":3,"user_id":"1","full_name":"Niragire Sangano Charles","school":"Gs. shyogwe","level":"Sinior 4","year":20]

【讨论】:

Nadiger所以,谢谢。请你帮我,因为我不熟悉 JSONArray,我的这个例子?【参考方案2】:

编辑: 我的 php 代码看起来像下面的文件,但它的工作没问题, 但问题出在安卓。

  public function StudentsOfParent($mobile)
 $stmt = $this->conn->prepare("SELECT
                         a.id,
                         a.name, 
                         a.mobile, 
                         c.id as sutdentId, 
                         c.user_id, 
                         c.full_name, 
                         c.school, 
                         c.level,
                         c.year,
                         c.id                    
                         from users a 
                         join students c 
                         on a.id = c.user_id where a.mobile= ?");
    $stmt->bind_param("i", $mobile);
    if ($stmt->execute()) 

        // $user = $stmt->get_result()->fetch_assoc();
        // $stmt->close();
        //     // return user's results
        //     return $user;
   $result = $stmt->get_result();
      $usersArr = array();
    while ($user = $result->fetch_assoc())
    $usersArr[] = $user;
     
   $stmt->close();
    return $usersArr;
   else 
return NULL;
  

.......

访问上述功能:从mysql获取信息

...........

   $usersArr = $db->StudentsOfParent($mobile);
  if ($usersArr != false) 
     // user found successfully
   $response["error"] = FALSE;
     foreach($usersArr as $key=>$user)
      $response[$key]["user"]["id"] = $user["id"];
      $response[$key]["user"]["sutdentId"] = $user["sutdentId"];
      $response[$key]["user"]["user_id"] = $user["user_id"];
      $response[$key]["user"]["full_name"] = $user["full_name"];
     $response[$key]["user"]["school"] = $user["school"];
      $response[$key]["user"]["level"] = $user["level"];
      $response[$key]["user"]["year"] = $user["year"];
      echo json_encode($response);
     
   else 
 .........

【讨论】:

以上是关于如何在json android中返回多行并将其传递给sqlite的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Node JS 中读取文本文件并将其作为 JSON 对象返回?

android html5,如何从图库应用中获取照片并将其放入画布中

如何使用android studio中的改造服务在请求中传递json

如何在 argo 工作流程中的地图中传递多行 json 字符串

如何仅从一个键中过滤对象并将其作为 json 返回?

如何在 SqlDataReader 之前知道或获取数组大小?并将其作为 json 返回