【问题标题】:Connecting Php to MySQLi in Android在 Android 中将 PHP 连接到 MySQLi
【发布时间】:2018-05-16 05:22:23
【问题描述】:

我正在尝试将我的 Android 应用程序与 mySQL 连接。我在 LogCat 中遇到错误。 你可以在这里找到我的完整代码https://github.com/rraj56801/php-connection 我只关心在这里获得所有产品。

class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivity.this);
        pDialog.setMessage("Loading products. 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>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
       //  Log.d("All Products: ", json.toString());

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

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

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

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 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
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllProductsActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME},
                        new int[] { R.id.pid, R.id.name });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}

JSONParser 代码在这里:

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

            if (params!=null)
                httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

        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(new BasicHttpParams());
            // Setup the get request

            HttpGet httpGetRequest = new HttpGet("http://127.0.0.1");
            try{
                // Execute the request in the client
                HttpResponse httpResponse = httpclient.execute(httpGetRequest);
                // Grab the response
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
                json = reader.readLine();
            }catch(Exception e){
                Log.d("Error",e.toString());
            }
        }


    } 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) {
            sb.append(line + "\n");
        }
        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;

}

这里是LogCat:

原因:java.lang.NullPointerException:尝试调用虚拟 方法 'int org.json.JSONObject.getInt(java.lang.String)' 为空 对象引用 在 com.example.errahulraj.phpconnection.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:134) 在 com.example.errahulraj.phpconnection.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:105) 在 android.os.AsyncTask$2.call(AsyncTask.java:304)

【问题讨论】:

    标签: java php android mysql mysqli


    【解决方案1】:

    你在这行有问题。

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

    您的 json 对象没有获得价值,因此仍然是 null。和信您试图访问空对象的方法,因此发生错误。检查你的网址

    否则在使用前检查值

    if(json != null)
    {
      try
       {
           int success = json.getInt(TAG_SUCCESS);
            ...
            ...
            ...
        }
    }
    

    【讨论】:

    • 没错,但我想知道应该为模拟器和物理设备使用哪个 url..
    • 你应该使用你的系统的IP地址而不是你的本地服务器运行的(127.0.0.1)。在 cmd 中输入 ipconfig 并从那里获取您的 ip(IPv4)
    • Rajs-MacBook-Air:untitled rahulraj$ ifconfig lo0: flags=8049 mtu 16384 options=1203 inet 127.0.0.1网络掩码 0xff000000 inet6 ::1 prefixlen 128 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 nd6 options=201
    • json 实际上始终为空。所以需要一些修改,但我是 JSON 新手。
    • [see this](osxdaily.com/2010/11/21/find-ip-address-mac) 知道你的 ip 然后使用它就像192.168.0.***
    猜你喜欢
    • 2018-01-11
    • 2023-03-11
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2013-12-26
    • 1970-01-01
    • 2013-03-18
    相关资源
    最近更新 更多