如何从Android应用程序发送数据到客户端的数据库?

时间:2014-09-13 13:52:36

标签: android database client send

我想使用android应用程序订购一些项目。我有一个xml文件,在这个xml文件中有一些编辑文本,输入一些文本我想从客户端购买的项目。然后点击提交按钮。然后将这些项目详细信息发送到客户端数据库。如何将这些购买详细信息发送到客户的数据库?

1 个答案:

答案 0 :(得分:2)

按照本教程(最好的一个),我添加了一些具体的代码

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

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

// url来创建新产品 //你必须创建php文件才能与服务器连接,而url就是一个例子

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

//编辑文字

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

//创建按钮

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

        }
    });
    }

/ **      *背景异步任务创建新产品      * * /

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();
        }

    }

//连接服务器的类

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;

    }
}