dsg24156 2015-05-31 13:14
浏览 72

即使php工作正常,在android中对php查询的空响应

Tableenter image description here

I'm trying to retrieve the above data using the two php files below. I want to pass a email parameter and return all bets with the user = email. They work fine when tested with Advanced Rest Client, so the problem is not with php. However, when I try to do this through Android with the two java classes below, I get a null pointer exception (logcat below) and the json object returned is null. I'm not sure where my error is, I think I'm not passing the parameter properly to the php and that's why it's producing a null response.

Logcat

05-31 15:10:50.227  26074-26074/com.example.albert.betterapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.albert.betterapp, PID: 26074
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.albert.betterapp/com.example.albert.betterapp.DisplayAllBets}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350)
            at android.app.ActivityThread.access$800(ActivityThread.java:163)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5335)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.albert.betterapp.DisplayAllBets.onCreate(DisplayAllBets.java:79)
            at android.app.Activity.performCreate(Activity.java:5389)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2256)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350)
            at android.app.ActivityThread.access$800(ActivityThread.java:163)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5335)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)

Get_Bets.php

<?php

class Get_Bets {

   private $db;

   function __construct() {

    require_once 'DB_Connect.php';
    $this->db = new DB_Connect();
        $response = array();

    $this->db->connect();


}


function __destruct() {
   
  }

  public function getUsersBets($email) {

   $conn=mysqli_connect("****", "*****", "****","****");

   $result = mysqli_query($conn,"SELECT * FROM bet WHERE user = '$email'");

   $no_of_rows = mysqli_num_rows($result);
     
    if ($no_of_rows > 0) {
     
      $response["bet"] = array();

        while ($row = mysqli_fetch_array($result)) {
        // temp user array
        $bet = array();
        $bet["id"] = $row["id"];
        $bet["stake"] = $row["stake"];
        $bet["user"] = $row["user"];
        $bet["returns"] = $row["returns"];
        $bet["teams"] = $row["teams"];
        $bet["status"] = $row["status"];
        



        // push single gamelist into final response array
        array_push($response["bet"], $bet);
}
      return $response;
       }
    
}
}
?>

Get_All_Bets.php

<?php

if (isset($_POST['email']) && $_POST['email'] != '') {
    // get tag
    $email = $_POST['email'];
 
    // include db handler
     require_once 'include/Get_Bets.php';


    $db = new Get_Bets();
 
    // response Array
    $response = $db->getUsersBets($email);
           
    echo json_encode($response);
}
?>
 

DisplayAllBets.java

public class DisplayAllBets extends ActionBarActivity {
    private String user1 = "user";
    private static String url_all_games = "******";
    // Progress Dialog
    private ProgressDialog pDialog;
    private String name;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> bet;

    // url to get all products list

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_BET = "bet";
    private static final String TAG_ID = "id";
    private static final String TAG_STAKE = "stake";
    private static final String TAG_USER = "user";
    private static final String TAG_RETURNS = "returns";
    private static final String TAG_TEAMS = "teams";
    private static final String TAG_STATUS = "status";


    // products JSONArray
    JSONArray allgames = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_display_all_bets);


        name = (getIntent().getExtras().getString("user")).toLowerCase();
        Log.d("name",name);
        // Hashmap for ListView
        bet = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllGames().execute();

      
    /**
     * Background Async Task to Load all product by making HTTP Request
     */
    class LoadAllGames extends AsyncTask<String, String, String> {
            private String id;
            private String stake;
            private String user;
            private String returns;
            private String teams;
            private String status;


          //  *//**
          //   * Before starting background thread Show Progress Dialog
         //    *//*
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(DisplayAllBets.this);
                pDialog.setMessage("Loading Games. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
            }

          //  *//**
         //    * getting All products from url
         //    *//*
            protected String doInBackground(String... args) {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("email", name));
                // getting JSON string from URL
                JSONObject json = jParser.makeHttpRequest(url_all_games, "GET", params);

                // Check your log cat for JSON reponse

                try {
                    // Checking for SUCCESS TAG
                    int success = json.getInt(TAG_SUCCESS);

                    if (success == 1) {
                        // products found
                        // Getting Array of Games
                        String jsons = json.toString();
                        Log.d("json.tostring",jsons);
                        String formattedjsons = jsons.substring(jsons.indexOf('{'));
                        Log.d("formatted",formattedjsons);
                        JSONObject jObj = new JSONObject(formattedjsons);
                        allgames = jObj.getJSONArray(TAG_BET);

                        // looping through All Products
                        for (int i = 0; i < allgames.length(); i++) {
                            JSONObject c = allgames.getJSONObject(i);

                            // Storing each json item in variable
                            String id = c.getString(TAG_ID);
                            String user = c.getString(TAG_USER);
                            String returns = c.getString(TAG_RETURNS);
                            String stake = c.getString(TAG_STAKE);
                            String status = c.getString(TAG_STATUS);
                            String Teams = c.getString(TAG_TEAMS);


                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            map.put(TAG_ID, id);
                            map.put(TAG_TEAMS, Teams);
                            map.put(TAG_USER, user);
                            map.put(TAG_RETURNS, returns);
                            map.put(TAG_STAKE, stake);
                            map.put(TAG_STATUS, status);


                            // adding HashList to ArrayList
                            bet.add(map);
                        }

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

                return "";
            }

        /**
         * After completing background task Dismiss the progress dialog
         * *
         */
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread



        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_display_all_bets, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

JSONParser.java

public class JSONParser {

    static InputStream is = null;

    static JSONObject jObj = null;

    static String json = "";
    // constructor


    public JSONParser() {
    }


    // function get json from url
    // by making HTTP POST or GET mehtod


    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {
        // Making HTTP request
        try {
            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {

                if (!line.startsWith("<", 0)) {
                    if (!line.startsWith("(", 0)) {
                        sb.append(line + "
");
                    }
                }
            }

            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

</div>
  • 写回答

1条回答 默认 最新

  • dongsilu2237 2015-05-31 13:31
    关注

    Your Java code performs a HTTP GET request:

    JSONObject json = jParser.makeHttpRequest(url_all_games, "GET", params);
    

    and your PHP code expects a POST request:

    if (isset($_POST['email']) && $_POST['email'] != '')
    

    You can change your Java code to:

    JSONObject json = jParser.makeHttpRequest(url_all_games, "POST", params);
    

    or your PHP code to:

    if (isset($_GET['email']) && $_GET['email'] != '')
    

    I'm not sure if this is the only problem.

    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集