我正在尝试使用PHP从Android设备向服务器提供数据。我在logcat中收到以下错误:
03-29 17:08:56.706: D/Create Response(12702): {"message":"Required field(s) missing!","success":0}
我有三个相关的PHP文件: 1. db_config 2. db_connect 3. create_scan_record
来自create_Scan_record的代码:
<?php
/*
*Following code will create a new barcode scan record row
*All scan details are read from HTTP POST request
*/
//array for JSON response
$response = array();
//check for required fields
//There might be a synxtax error here
if(isset($_POST['scanFormat1']) && isset($_POST['scanContent1'])){
//&& isset($_POST['deviceID']) && isset($_POST['operatorID']) && isset($_POST['scanFormat']) && isset($_POST['scanFormat'])){
//global $con;
$scanFormat1 = $_POST['scanFormat1'];
$scanContent1 = $_POST['scanContent1'];
//$deviceID = $_POST['deviceID'];
//$operatorID = $_POST['operatorID'];
//include db connect class
//required_once __DIR__ . '/db_connect.php';
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/db_name/db_connect.php');
//connecting to db
$db = new DB_CONNECT();
//$con = new mysqli('localhost', 'username', 'password', 'db_name') or die(mysqli_error($con));
//mysql inserting a new row
$query = "INSERT INTO scan_data(scanFormat, scanContent) VALUES ('".$scanFormat1."','".$scanContent1."')";
$result = mysqli_query($con,$query);
//check whether row has been inserted
if($result){
//row successfully inserted
$response["success"] = 1;
$response["message"] = "Record successfully created.";
//echoing JSON response
echo json_encode($response);
} else {
//failed to insert row
$response["success"] = 0;
$response["message"] = "Error occurred!";
//echoing JSON response
echo json_encode($response);
}
} else {
//required field is missiing
$response["success"] = 0;
$response["message"] = "Required field(s) missing!";
//echoing JSON response
echo json_encode($response);
}
?>
db_connect.php中的代码。我认为这个问题在这里:
<?php
/*
*A class file to connect to database
*/
class DB_CONNECT{
//constructor
function __construct() {
//connect to database
$this ->connect();
}
//destructor
function __destruct() {
//closing db connection
$this ->close();
}
/*
*Function to connect to database
*/
function connect(){
//import database connection variables
// required_once __DIR__ . '/db_config.php';
define('__ROOT1__', dirname(dirname(__FILE__)));
require_once(__ROOT1__.'/db_name/db_config.php');
global $con;
//connecting to mysql database
$con = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE) or die(mysqli_error($con));
//selecting database
//$db = mysqli_select_db($con,DB_DATABASE) or die (mysqli_error()) or die(mysqli_error());
//returning connection cursor
return $con;
}
/*
*Function to close db connection
*/
function close(){
//closing db connection
mysqli_close($con);
}
}
?>
Android代码在这里:
package com.something.something;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
//Import Zxing classes
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
//Imported based on tutorial instruction
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class ScanBarcodeActivity extends ActionBarActivity {
// Added as per tutorial instruction
private Button scanBtn;
private Button updateBtn;
private TextView formatTxt, contentTxt;
String scanContent;
String scanFormat;
//Done on own
public Button btnUpdateDatabase;
jsonParser jsonParser = new jsonParser();
// Progress Dialog
private ProgressDialog pDialog;
private static String url_create_scan_record = "http://IP.IP.IP.IP/db_name/create_scan_record.php";
public String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_barcode);
// Added as per tutorial
scanBtn = (Button) findViewById(R.id.ScanBarcode);
updateBtn = (Button) findViewById(R.id.UpdateDatabaseButton);
formatTxt = (TextView) findViewById(R.id.scan_format);
contentTxt = (TextView) findViewById(R.id.scan_content);
updateBtn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View a){
//creating new record in background thread
UpdateDatabaseMethod(a);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.scan_barcode, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Added as per tutorial
public void scanBarcodeMethod(View v) {
if (v.getId() == R.id.ScanBarcode) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
// retrieve scan result
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
scanContent = scanningResult.getContents();
scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
//Log.d("format: ",scanFormat);
//Log.d("content: ",scanContent);
//---------------------------------------------------------------------------------------------------------------------
//Update database method
public void UpdateDatabaseMethod(View view){
new CreateNewRecord().execute();
}
//Background Async Task to create new record
class CreateNewRecord extends AsyncTask<String, String, String>{
//Show progress dialog before starting background thread
@Override
protected void onPreExecute(){
super.onPreExecute();
//Unsure of this line. Different activity in tutorial
// pDialog = new ProgressDialog(ScanBarcodeActivity.this);
// pDialog.setMessage("Creating Record...");
// pDialog.setIndeterminate(false);
// pDialog.setCancelable(true);
// pDialog.show();
}
//Creating Record
protected String doInBackground(String...args){
Log.d("scanFormat: --->> ",scanFormat);
Log.d("scanContent: --->> ",scanContent);
String scanFormat1 = scanFormat.toString();
String scanContent1 = scanContent.toString();
// String DeviceID = deviceIDView.getText().toString();
// String OperatorID = operatorIDView.getText().toString();
Log.d("scanFormat1: ",scanFormat1);
Log.d("scanContent1: ",scanContent1);
//Building Parameters. Need to check that the order of parameters is correct
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.d("got here ---> 1", "new ArrayList");
params.add(new BasicNameValuePair("scanFormat1", scanFormat1));
Log.d("got here ---> 2", "NameValuePair-scanFormat");
params.add(new BasicNameValuePair("scanContent1", scanContent1));
Log.d("got here ---> 3", "NameValuePair-scanContent");
// params.add(new BasicNameValuePair("deviceIDView", DeviceID));
// params.add(new BasicNameValuePair("operatorIDView", OperatorID));
//getting JSON object
//Note that create record url accepts POST method
JSONObject json = com.somename.somename.jsonParser.makeHttpRequest(url_create_scan_record, "POST", params);
// if json.isNull(json)
// {}
Log.d("got here ---> 4", "json created");
//Check log cat for response
Log.d("Create Response",json.toString());
Log.d("got here ---> 5", "json.toString() executed");
//Check for success tag
try{
String TAG_SUCCESS= "success";
int success = json.getInt(TAG_SUCCESS);
if (success==1){
//Successfully created record
//Unsure of this line. Different activity in tutorial
// Intent i = new Intent(getApplicationContext(), CreateNewRecord.class);
// startActivity(i);
Context context = getApplicationContext();
CharSequence text = "Success";
int duration = Toast.LENGTH_SHORT;
// Toast toast = Toast.makeText(context, text, duration);
// toast.show();
//closing this screen
// finish();
} else {
//failed to create record
}
} catch (JSONException e){
e.printStackTrace();
}
return null;
}
/**Dismiss progress dialog after completing background task
**/
protected void onPostExecute(String file_url){
//dismiss the dialog once done
// pDialog.dismiss();
}
}
}