Volley,json和php连接

时间:2015-10-10 19:53:41

标签: php android json android-volley

我正在尝试从MySql数据库中获取数据。 这是php代码:

<?php

if($_SERVER["REQUEST_METHOD"]=="POST"){
    include 'connection.php';
    showStudent();
}

function showStudent(){
    global $connect;

    $query = " Select * FROM  utenti";

    $result = mysqli_query($connect, $query);
    $number_of_rows = mysqli_num_rows($result);

    $temp_array  = array();

    if($number_of_rows > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $temp_array[] = $row;
        }
    }

    header('Content-Type: application/json');
    echo json_encode(array("utenti"=>$temp_array));
    mysqli_close($connect);

}

?>

这是获取数据的方法:

public static String mostraDati(){

    final String[] result = new String[50];

    System.out.println("ww");
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, DatiNet.MostraDati, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            System.out.println("fin qui ci siamo");
            try {

                JSONArray utenti = response.getJSONArray("utenti");


                for (int i = 0; i < utenti.length(); i++) {
                    JSONObject student = utenti.getJSONObject(i);

                    String nome = student.getString("nome");
                    String cognome = student.getString("cognome");
                    String numero = student.getString("numero");
                    String email = student.getString("email");

                    result[i] = nome + " " + cognome + " " + email + "\n";
                }

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

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.append(error.getMessage());

        }
    });
    requestQueue.add(jsonObjectRequest);

    return result[0];
}

当我执行它们时,应用程序崩溃..

这是日志:

10-10 19:45:26.363    4373-4373/com.rete.prova.ale.reteale E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.rete.prova.ale.reteale, PID: 4373
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rete.prova.ale.reteale/com.rete.prova.ale.reteale.MostraDati}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
        at com.rete.prova.ale.reteale.Rete.mostraDati(Rete.java:98)
        at com.rete.prova.ale.reteale.MostraDati.onCreate(MostraDati.java:20)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)

at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

问题出在哪里? 我已经宣布结果是最终的,因为编辑强迫我,但是常量不能改变吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

 private static List<String> result = new ArrayList<String>();
 public static void mostraDati(){

    System.out.println("ww");
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, DatiNet.MostraDati, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            System.out.println("fin qui ci siamo");
            try {

                JSONArray utenti = response.getJSONArray("utenti");


                for (int i = 0; i < utenti.length(); i++) {
                    JSONObject student = utenti.getJSONObject(i);

                    String nome = student.getString("nome");
                    String cognome = student.getString("cognome");
                    String numero = student.getString("numero");
                    String email = student.getString("email");
            result.add(nome + " " + cognome + " " + email); // or use StringBuilder to create string!
                }

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

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.append(error.getMessage());

        }
    });   
}

显示数据使用此:

for(String s : result)
{
  System.out.println(s);
}

试试这个php请求:

<?php
mysql_connect("localhost","root","password");
mysql_select_db("DBName");
$q=mysql_query("SELECT * FROM utenti");
while($e=mysql_fetch_assoc($q))
        $output[]=$e;

print(json_encode($output));

mysql_close();
?>