我有一个Android应用程序,我正在编程将数据数组发布到本地服务器中的php文件。数据格式如下。 Name1->数量1 Name2-> Qunatity2 我试图将其作为json数组发送,但问题是每当我发送数据时,它表明它成功发布了这些数据。但是,由于从Android应用程序发送的数据,我无法看到数据库的任何更改。如果有人指导或解决我的这个问题,我将感激不尽。请帮助我。
Bellow是我用来发送和接收数据的类
这是发送数据的类
public class Thirdscreen extends Activity {
private static String url = "http://10.0.2.2/bootstrap-dist/postingdata.php";
public ArrayList<QantityModelProduct> quantitymodel=new ArrayList<QantityModelProduct>();
// Progress Dialog
private ProgressDialog pDialog;
// Json parser object
JSONParser jsonParser = new JSONParser();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdscreen);
QantityModelProduct qmp;
TextView showCartContent = (TextView) findViewById(R.id.showCart);
TextView showCarttotal = (TextView) findViewById(R.id.showtotal);
Button btn = (Button) findViewById(R.id.subtractQuantity);
final Controller aController = (Controller) getApplicationContext();
int cartSize = aController.getCart().getCartSize();
String showString = "";
int total = 0;
for (int i = 0; i < cartSize; i++) {
String pName = aController.getCart().getProducts(i)
.getProductName();
int pPrice = aController.getCart().getProducts(i).getProductPrice();
int quantity = aController.getCart().getProducts(i)
.getProductQuantity();
int dataProQuantityStore = aController.getCart()
.getProducts(i).getDatabaseProductQuantity();
String pDisc = aController.getCart().getProducts(i)
.getProductDesc();
total = total + (pPrice * quantity);
showString += "\n\nProduct Name : " + pName + "\n" + "Price : "
+ pPrice + "\t" + "Quantity: " + quantity + "\n"
+ "Discription : " + pDisc + ""
+ "\n -----------------------------------";
//databaseQuantity-Current quantity
int finalVal = dataProQuantityStore - quantity;
String finalstringValue=""+finalVal;
qmp=new QantityModelProduct(pName,finalstringValue);
quantitymodel.add(qmp);
}
showCarttotal.setText("Your Total is: " + total + "Tk");
showCartContent.setText(showString);
final int productSize=quantitymodel.size();
Toast.makeText(getApplicationContext(),"Array size: "+productSize, Toast.LENGTH_SHORT).show();
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
new getQuantity().execute();
}
});
}
class getQuantity extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Thirdscreen.this);
pDialog.setMessage("Processing your request..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
JSONArray jsonArray = new JSONArray();
for (int i=0; i < quantitymodel.size(); i++) {
jsonArray.put(quantitymodel.get(i).getJSONObject());
}
jsonParser.getandpostJSONFromUrl(url, "POST",jsonArray);
return null;
}
@Override
protected void onPostExecute(String file_url) {
final Controller aController = (Controller) getApplicationContext();
// dismiss the dialog once done
pDialog.dismiss();
aController.getCart().clearCart();
aController.getProductsArraylist().clear();
Toast.makeText(getBaseContext(), "I am in second loop", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getBaseContext(), FirstScreen.class);
finish();
startActivity(i);
}
}
}
public class QantityModelProduct {
private String ProductName;
private String ProductQuantity;
public QantityModelProduct(String productName, String productQuantity) {
ProductName = productName;
ProductQuantity = productQuantity;
}
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Name", ProductName);
obj.put("Quantity", ProductQuantity);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}
以下是Json Parser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {
// Making HTTP request
try {
// defaultHttpClient
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(name.toString()));
HttpResponse httpResponse = httpClient.execute(httpPost);
httpPost.setHeader("jsonArray",json.toString());
HttpEntity httpEntity = httpResponse.getEntity();
int response = httpResponse.getStatusLine().getStatusCode();
is = httpEntity.getContent();
Log.e("posting Status", "Post status: " + response);
}
if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (method == "POST") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
} catch (Exception e) {
Log.e("Buffer error", "Buffer error" + e);
}
} else if (method == "GET") {
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;
}
}
最后是假设接收这些数据的php文件。
?php
define('DB_NAME', 'sshop');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$link){
die('could not connect: '.msql_error());
}
$db_selected=mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can not use '.DB_NAME.':'.mysql_error());
}
if (isset($_POST['jsonArray'])){
$jArray = json_decode($jsonArray,true);
foreach ($jArray['jsonArray'] as $obj) {
$ProductName = $obj['Name']; //String
$ProductQuantity= $obj['Quantity'];
$sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";
echo $ProductName." ".$ProductQuantity;
}
}else {
echo 'empty';
}
?>
答案 0 :(得分:0)
首先,您不应该使用==
比较字符串试试这个!
if (method.equals("POST"))
接下来,要调试,通过发送与响应相同的请求,查看您通过Android应用程序向PHP Web服务发送的数据。因此,您确切地知道您是否正在发送数据。
如果上述步骤正常,则表示问题出在PHP端。使用Chrome中的http://hurl.it或Postman客户端通过浏览器发布帖子,然后调试PHP代码。查看是否正在插入数据。
这可以解决您的问题。
尼西