java - 在 Android 中将 Php 连接到 MySQLi

标签 java php android mysql mysqli

我正在尝试将我的 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:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference at com.example.errahulraj.phpconnection.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:134) at com.example.errahulraj.phpconnection.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:105) at android.os.AsyncTask$2.call(AsyncTask.java:304)

最佳答案

你在这行有问题。

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

您的 json 对象没有获得值(value),因此保持为 null。和字母您正在尝试访问空对象的方法,因此会发生错误。检查你的网址

否则在使用前检查值

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

关于java - 在 Android 中将 Php 连接到 MySQLi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47604654/

相关文章:

java - 榛子 Actor | IMap 上的操作是否是分布式的?

java - 根据不同的对象类型修改java中的列表的位置

PHP获取数组中最后插入项的索引

javascript - Sublime Text 3 Linter 问题

java - 如何从静态方法调用非静态方法?

android 自动完成在第一次不起作用

java - Spring 启动: How run Bean Validation before Authentication?

java - 为什么以下代码在运行时不打印值?

php - 在进行 == 和 === 比较时,变量的顺序是否重要?

android - React-native ERROR : In <declare-styleable> FontFamilyFont, 无法找到属性 android:fontVariationSettings