How to send data from android application to client database?

I want to order some items using android app. I have one xml file, this XML file has some editing texts, some texts entered, which items I want to purchase from the client. Then click the submit button. This part data is then sent to the client database. How can I submit this purchase data to the customer database?

+3


source to share


1 answer


follow this tutorial (the best one) and i added some specific code

link: http://www.androidhive.info/category/mysql/page/2/

link: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

// url to create new product // you need to create php file to connect to server and below url is example

private static String url_create_product = "http://10.0.2.2/html/atm_database`/customers.php";

      

// Edit text

edittext= (EditText) findViewById(R.id.input1);
edittext= (EditText) findViewById(R.id.input2);

      



// Create button

    Button sub = (Button) findViewById(R.id.submit);

 sub.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

        // write code here to  get data from edittext 



            // creating new product in background thread


            new CreateNewProduct().execute();

        }
    });
    }

      

/ ** * Async background task to create new product * * /

class CreateNewProduct extends AsyncTask<String, String,String> {



        /**
         * Before starting background thread Show Progress Dialog
         * */

        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Ac1.this);
            pDialog.setMessage("Please wait..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Log in
         * */

        protected String doInBackground(String... args) {



            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();//namevaluepair is a class in apachae for setting name-val parameter
            params.add(new BasicNameValuePair("id", data1);//BasicNameValuePair is a subclass of NameValuePair is data you have to server
            params.add(new BasicNameValuePair("pass",data2));



            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

            // check log cat fro response
           // Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);
                String cust_name=json.getString("name");
                String sessid=json.getString("id");

                if (success == 1) {
                    // successfully created product

                    //write code to do things getting response from server

                } else {


                    Log.w("else", "wrong id");
                    runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(Ac1.this, "Wrong ID or Password!!", Toast.LENGTH_LONG).show();
                                }
                            });

                }

            } 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 done
            pDialog.dismiss();
        }

    }

      

// class for connecting the server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

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) {//JSONObject used to convert one data type to other  

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));//UrlEncodedFormEntity-->converts string to encoded string to represent in post method

                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;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();//getContent is used to to extract data frm connection between app and php 
            }           


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {//ClientProtocolException-->error in http protocol
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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");
            }
            is.close();
            json = sb.toString();
             Log.i("StringBuilder...", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parserrr", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

      

+2


source







All Articles