roshanpeter
roshanpeter

Reputation: 1364

Android get data from MySql table

I am developing an android app... where I developed a table in MySql and table has certain results for values of 1-10 and all the values are entered seperately ...

in my android application when a particular value is displayed the result of that value has to be taken from the table... but it is not working correctly ...the message is getting like 'unfortunately application closed'... i am adding my code here... please check the code and if found any mistake pls help.....

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 file

<?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";

my Logcat

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)

Upvotes: 1

Views: 2312

Answers (2)

Jocheved
Jocheved

Reputation: 1135

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
            }

add this line after

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

that will solve the issue

Upvotes: 1

metter
metter

Reputation: 1442

You need to post the stack trace of the problem. You will find it in your logcat view. Also, on a sidenote:

runOnUiThread(new Runnable() { public void run() {

This doesnt make any sense at all at this place because you are basically running a background thread, then you synchronize it and run it on the main thread. Depending on your settings, that won't work because Android does not allow network operations on the main / UI thread.

Edit after LogCat was added:

It's exactly what I mentioned. Android does not allow you to run network traffic on the UI thread. Remove that runOnUiThread stuff from the runOnBackground. Now to set the data you can two one of two things:

  1. Add the runOnUiThread part where you set the textView. Something like:

    runOnUiThread(new Runnable() {
            public void run() {
                TextView tv = findViewById...
                tv.setText(...
            }
    }
    
  2. Return the object you need. This is actually how AsyncTask is supposed to work: In your AsyncTask's runOnBackground, you'd do:

    return product.getString(TAG_DESCRIPTION)
    

Then, in onPostExecute you get that String and set it to your TextViews.

Upvotes: 1

Related Questions