Php 引导Android应用程序在服务器上检索和更新数据

Php 引导Android应用程序在服务器上检索和更新数据,php,android,http-post,httprequest,Php,Android,Http Post,Httprequest,我对整个Android环境比较陌生,所以请指导我 我计划实现的是让我的android应用程序通过php脚本接收数据并发送到服务器。基本上是和服务器对话。 到目前为止,我创建的是php连接脚本、更新脚本、检索脚本和Android函数 现在我面临的问题是,我不确定Android编码应该放在什么位置,以让我实现推/拉请求 <?php /* * Following code will update a product information * A product is identified

我对整个Android环境比较陌生,所以请指导我

我计划实现的是让我的android应用程序通过php脚本接收数据并发送到服务器。基本上是和服务器对话。 到目前为止,我创建的是php连接脚本、更新脚本、检索脚本和Android函数

现在我面临的问题是,我不确定Android编码应该放在什么位置,以让我实现推/拉请求

<?php

/*
 * Following code will update a product information
 * A product is identified by product id (pid)
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['WifiMacAddress']) && isset($_POST['WifiSSID']) && isset($_POST['WifiLatitude']) && isset($_POST['WifiLongtitude']) && isset($_POST['WifiLocation'])) {

    $WifiMacAddress = $_POST['WifiMacAddress'];
    $WifiSSID = $_POST['WifiSSID'];
    $WifiLatitude = $_POST['WifiLatitude'];
    $WifiLongtitude = $_POST['WifiLongtitude'];
    $WifiLocation = $_POST['WifiLocation'];



     // include db connect class
        require_once __DIR__ . '/db_connect.php';

        // connecting to db
        $db = new DB_CONNECT();

        // mysql update row with matched pid
        $result = mysql_query("UPDATE Wifi SET WifiSSID = '$WifiSSID', WifiLatitude = '$WifiLatitude', WifiLongtitude = '$WifiLongtitude' , WifiLocation = '$WifiLocation' WHERE WifiMacAddress = $WifiMacAddress");

        // check if row inserted or not
        if ($result) {
            // successfully updated
            $response["success"] = 1;
            $response["message"] = "Product successfully updated.";

            // echoing JSON response
            echo json_encode($response);
        } else {

        }
    } else {
        // required field is missing
        $response["success"] = 0;
        $response["message"] = "Required field(s) is missing";

        // echoing JSON response
        echo json_encode($response);
    }
    ?>

在这种情况下,我基本上使用
PhoneGap
来构建这样的Android应用程序。使用jQuery Ajax,您的Android应用程序(
使用phonegap构建)可以轻松地与web服务器交互。以及从web服务器接收数据


您可以在服务器中使用PHP,并将输出格式编码为
json
,然后通过jQuery您可以轻松处理json数据并使用应用程序。我认为这将是最简单的解决方案。

您只需通过json、xml等web服务从服务器获取数据。
    <?php  

    #Ensure that the client has provided a value for "FirstNameToSearch"  
    if (isset($_POST["FirstNameToSearch"]) && $_POST["FirstNameToSearch"] != ""){  

        #Setup variables  
        $firstname = $_POST["FirstNameToSearch"];  

        #Connect to Database  
        $con = mysqli_connect("localhost","root","", "unnamedwifistrengthvisualisation");  

        #Check connection  
        if (mysqli_connect_errno()) {  
            echo 'Database connection error: ' . mysqli_connect_error();  
            exit();  
        }  

        #Escape special characters to avoid SQL injection attacks  
        $firstname = mysqli_real_escape_string($con, $firstname);  

        #Query the database to get the user details.  
        $userdetails = mysqli_query($con, "SELECT * FROM wifi WHERE WifiMacAddress = '$WifiMacAddress'");  

        #If no data was returned, check for any SQL errors  
        if (!$userdetails) {  
            echo 'Could not run query: ' . mysqli_error($con);  
            exit;  
        }  

        #Get the first row of the results  
        $row = mysqli_fetch_row($userdetails);  

        #Build the result array (Assign keys to the values)  
        $result_data = array(  
            'WifiMacAddress' => $row[0],  
            'WifiSSID' => $row[1],  
            'WifiLatitude' => $row[2],  
            'WifiLongtitude' => $row[3],  
            'WifiLocation' => $row[4],  
            );  

        #Output the JSON data  
        echo json_encode($result_data);   
    }else{  
        echo "Could not complete query. Missing parameter";   
    }  
?>
            btn_loc.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub  
                   mlocal.getlocation();
                   txtlocation.setText(mlocal.mCurrentLocation.getLatitude() + "," + mlocal.mCurrentLocation.getLongitude());
                   mwifi.scanWifi();
                   mwifi.getwifilist();            
                   System.out.println("111");
            }
            });


            btn_ser.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                      mlocal.getlocation();

                      if( ((Button)v).getText().equals("Start Location Service")){
                           ((Button) v).setText("Stop Location Service");                          
                           mlocal.getupdate();
                           System.out.println("222");
                       }
                       else{
                           mlocal.removeupdate();
                           ((Button) v).setText("Start Location Service");
                       }
                }
                });         

            bnt_aploc.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) 
                {

                }
            });     

     }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected Boolean doInBackground(String... arg0) {

        try{

    //Creating and Executing a HTTP POST in Java
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("FirstNameToSearch", strNameToSearch));


    //Create the HTTP request
    HttpParams httpParameters = new BasicHttpParams();

    //Setup timeouts
    HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
    HttpConnectionParams.setSoTimeout(httpParameters, 15000);           

    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost("http://192.168.1.112/clientservertest/login.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    //The following code executes the POST, gets the result and converts it to a string:
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    String result = EntityUtils.toString(entity);

    //the following code creates a JSON object from the result string and extracts our data
    // Create a JSON object from the request response
    JSONObject jsonObject = new JSONObject(result);

    //Retrieve the data from the JSON object
    strWifiMacAddress = jsonObject.getString("WifiMacAddress");
    strWifiSSID = jsonObject.getString("WifiSSID");
    strWifiLatitude = jsonObject.getString("WifiLatitude");
    strWifiLongtitude = jsonObject.getString("WifiLongtitude");
    strWifiLocation = jsonObject.getString("WifiLocation");         

}catch (Exception e){
    Log.e("ClientServerDemo", "Error:", e);
    exception = e;
}

return true;
}

    @Override
    protected void onPostExecute(Boolean valid){
        //Update the UI
        textViewWifiMacAddress.setText("First Name: " + strWifiMacAddress);
        textViewWifiSSID.setText("WifiSSID: " + strWifiSSID);
        textViewWifiLatitude.setText("WifiLatitude: " + strWifiLatitude);
        textViewWifiLongtitude.setText("WifiLongtitude: " + strWifiLongtitude);
        textViewWifiLocation.setText("WifiLocation: " + strWifiLocation);
        buttonGetData.setEnabled(true);

        if(exception != null){
            Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
        }
    }