2017-08-22 69 views
0

我在Android Studio中遇到了關於如何請求JSON對象的問題。如何使用Android Volley顯示/請求JSON對象?

我的Logcat只能打印字符串onResponse而不是JSONObject值。我遇到了一個問題,請嘗試{}在AccessActivity.java中{}

我的代碼說明如下。

我有這些JSON對象輸出,我從MySQL數據庫中獲取。

{ 
    "access":"PA001", 
    "password":"123", 
    "fullname":"ARCADE", 
    "branch":"HQ", 
    "section":"MPR" 
} 

在我的PHP代碼中,這是我如何獲取數據並將其編碼爲JSON對象。

access.php

<?php 
    $conn = mysqli_connect("","","",""); 
    if(
     isset($_POST['access']) && 
     isset($_POST['password']) 
    ){ 
     $access  = $_POST['access']; 
     $password = $_POST['password']; 
     $sql = "SELECT * FROM table WHERE access = '$access' AND password = '$password' "; 
     $result = mysqli_query($conn, $sql); 
     if($result && mysqli_num_rows($result) > 0){ 
      while($row = mysqli_fetch_array($result)){ 

       $accessdb  = $row['access']; 
       $passworddb = $row['password']; 
       $fullnamedb = $row['fullname']; 
       $branchdb  = $row['branch']; 
       $sectiondb = $row['section']; 

       echo "success_access"; 

       $response = array('access' => $accessdb, 'password' => $passworddb, 'fullname' => $fullnamedb, 'branch' => $branchdb, 'section' => $sectiondb); 
       echo json_encode($response); 
      } 
     mysqli_free_result($result); 
     } else { 
      echo "access_failed"; 
     } 
    } 
?> 

但Android Studio中出現我的問題,

  1. 我甚至不能打印Log.e(TAG, 「JSON對象=」 +的JSONObject );
  2. 我無法將JSON對象值轉換爲下一個活動。

這是我的代碼。

AccessActivity.java

public class AccessActivity extends AppCompatActivity{ 

    final String TAG = this.getClass().getName(); 
    EditText etAccess, etPassword; 
    Button bLogin; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     etAccess  = (EditText)findViewById(R.id.etAccess); 
     etPassword  = (EditText)findViewById(R.id.etPassword); 
     bLogin   = (Button)findViewById(R.id.bLogin); 
     bLogin.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       String url = "http://localhost/access.php"; 
       StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 
         Log.e(TAG, "Response is = " + response); 
         if(response.equals("success_access")){ 
          try { 
           JSONObject jsonObject = new JSONObject(response); 
           Log.e(TAG, "JSON Object is = " + jsonObject); 

           final String accessdb = jsonObject.getString("access"); 
           final String passworddb = jsonObject.getString("password"); 
           final String fullnamedb = jsonObject.getString("fullname"); 
           final String branchdb = jsonObject.getString("branch"); 
           final String sectiondb = jsonObject.getString("branch"); 

           Intent intent = new Intent(AccessActivity.this, NextActivity.class); 
           intent.putExtra("access", accessdb); 
           intent.putExtra("password", passworddb); 
           intent.putExtra("fullname", fullnamedb); 
           intent.putExtra("branch", branchdb); 
           intent.putExtra("section", sectiondb); 
           AccessActivity.this.startActivity(intent); 
          } catch (JSONException e) { 
           e.printStackTrace(); 
          } 
         } else{ 
          Toast.makeText(getApplicationContext(), "Access Error", Toast.LENGTH_SHORT).show(); 
         } 
        } 
       }, new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         Toast.makeText(getApplicationContext(), "Volley Error", Toast.LENGTH_SHORT).show(); 
        } 
       }){ 
        @Override 
        protected Map<String, String> getParams() throws AuthFailureError { 
         Map<String, String> params = new HashMap<>(); 
         params.put("access", etAccess.getText().toString()); 
         params.put("password", etPassword.getText().toString()); 
         return params; 
        } 
       }; 
       MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest); 
      } 
     }); 
    } 
} 

UPDATE:

我logcat中顯示此

