簡體   English   中英

無法從Android應用中的服務器獲取JSON數據

[英]JSON data not being fetched from server in android app

因此,我才剛剛開始使用JSON和Volley。 我已經使用XAMMP創建了服務器,並添加了生成JSON數據所需的php腳本。 它在瀏覽器中正常顯示。 但是,在模擬器上運行應用程序時。 永遠不會檢索數據,並且進度對話框會不斷加載,因此應用程序絕不會崩潰。 我采用的代碼如下。 我想念什么?

public class Config {


public static final String DATA_URL2= "http://10.0.2.2:8080/webservice/index.php";
public static final String KEY_ID = "ID";
public static final String KEY_NAME = "Name";
public static final String KEY_SURNAME = "Surname";
public static final String JSON_ARRAY = "result";}

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;

private ProgressDialog loading;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editTextId = (EditText) findViewById(R.id.editTextId);
    buttonGet = (Button) findViewById(R.id.buttonGet);
    textViewResult = (TextView) findViewById(R.id.textViewResult);

    buttonGet.setOnClickListener(this);
}

private void getData() {

    loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);

    String url = Config.DATA_URL2.toString();

    StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            loading.dismiss();
            showJSON(response);
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private void showJSON(String response){
    String id="";
    String name="";
    String surname = "";
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
        JSONObject collegeData = result.getJSONObject(0);
        id = collegeData.getString(Config.KEY_ID);
        name = collegeData.getString(Config.KEY_NAME);
        surname = collegeData.getString(Config.KEY_SURNAME);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    textViewResult.setText("ID:\t"+id+"\nName:\t" +name+ "\nSurname:\t"+ surname);
}

@Override
public void onClick(View v) {
    getData();
}}

這是我的堆棧跟蹤:

    02-14 00:15:19.215 22098-22098/? I/art: Not late-enabling -Xcheck:jni (already on)
02-14 00:15:19.807 22098-22125/za.co.volleydemo D/OpenGLRenderer: Render dirty regions requested: true
02-14 00:15:19.839 22098-22098/za.co.volleydemo D/Atlas: Validating map...
02-14 00:15:19.902 22098-22106/za.co.volleydemo I/art: Background partial concurrent mark sweep GC freed 1945(127KB) AllocSpace objects, 0(0B) LOS objects, 52% free, 921KB/1945KB, paused 5.021ms total 25.227ms
02-14 00:15:19.958 22098-22125/za.co.volleydemo I/OpenGLRenderer: Initialized EGL, version 1.4
02-14 00:15:20.046 22098-22125/za.co.volleydemo D/OpenGLRenderer: Enabling debug mode 0
02-14 00:15:20.073 22098-22125/za.co.volleydemo W/EGL_emulation: eglSurfaceAttrib not implemented
02-14 00:15:20.073 22098-22125/za.co.volleydemo W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xae2c5a40, error=EGL_SUCCESS
02-14 00:15:23.058 22098-22182/za.co.volleydemo E/Volley: [275] BasicNetwork.performRequest: Unexpected response code 401 for http://10.0.2.2:8080
02-14 00:15:23.076 22098-22125/za.co.volleydemo W/EGL_emulation: eglSurfaceAttrib not implemented
02-14 00:15:23.077 22098-22125/za.co.volleydemo W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa609f700, error=EGL_SUCCESS
02-14 00:15:23.220 22098-22182/za.co.volleydemo E/Volley: [275] BasicNetwork.performRequest: Unexpected response code 401 for http://10.0.2.2:8080

另外...這是我的PHP腳本

<?php

define('HOST','localhost');
  define('USER','ruchen');
  define('PASS','lollatjie');
  define('DB','webservice1');

 $con = mysqli_connect(HOST,USER,PASS,DB);

$sql = "select * from users where surname = 'Miller'";

$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('id'=>$row[0],
'name'=>$row[1],
'surname'=>$row[2]
));
}

echo json_encode(array("result"=>$result));

mysqli_close($con);
?>

最后,腳本通過我的互聯網瀏覽器生成的JSON數據...

{"result":[{"id":"7","name":"Bob","surname":"Miller"}]}

401表示您無權使用此URL。

從此鏈接http代碼

10.4.2 401未經授權

該請求需要用戶認證。 響應必須包括一個WWW-Authenticate頭域(第14.47節),該頭域包含適用於所請求資源的質詢。 客戶可以用合適的授權頭域(第14.8節)重復請求。 如果請求已包含授權憑證,則401響應指示已拒絕這些憑證的授權

我不確定為什么會收到錯誤代碼401,但我注意到您的代碼中有些奇怪的地方。 為什么要發出String請求而不是JsonObject請求?

畢竟,您是從php服務獲取JSON數據?

將其更改為JsonObjectRequest,因為您的Json的開頭是一個名為“結果”的對象,其中包含一個數組。

我在我的應用程序中做同樣的事情,我的Volley下載看起來像這樣:

 theEvents = new ArrayList<Event>();
    requestQueue = Volley.newRequestQueue(getActivity());
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
            (Request.Method.GET, urlService, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {

                    try {


                        id = response.getString(Config.KEY_ID); // response is now the actual object called "result" from your JSON data.
                          // do something with the ID
                        }
.........etc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM