我正在使用我的Android应用程序一个php文件与mySql DB进行通信。但是无法更新它。它显示所需的fiels缺失,我认为我的PHP代码不正确。请指导我或分享一些简单的例子。 这是我的代码。
<?php
require_once __DIR__ . '/db_config.php';
$con=mysqli_connect($sql_login_host, $sql_login_user, $sql_login_pass, $sql_login_db);
if(!$con){
die("Connection Error: ".mysqli_error($con));
}
if (mysqli_connect_errno()) {
die("Connection failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
}
// check for required fields
//if ()
if ((isset($_POST['teamid']) && isset($_POST['memberid']) && isset($_POST['macaddress']) && isset($_POST['countryid'])))
{
$teamid = $_POST['teamid'];
$memberid = $_POST['memberid'];
$macaddress = $_POST['macaddress'];
$countryid = $_POST['countryid'];
/*$teamid = 4;
$memberid = 1;
$macaddress = "'878jjh-iiy'";
$countryid = 7;*/
$date1 = "'". date('Y-m-d H:i:s') ."'";
// mysql inserting a new row
$sql = "INSERT INTO vote(teamid, memberid, macaddress,countryid,votedon) VALUES($teamid, $memberid, $macaddress,$countryid,$date1)";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
// check if row inserted or not
if ($sql) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
的.java
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
//String name = inputName.getText().toString();
//String price = inputPrice.getText().toString();
//String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("teamid", "1"));
params.add(new BasicNameValuePair("macadddress", "---"));
params.add(new BasicNameValuePair("countryid", "1"));
params.add(new BasicNameValuePair("memberid", "1"));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
/*function get json from url
// by making HTTP POST or GET mehtod*/
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
日志
06-12 11:42:09.491: D/Create Response(7500): {"message":"Required field(s) is missing","success":0}
06-12 11:42:09.501: D/memalloc(7500): /dev/pmem: Unmapping buffer base:0x52ee4000 size:5828608 offset:5558272
06-12 11:42:09.511: D/memalloc(7500): /dev/pmem: Unmapping buffer base:0x5296f000 size:5558272 offset:5287936
06-12 11:42:29.821: D/memalloc(7500): /dev/pmem: Unmapping buffer base:0x54424000 size:14622720 offset:12533760
06-12 11:42:29.821: D/memalloc(7500): /dev/pmem: Unmapping buffer base:0x51e2a000 size:10166272 offset:8077312
new log.
now I am getting following error @Golu 06-12 13:40:57.261: E/AndroidRuntime(12080): FATAL EXCEPTION: AsyncTask #1
06-12 13:40:57.261: E/AndroidRuntime(12080): java.lang.RuntimeException: An error occured while executing doInBackground()
06-12 13:40:57.261: E/AndroidRuntime(12080): at android.os.AsyncTask$3.done(AsyncTask.java:278)
06-12 13:40:57.261: E/AndroidRuntime(12080): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-12 13:40:57.261: E/AndroidRuntime(12080): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-12 13:40:57.261: E/AndroidRuntime(12080): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-12 13:40:57.261: E/AndroidRuntime(12080): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-12 13:40:57.261: E/AndroidRuntime(12080): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-12 13:40:57.261: E/AndroidRuntime(12080): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-12 13:40:57.261: E/AndroidRuntime(12080): at java.lang.Thread.run(Thread.java:864)
06-12 13:40:57.261: E/AndroidRuntime(12080): Caused by: java.lang.NullPointerException
06-12 13:40:57.261: E/AndroidRuntime(12080): at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:101)
06-12 13:40:57.261: E/AndroidRuntime(12080): at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:1)
06-12 13:40:57.261: E/AndroidRuntime(12080): at android.os.AsyncTask$2.call(AsyncTask.java:264)
06-12 13:40:57.261: E/AndroidRuntime(12080): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
答案 0 :(得分:2)
您要发送到以下字段: -
params.add(new BasicNameValuePair("teamid", "1"));
params.add(new BasicNameValuePair("macadddress", "---"));
params.add(new BasicNameValuePair("countryid", "1"));
params.add(new BasicNameValuePair("memberid", "1"));
您的PHP需要如下: -
if ((isset($_POST['teamid']) && isset($_POST['memberid']) && isset($_POST['macaddress']) && isset($_POST['countryid'])))
错误的发生是因为: -
你在android "macadddress"
上使用它并使用php "macaddress".
请在php和android上使用相同的参数。