0

我对整个 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);
    }
    ?>

一个php请求脚本

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

1 回答 1

0

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

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

于 2013-08-24T07:20:00.940 回答