来自MySQL数据库的数据未显示在Android Textview中

时间:2013-12-20 13:31:29

标签: java android mysql json textview

我无法显示MySQL数据库中的数据。我想从我的数据库中检索一些数据并将其显示到textview,但它无法正常工作。

Java代码:

public class Penjualan1 extends Activity {
// All xml labels

String pid;

TextView mejaTv;
TextView customerTv;
TextView keteranganTv;

// Progress Dialog
private ProgressDialog pDialog;

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

// Profile JSON url
private static final String url_order_detials =  "-my url-/get_penjualan_details.php";

// ALL JSON node names
private static final String TAG_PRODUCT = "product";
private static final String TAG_SUCCESS = "success";
private static final String TAG_GET = "get";
private static final String TAG_MEJA = "meja";
private static final String TAG_CUST = "customer";
private static final String TAG_KET = "keterangan";


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


mejaTv = (TextView) findViewById(R.id.meja);
customerTv = (TextView) findViewById(R.id.customer);
keteranganTv = (TextView) findViewById(R.id.keterangan);

// Loading Profile in Background Thread
new GetProductDetails().execute();
}

/**
 * Background Async Task to Get complete product details
 * */
class GetProductDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Penjualan1.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
                 // TODO Auto-generated method stub
                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(
                            url_order_detials, "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_GET); // JSON Array

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

                        // product with this pid found
                        // Edit Text
                        mejaTv = (TextView) findViewById(R.id.meja);
                        customerTv = (TextView) findViewById(R.id.customer);
                        keteranganTv = (TextView) findViewById(R.id.keterangan);

                        // display product data in EditText
                        mejaTv.setText(product.getString(TAG_MEJA));
                        customerTv.setText(product.getString(TAG_CUST));
                        keteranganTv.setText(product.getString(TAG_KET));

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

}

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 penjualan WHERE pid = $pid");

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

            $result = mysql_fetch_array($result);

            $product = array();
            $product["pid"] = $result["pid"];
            $product["meja"] = $result["meja"];
            $product["customer"] = $result["customer"];
            $product["keterangan"] = $result["keterangan"];
            // success
            $response["success"] = 1;

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

            array_push($response["get"], $product);

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

/* * 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 penjualan WHERE pid = $pid"); if (!empty($result)) { // check for empty result if (mysql_num_rows($result) > 0) { $result = mysql_fetch_array($result); $product = array(); $product["pid"] = $result["pid"]; $product["meja"] = $result["meja"]; $product["customer"] = $result["customer"]; $product["keterangan"] = $result["keterangan"]; // success $response["success"] = 1; // user node $response["get"] = array(); array_push($response["get"], $product); // 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); } ?>

我见过其他帖子的示例代码,但我不太明白如何应用它。你能给我一些示例代码吗?

1 个答案:

答案 0 :(得分:0)

PHP代码

//您需要在$ pid附近添加单引号

 $result = mysql_query("SELECT *FROM penjualan WHERE pid = '$pid'");

对于您的java代码:

public class Penjualan1 extends Activity {
// All xml labels

String pid;

TextView mejaTv;
TextView customerTv;
TextView keteranganTv;

// Progress Dialog
private ProgressDialog pDialog;

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

// Profile JSON url
private static final String url_order_detials =  "-my url-/get_penjualan_details.php";

// ALL JSON node names
private static final String TAG_PRODUCT = "product";
private static final String TAG_SUCCESS = "success";
private static final String TAG_GET = "get";
private static final String TAG_MEJA = "meja";
private static final String TAG_CUST = "customer";
private static final String TAG_KET = "keterangan";


String sMeja, sCustomer, sKeterangan; //Declare a variable to handle your data.

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


mejaTv = (TextView) findViewById(R.id.meja);
customerTv = (TextView) findViewById(R.id.customer);
keteranganTv = (TextView) findViewById(R.id.keterangan);

// Loading Profile in Background Thread
new GetProductDetails().execute();
}

/**
 * Background Async Task to Get complete product details
 * */
    class GetProductDetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Penjualan1.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) {


                    // Check for success tag
                     // TODO Auto-generated method stub
                    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(
                                url_order_detials, "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_GET); // JSON Array

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

                            // product with this pid found
                            // Edit Text

                            // display product data in EditText
                            sMeja = product.getString(TAG_MEJA);
                            sCustomer = product.getString(TAG_CUST);
                            sKeterangan = product.getString(TAG_KET);

                        }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) {
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    mejaTv.setText(sMeja);
                    customerTv.setText(sCustomer);
                    keteranganTv.setText(sKeterangan);
                }
            });


            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }

}

完成..:D