08-22 10:22:22.059 19801-19908/com.apps.test D/NetworkSecurityConfig: No Network Security Config specified, using platform default 
08-22 10:22:22.064 19801-19801/com.apps.test E/my.com.apps.test.Activity: Response is = success_access{"access":"PA001","password":"123","fullname":"ARCADE","branch":"HQ","section":"HQ"} 
08-22 10:22:22.112 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200) 
08-22 10:22:22.128 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200) 
08-22 10:22:22.134 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200) 
08-22 10:22:22.140 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200) 
08-22 10:22:23.697 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200) 
08-22 10:22:25.751 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200) 
08-22 10:22:25.780 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200) 

感激,如果有人可以幫我解決這個問題。謝謝。

+0

這將是真正的幫助,如果你可以添加你的logcat – ZeekHuge

+0

@ZeekHuge,我編輯了以上我的問題。 – AlotJai

回答

0

試試這個。

在AccessActivity

Intent intent = new Intent(AccessActivity.this, NextActivity.class); 
intent.putExtra("access", accessdb); 
intent.putExtra("password", passworddb); 
intent.putExtra("fullname", fullnamedb); 
intent.putExtra("branch", branchdb); 
intent.putExtra("section", sectiondb); 
AccessActivity.this.startActivity(intent); 

變化

LoginActivity.this.startActivity(intent); 

AccessActivity.this.startActivity(intent); 

在NextActivity

Intent intent = getIntent(); 
String access = intent.getStringExtra("access"); 
String password = intent.getStringExtra("password"); 
String fullname = intent.getStringExtra("fullname"); 
String branch = intent.getStringExtra("branch"); 
String section = intent.getStringExtra("section"); 

編輯

變化

if(response.equals("success_access")){ 
} 

if(response.contains("success_access")){ 
} 

,並根據您的代碼。 您需要確保您當前的活動是com.apps.test.AccessActivitycom.apps.test.AccessActivity

編輯

變化

if (response.contains("success_access")) { 
     String res = response.substring(response.indexOf("{")); 
     try { 
      JSONObject jsonObject = new JSONObject(res); 
      final String accessdb = jsonObject.getString("access"); 
      final String passworddb = jsonObject.getString("password"); 
      final String fullnamedb = jsonObject.getString("fullname"); 
      final String branchdb = jsonObject.getString("branch"); 
      final String sectiondb = jsonObject.getString("branch"); 
      Log.e("Tag", accessdb); 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
} 
+0

感謝您的反饋。但它不起作用。 。 – AlotJai

+0

@AlotJai你可以顯示·Log.e(標籤,「JSON對象= =」+ jsonObject);·日誌信息? – KeLiuyue

+0

nope。我無法在日誌中顯示jsonObject。 。我已經用我的logcat編輯了我的問題。 – AlotJai

0

你請求一個JSONObject? 您似乎掌握了StringRequest,所以生病讓它簡單。將您的StringRequest更改爲JsonObjectRequest

0

問題:

正如你可以在你的logcat看到你從服務器得到的迴應是success_access{"access":"PA001","password":"123","fullname":"ARCADE","branch":"HQ","section":"HQ"}

首先,這不是一個有效的JSON。 此外,這是response變量的值。 現在,您response.equals("success_access")永遠不會返回true,因此代碼控制將不會進入if塊。

解決方案:

理想情況下,應該沒有額外字符串等success_access,insted的你的反應應該是ALWAYS含有一個指定字段(result費爾德例如)JSON對象。要顯示成功,你的JSON看起來像:

{ 
    result : "success_access", 
    /* other parameters down here */ 
} 

並在發生故障的情況下:

{ 
    result : "access_failed" 
} 

然後你的代碼應respose字符串轉換爲JSON(服務器代碼應該確保它始終返回有效的JSON)檢查result字段的值,然後繼續。

快速修復:

更改您的代碼:

.... 
    Log.e(TAG, "Response is = " + response); 
    String result = response.replace("{.*}",""); 
    String jsonString = response.replace(result, ""); 

    if(result.equals("success_access")){ 
    try { 
      JSONObject jsonObject = new JSONObject(jsonString); 
    ....