Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • errror come on run time to connect my android app with mysql

    • 0
    • 0
    • 0
    • 4
    • 0
    • 0
    • 0
    • 721
    Answer it

    my code this AllProductsActivity Class

    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&#95;all&#95;products = "http://192.168.56.1/android&#95;connect/get&#95;all&#95;products.php";
    
    // JSON Node names
    private static final String TAG&#95;SUCCESS = "success";
    private static final String TAG&#95;PRODUCTS = "products";
    private static final String TAG&#95;PID = "pid";
    private static final String TAG&#95;NAME = "name";
    
    // products JSONArray
    JSONArray products = null;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all&#95;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&#95;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&#95;all&#95;products, "GET", params);
    
            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());
    
            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG&#95;SUCCESS);
    
                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG&#95;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&#95;PID);
                        String name = c.getString(TAG&#95;NAME);
    
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
    
                        // adding each child node to HashMap key => value
                        map.put(TAG&#95;PID, id);
                        map.put(TAG&#95;NAME, name);
    
                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewProductActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG&#95;ACTIVITY&#95;CLEAR&#95;TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file&#95;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&#95;item, new String[] { TAG&#95;PID,
                            TAG&#95;NAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });
    
        }
    
    }
    

    }

    My JsonParsert Classis here

    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) {
    
        is = null;
        jObj = null;
        json = "";
    
    
        // Making HTTP request
        try {
    
            Log.i("url", "http://www.google.com");
    
            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                Log.i("url", url);
                HttpPost httpPost = new HttpPost(url);
    
                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;
                Log.i("url", url);
                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();
        }
    
    
        Log.i("Stage 1", "Stage 1");
    
        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");
    
                    Log.i("1 ", line);
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
    
        Log.i("Stage 2", "Stage 2");
    
        // 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());
        }
    
        Log.i("Stage 3", "Stage 3");
    
        // return JSON String
        return jObj;
    
    }
    

    }

    Logcat error

    10-13 08:43:41.685: E/AndroidRuntime(1354): FATAL EXCEPTION: AsyncTask #1 10-13 08:43:41.685: E/AndroidRuntime(1354): Process: gurudev.additem, PID: 1354 10-13 08:43:41.685: E/AndroidRuntime(1354): java.lang.RuntimeException: An error occured while executing doInBackground() 10-13 08:43:41.685: E/AndroidRuntime(1354): at android.os.AsyncTask$3.done(AsyncTask.java:300) 10-13 08:43:41.685: E/AndroidRuntime(1354): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 10-13 08:43:41.685: E/AndroidRuntime(1354): at java.util.concurrent.FutureTask.setException(FutureTask.java:222) 10-13 08:43:41.685: E/AndroidRuntime(1354): at java.util.concurrent.FutureTask.run(FutureTask.java:242) 10-13 08:43:41.685: E/AndroidRuntime(1354): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 10-13 08:43:41.685: E/AndroidRuntime(1354): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 10-13 08:43:41.685: E/AndroidRuntime(1354): at java.lang.Thread.run(Thread.java:841) 10-13 08:43:41.685: E/AndroidRuntime(1354): Caused by: java.lang.NoSuchMethodError: org.apache.http.impl.client.DefaultHttpClient.execute 10-13 08:43:41.685: E/AndroidRuntime(1354): at gurudev.additem.JSONParser.makeHttpRequest(JSONParser.java:77) 10-13 08:43:41.685: E/AndroidRuntime(1354): at gurudev.additem.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:128) 10-13 08:43:41.685: E/AndroidRuntime(1354): at gurudev.additem.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1) 10-13 08:43:41.685: E/AndroidRuntime(1354): at android.os.AsyncTask$2.call(AsyncTask.java:288) 10-13 08:43:41.685: E/AndroidRuntime(1354): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 10-13 08:43:41.685: E/AndroidRuntime(1354): ... 3 more

 4 Answer(s)

  • query("SELECT *FROM products")){ if($count = $result->num_rows){ $response["products"] = array(); while($row = $result->fetch_object()){ $product = array(); $product["pid"] = $row->pid; $product["name"] = $row->name; $product["price"] = $row->price; $product["description"] = $row->description; $product["created_at"] = $row->created_at; $product["updated_at"] = $row->updated_at; array_push($response["products"], $product); } $response["success"] = 1; // echoing JSON response echo json_encode($response); // echo $response["products"]; } $result->free(); } else { // no products found $response["success"] = 0; $response["message"] = "No products found"; // echo no users JSON echo json_encode($response); } ?>
Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: