简体   繁体   English

无法从Android应用中的服务器获取JSON数据

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

So I have just started playing around with JSON and Volley. 因此,我才刚刚开始使用JSON和Volley。 I've created a server using XAMMP and added the php script required to generate JSON data. 我已经使用XAMMP创建了服务器,并添加了生成JSON数据所需的php脚本。 It comes up fine in the browser. 它在浏览器中正常显示。 However, when running the app on the emulator. 但是,在模拟器上运行应用程序时。 The data is never retrieved and the progress dialog endlessly loads, so the app never crashes. 永远不会检索数据,并且进度对话框会不断加载,因此应用程序绝不会崩溃。 The code I've adopted is below. 我采用的代码如下。 What am I missing? 我想念什么?

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();
}}

Here is my stack trace: 这是我的堆栈跟踪:

    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

Additionally... here is my php script 另外...这是我的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);
?>

and finally, the JSON data generated by the script through my internet browser... 最后,脚本通过我的互联网浏览器生成的JSON数据...

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

401 means you are not authorized to this url. 401表示您无权使用此URL。

From this link http codes 从此链接http代码

10.4.2 401 Unauthorized 10.4.2 401未经授权

The request requires user authentication. 该请求需要用户认证。 The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. 响应必须包括一个WWW-Authenticate头域(第14.47节),该头域包含适用于所请求资源的质询。 The client MAY repeat the request with a suitable Authorization header field (section 14.8). 客户可以用合适的授权头域(第14.8节)重复请求。 If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials 如果请求已包含授权凭证,则401响应指示已拒绝这些凭证的授权

I'm not sure why you get Error Code 401, but I notice something strange in your code. 我不确定为什么会收到错误代码401,但我注意到您的代码中有些奇怪的地方。 Why are you making a String request and not a JsonObject request?! 为什么要发出String请求而不是JsonObject请求?

You are getting JSON data from your php service after all? 毕竟,您是从php服务获取JSON数据?

Change it to a JsonObjectRequest as the beginning of your Json is an Object called "result" which holds an array. 将其更改为JsonObjectRequest,因为您的Json的开头是一个名为“结果”的对象,其中包含一个数组。

I do the same thing in my app and my Volley download looks like that: 我在我的应用程序中做同样的事情,我的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