0
我對整個Android環境相對較新,所以請引導我一起。Geeting 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();
}
}
你必須通過網絡服務獲取數據,比如json,xml等。 – Yugesh