【问题标题】:Data from a MySQL database is not displaying in Android Textview来自 MySQL 数据库的数据未显示在 Android Textview 中
【发布时间】:2013-12-20 13:31:28
【问题描述】:

我无法显示 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);
}
?>

我看过其他帖子的示例代码,但我不太明白如何应用它。可以给我示例代码吗?

【问题讨论】:

  • 该查询是否正确?您在 * 之后错过了一个空格
  • 首先检查您通过浏览器从 PHP 获得的响应。然后检查您的 JSON 是否被正确解析。在控制台上记录值。学习调试代码。
  • 佩德罗眼光不错。还有你可以分享的日志吗?
  • 我已经尝试寻找错误,但我不知道她的错误在哪里,这是我的第一个代码,如果从 SQLite 我能够向她展示,但从 MYSQL 对我来说非常困难,我有3天找到他的错,但我没有找到它

标签: java android mysql json textview


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多