且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android应用程序连接到外部数据库(phpMyAdmin的)使用JSON

更新时间:2022-12-17 22:31:16

我认为错误的主要原因是,您的服务器不返回JSON。

我试图打开 http://101.78.175.101:21280/android_connect/get_all_products.php 在浏览器中,不幸的是,我得到了一个空白页。

有关有效的JSON它应该至少返回 {}

您可以手动验证JSON这个流行的工具 http://jsonlint.com/

所以,首先,你必须让你的服务器返回有效JSON,然后我们可以看到,如果一切工作正常。

I'm trying to connect my android application to an external database. I have a table 'products' in my phpmyadmin database. when I try to open the activity AllProductsActivity in my app, it will crush and show an error.

I have used debug mode to run the app and find that it will dead when runs to the code Log.d("All Products: ", json.toString()); on line 129 and the value of JSONObject json is null.

I am new to write app and I really feel desperate right now. It would be thankful if you can help. thank you to everyone.

FYI:The program first goes to AllProductsActivity.java and then it calls JSONParser.java and EditProductActivity.java. The layout of the AllProductsActivity.java is list_item.xml and the layout of EditProductActivity.java is edit_product.xml. User suppose can choose the option from the list_item and go to regarding page.

Below is the error:

       03-17 17:17:54.003    1821-1821/com.google.andriod.gms.example.hongkongmedicalapp I/Choreographer﹕ Skipped 70 frames!
The application may be doing too much work on its main thread.
       03-17 17:17:54.963    1821-1835/com.google.andriod.gms.example.hongkongmedicalapp E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
       03-17 17:17:54.963    1821-1835/com.google.andriod.gms.example.hongkongmedicalapp W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x40a71930)
       03-17 17:17:55.203    1821-1835/com.google.andriod.gms.example.hongkongmedicalapp E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
       at android.os.AsyncTask$3.done(AsyncTask.java:299)
       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
       at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
       at java.util.concurrent.FutureTask.run(FutureTask.java:239)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
 Caused by: java.lang.NullPointerException
        at com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:129)
       at com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:102)
       at android.os.AsyncTask$2.call(AsyncTask.java:287)
       at java.util.concurrent.FutureTask.run(FutureTask.java:234)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
       at java.lang.Thread.run(Thread.java:856)
03-17 17:17:56.093    1821-1821/com.google.andriod.gms.example.hongkongmedicalapp I/Choreographer﹕ Skipped 57 frames!  The application may be doing too much work on its             
03-17 17:17:56.473    1821-1821/com.google.andriod.gms.example.hongkongmedicalapp I/Choreographer﹕ Skipped 33 frames!  The application may be doing too much work on its main thread.
03-17 17:17:57.173    1821-1821/com.google.andriod.gms.example.hongkongmedicalapp I/Choreographer﹕ Skipped 73 frames!  The application may be doing too much work on its main thread.
03-17 17:17:58.083    1821-1821/com.google.andriod.gms.example.hongkongmedicalapp E/WindowManager﹕ Activity com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40db1fe0 V.E..... R.....ID 0,0-729,192} that was originally added here
android.view.WindowLeaked: Activity com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40db1fe0 V.E..... R.....ID 0,0-729,192} that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
        at android.app.Dialog.show(Dialog.java:281)
        at com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:114)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
        at android.os.AsyncTask.execute(AsyncTask.java:534)
        at com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity.onCreate(AllProductsActivity.java:57)
        at android.app.Activity.performCreate(Activity.java:5104)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
        at android.app.ActivityThread.access$600(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)

Below is the code of AllProductActivity.Java:

package com.google.andriod.gms.example.hongkongmedicalapp;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AllProductsActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

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

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://101.78.175.101:21280/android_connect/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray products = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

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

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received 
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    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
            //When I use debug mode, I find the program dead on this line and the value of JSONObject json is null
            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 {

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

        }

    }
}

Below is the code of EditProductActivity.java

