java - Android从MySql表中获取数据

标签 java php android mysql

我正在开发一个 android 应用程序...我在 MySql 中开发了一个表,该表具有 1-10 值的某些结果,所有值都是单独输入的...

在我的 android 应用程序中,当显示特定值时,必须从表中获取该值的结果......但它无法正常工作......消息越来越像“不幸的应用程序关闭”......我在这里添加我的代码......请检查代码,如果发现任何错误请帮助......

Activity .java

public class FirstResult extends Activity

{

        String pid;
        TextView txtName;

    // Progress Dialog
        private ProgressDialog pDialog;

        // JSON parser class
        JSONParser jsonParser = new JSONParser();


        // single product url
           private static final String url_product_detials = "http://iascpl.com/app/get_product_details.php";


        // 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_NUMBER = "number";
            //private static final String TAG_PRICE = "price";
            private static final String TAG_DESCRIPTION = "description";


    @Override
    protected void onCreate(Bundle savedInstanceState) 

    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.firstresult_xm);




        TextView txt1 = (TextView) findViewById (R.id.textView2);
        txt1.setText(getIntent().getStringExtra("name10"));

        pid = txt1.getText().toString();


        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(FirstResult.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(
                                url_product_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_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.textView3);


                            // display product data in EditText

                            txtName.setText(product.getString(TAG_DESCRIPTION));

                        }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文件

<?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 prediction 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["number"] = $result["number"];
           // $product["price"] = $result["price"];
            $product["description"] = $result["description"];
            $product["created_at"] = $result["created_at"];
            $product["updated_at"] = $result["updated_at"];


            // success
            $response["success"] = 1;

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

            array_push($response["product"], $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";

我的日志

11-05 11:44:12.701: E/AndroidRuntime(7643):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at com.example.numero.JSONParser.makeHttpRequest(JSONParser.java:63)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at com.example.numero.FirstResult$GetProductDetails$1.run(FirstResult.java:105)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at android.os.Handler.handleCallback(Handler.java:725)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at android.os.Looper.loop(Looper.java:137)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at android.app.ActivityThread.main(ActivityThread.java:5041)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at java.lang.reflect.Method.invokeNative(Native Method)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at java.lang.reflect.Method.invoke(Method.java:511)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-05 11:44:12.701: E/AndroidRuntime(7643):     at dalvik.system.NativeStart.main(Native Method)
11-05 11:52:08.052: E/Trace(7805): error opening trace file: No such file or directory (2)
11-05 11:56:14.171: E/AndroidRuntime(7805): FATAL EXCEPTION: main
11-05 11:56:14.171: E/AndroidRuntime(7805): android.os.NetworkOnMainThreadException
11-05 11:56:14.171: E/AndroidRuntime(7805):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at com.example.numero.JSONParser.makeHttpRequest(JSONParser.java:63)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at com.example.numero.FirstResult$GetProductDetails$1.run(FirstResult.java:105)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at android.os.Handler.handleCallback(Handler.java:725)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at android.os.Looper.loop(Looper.java:137)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at android.app.ActivityThread.main(ActivityThread.java:5041)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at java.lang.reflect.Method.invokeNative(Native Method)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at java.lang.reflect.Method.invoke(Method.java:511)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-05 11:56:14.171: E/AndroidRuntime(7805):     at dalvik.system.NativeStart.main(Native Method)
11-05 11:56:25.961: E/Trace(7893): error opening trace file: No such file or directory (2)

最佳答案

runOnUiThread(new Runnable() {  
                    @Override
                    public void run() 
                    {
                        // TODO Auto-generated method stub
                        try {


                            txt3.setText(product.getString(TAG_DESCRIPTION));

                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });

            }else{
                // product with pid not found
            }

之后添加这一行
/ get first product object from JSON Array
                            JSONObject product = productObj.getJSONObject(0);

                            // product with this pid found
                            // Edit Text
                            txtName = (TextView) findViewById(R.id.textView3);

这将解决问题

关于java - Android从MySql表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19788635/

相关文章:

java - Pivotal Server 3.1 无法在 STS 3.6.4 中工作

java - 拖放程序项目

php - 匹配两个不同表中的变量

android - 谷歌助手安卓集成

java - 我有两个线程,两个几乎相同的东西,但仅在其中一个上出现 CalledFromWrongThreadException 错误。为什么?

java - 如何使用 ReSTLet 将所有路径路由到单个 ServerResource

java - Bash 在 Java 中无法正确执行

平面文件 ORM 类中的 PHP 空文件输出

php - 无法使用 PHP 从 MySQL 获取

java - 在设备中安装 Android 应用程序