2016-09-20 78 views
0

我想從我的android工作室應用程序發送數據到MySQL的PHP​​服務器,這裏是我的代碼,該程序可以運行,但我的服務器無法從我的應用程序接收數據。我的編碼在某個地方出錯了嗎?從Android工作室應用程序發送數據到服務器

我的Android應用程序的工作室編碼

package com.sp.toilert; 

import android.app.PendingIntent; 
import android.bluetooth.BluetoothAdapter; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.nfc.NdefMessage; 
import android.nfc.NdefRecord; 
import android.nfc.NfcAdapter; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Parcelable; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 
import android.widget.TextView; 
import android.widget.Toast; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 

import java.io.IOException; 
import java.io.UnsupportedEncodingException; 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Calendar; 
import java.util.List; 


public class MainActivity extends AppCompatActivity { 

NfcAdapter nfcAdapter; 
TextView txtTagContent; 
private BluetoothAdapter myBluetooth = null; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(com.sp.toilert.R.layout.activity_main); 

    checkBTState(); 
    nfcAdapter = NfcAdapter.getDefaultAdapter(this); 
    txtTagContent = (TextView) findViewById(R.id.txtTagContent); 

} 

public void buttonOnClick(View v) { 

new SubmitData().execute(); //do something when button clicked 

} 

public class SubmitData extends AsyncTask<String, String, String> { 

    @Override 
    protected String doInBackground(String... strings) { 

     try { 

      postData(); 

     } catch (NullPointerException e) { 
      e.printStackTrace(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    //this function is the main thing that will upload the data to the server 
    public void postData() { 
     // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://172.22.47.245/notthatdirty.php"); 

     try { 
      // these are all the fields that will be submitted 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      //nameValuePairs.add(new BasicNameValuePair("MyName","MyValue")); 
      nameValuePairs.add(new BasicNameValuePair("cubicle_ID", "100003")); //send data to server 
      nameValuePairs.add(new BasicNameValuePair("issue", "dirty")); //send data to server 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 

     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 
    } 
} 

我的服務器編碼

<h1>WELCOME TO TOILERT</h1></P> 

<?php 
$servername = "localhost"; 
$username = "toilert"; 
$password = "toilert"; 
$dbname = "cleaning_db"; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 

// Check connection 
if ($conn->connect_error) { 
die("Connection failed: " . $conn->connect_error); 
} 
echo "Connected successfully"; 

//http://localhost/toilet-backend/backend.php?dirty=1&cubicleID=10003 
//GET the data from android 
/* 
$dirty = $_GET["dirty"]; //1 for true . 0 for false 
$emergency = $_GET["emergency"]; //1 for true . 0 for false 
$faulty = $_GET["faulty"]; //1 for true . 0 for false 
*/ 

$issue = htmlspecialchars($_GET["issue"]); // Sanitize input with   htmlspecialchars 
$cubicleID = $_GET['cubicleID']; 

//Check if the request has been sent before 
//ensure no duplicate toilet data 
$query = "SELECT * FROM cleaner_request WHERE cubicle_id = $cubicleID"; 
$result = $conn->query($query); 

if ($result->num_rows > 0) { 
$json = array("status" => 200, "msg" => "Complaint has already been   created"); 
echo json_encode($json); 
} else { 
switch ($issue) { 
    case "dirty": 
    case "emergency": 
    case "faulty": 
     $query = "INSERT INTO cleaner_request (cubicle_id, $issue) VALUES  ('$cubicleID', '1')"; 
     break; 
    default: 
     $error = "Invalid status"; 
} 
if (empty($error)) { 
    $result = $conn->query($query); 
    echo "Data written to Database"; 
    $json = array("status" => 200, "msg" => "Complaint has been successfully created"); 
    } else { 
    echo "error" ; 
    //$json = array("status" => 418, "msg" => $error); 

} 
echo json_encode($json); 
/* Ben commented this out. Because code 
if ($dirty == 1) { //dirty 
    $query = "INSERT INTO cleaner_request (cubicle_id,dirty) VALUES ('$cubicleID','$dirty')"; 
    $result = $conn->query($query); 
    $json = array("status" => 200, "msg" => "Complaint has been successfully created"); 
    echo json_encode($json); 
    } else if ($dirty == 0) { //clean 

    } 
    */ 
    //check require location 
    require 'C:/xampp/htdocs/toilet-backend/twilio-php-master/Services/Twilio.php'; 
$AccountSid = "AC52a80f076cca00c9547fdfd17bf4fbbb"; 
$AuthToken = "b145c2d4f7b722fe79cbe38f3009afcc"; 

// Step 3: instantiate a new Twilio Rest Client 
$client = new Services_Twilio($AccountSid, $AuthToken); 
$client->account->messages->create(array(
    'To' => "+65 9067 9919", 
    'From' => "+15672420325", 
    'Body' => "Greetings, please clean up Cubicle 100 001 and 100 004. Thank you. This service is brought to you by Toilert.", 
)); 
mysqli_close($conn); //$conn->close(); 
} 
?> 

A picture of the server side

回答

0

https://developer.android.com/training/volley/index.html

停止強調,並使用排它爲我工作得很好。

Volley是一個HTTP庫,可以使Android應用程序的聯網變得更簡單,最重要的是,更快。 Volley通過開放的AOSP存儲庫提供。

Volley提供以下好處:

自動調度網絡請求。 多個併發網絡連接。 標準HTTP緩存一致性的透明磁盤和內存響應緩存。 支持請求優先級。 取消請求API。您可以取消單個請求,也可以設置要取消的請求的範圍或範圍。 易於定製,例如,重試和退避。 強大的排序使得使用從網絡異步獲取的數據可以輕鬆正確地填充您的UI。 調試和跟蹤工具。

相關問題