package com.google.andriod.gms.example.hongkongmedicalapp;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class EditProductActivity extends Activity {

    TextView txtName;
    TextView txtPrice;
    TextView txtDesc;
    TextView txtUses;
    TextView txtSide;
    TextView txtPrecau;
    TextView txtinterac;
    TextView txtoverdose;
    String pid;

    // Progress Dialog
    private ProgressDialog pDialog;

// JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCT = "product";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_PRICE = "price";
    private static final String TAG_DESCRIPTION = "description";
    private static final String TAG_USES = "uses";
    private static final String TAG_SIDEEFFECTS = "sideeffects";
    private static final String TAG_PRECAUTIONS= "precauctions";
    private static final String TAG_INTERACTIONS = "interactions";
    private static final String TAG_OVERDOSE = "overdose";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_product);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        // getting product details from intent
        Intent i = getIntent();

        // getting product id (pid) from intent
        pid = i.getStringExtra(TAG_PID);

        // Getting complete product details in background thread
        GetProductDetails dproductdetail = new GetProductDetails();
        dproductdetail.execute();

    }

    /**
     * Background Async Task to Get complete product details
     * */
    class GetProductDetails extends AsyncTask<String, String, String> {
        // JSON parser class
        JSONParser jsonParser = new JSONParser();
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditProductActivity.this);
            pDialog.setMessage("Loading product details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("pid", pid));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest("http://101.78.175.101:21280/android_connect/get_product_details.php", "GET", params);

                        // check your log for json response
                        Log.d("Single Product Details", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received product details
                            JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON Array

                            // get first product object from JSON Array
                            JSONObject product = productObj.getJSONObject(0);

                            // product with this pid found
                            // Edit Text
                            txtName = (TextView) findViewById(R.id.inputName);
                            txtPrice = (TextView) findViewById(R.id.inputPrice);
                            txtDesc = (TextView) findViewById(R.id.inputDesc);
                            txtUses = (TextView) findViewById(R.id.inputuses);
                            txtSide = (TextView) findViewById(R.id.inputsideeffects);
                            txtPrecau = (TextView) findViewById(R.id.inputprecautions);
                            txtinterac= (TextView) findViewById(R.id.inputinteractions);
                            txtoverdose = (TextView) findViewById(R.id.inputoverdose);


                            // display product data in EditText
                            txtName.setText(product.getString(TAG_NAME));
                            txtPrice.setText(product.getString(TAG_PRICE));
                            txtDesc.setText(product.getString(TAG_DESCRIPTION));
                            txtUses.setText(product.getString(TAG_USES));
                            txtSide.setText(product.getString(TAG_SIDEEFFECTS));
                            txtPrecau.setText(product.getString(TAG_PRECAUTIONS));
                            txtinterac.setText(product.getString(TAG_INTERACTIONS));
                            txtoverdose .setText(product.getString(TAG_OVERDOSE));

                        }else{
                            // product with pid not found
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }



}

Below is the code of JSONParser.java

package com.google.andriod.gms.example.hongkongmedicalapp;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

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

    }
}

My php script get_product_details:

<?php

/*
 * Following code will get single product details
 * A product is identified by product id (pid)
 */

// array for JSON response
$response = array();


// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_GET["pid"])) {
    $pid = $_GET['pid'];

    // get a product from products table
    $result = mysql_query("SELECT *FROM products WHERE pid = $pid");

    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {

            $result = mysql_fetch_array($result);

            $products = array();
            $products["pid"] = $result["pid"];
            $products["name"] = $result["name"];
            $products["price"] = $result["price"];
            $products["description"] = $result["description"];
            $products["uses"] = $result["uses"];
            $products["sideeffects"] = $result["sideeffects"];
            $products["precauctions"] = $result["precauctions"];
            $products["interactions"] = $result["interactions"];
            $products["overdose"] = $result["overdose"];
            $products["created_at"] = $result["created_at"];
            $products["updated_at"] = $result["updated_at"];
            // success
            $response["success"] = 1;

            // user node
            $response["products"] = array();

            array_push($response["products"], $products);

            // echoing JSON response
            echo json_encode($response);
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "No product found";

            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

I think that the main reason of error is that your server doesn't return json.

I tried to open http://101.78.175.101:21280/android_connect/get_all_products.php in the browser, and, unfortunately, I got an empty page.

For valid JSON it should return at least {}.

You can manually validate JSON with this popular tool http://jsonlint.com/

So, firstly, you have to make your server return valid JSON, and then we can see if everything else is working fine.