我在用 php 将 arraylist 值存储到 mysql 数据库时遇到了一些问题。这是我创建的一些代码。
首先,我有一些类来存储名为 Constant.java 的变量:
public class Constant {
public static final String FIRST_COLUMN = "First";
public static final String SECOND_COLUMN = "Second";
public static final String THIRD_COLUMN = "Third";
public static final String FOURTH_COLUMN = "Fourth";
}
其次,我已经像这样将该类导入到 MainActivity.java 中:
import static com.testing.informationsystem.Constant.FIRST_COLUMN;
import static com.testing.informationsystem.Constant.SECOND_COLUMN;
import static com.testing.informationsystem.Constant.THIRD_COLUMN;
import static com.testing.informationsystem.Constant.FOURTH_COLUMN;
第三,我通过这种方式将我的值存储到arraylist:
btnInsert = (Button) findViewById(R.id.btnInsert);
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
orderValue = txtOrderValue.getText().toString();
price = txtPrice.getText().toString();
valueSpinner = spnProductFocus.getSelectedItem().toString();
HashMap temp = new HashMap();
if(orderValue.equalsIgnoreCase("")){
orderValue = "0";
}
if(price.equalsIgnoreCase("")){
price = "1000";
}
double count = Double.parseDouble(orderValue) + Double.parseDouble(price);
total = String.valueOf(count);
if(count.equalsIgnoreCase("")){
count = "0";
}
temp.put(FIRST_COLUMN, valueSpinner);
temp.put(SECOND_COLUMN, orderValue);
temp.put(THIRD_COLUMN, price);
temp.put(FOURTH_COLUMN, total);
list.add(temp);
}
});
好的,现在我的数组列表包含我从按钮中保存的值。现在我将通过 HTTPOST 将其发送到 PHP 并将其存储到 mysql。这是我将其发布到 PHP 的代码。
void saveOrder(){
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://dcmodular.com/saktisetia/mobile/order.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
--nameValuePairs.add(new BasicNameValuePair(arraylist));--
----this is my problem about how to post it to PHP---
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpclient.execute(httppost);
Log.d("Value : ", response.toString());
HttpEntity entity=response.getEntity();
String feedback = EntityUtils.toString(entity).trim();
Log.d("Feedback : ", feedback);
}
最后,这是我自己的 php 文件,用于将其存储到 mysql 数据库中:
<?php
include('connection.php');
--receive arraylist from httppost--
$query = "insert into order(value1) values(value1)";
$execute = mysql_query($query) or die(mysql_error());
if($execute){
echo "saved";
}else{
echo "failed";
}
?>
这是我的代码和我的问题,如何将数组列表发布到 PHP。之前感谢您的帮助。
最佳答案
不再支持使用 HttpUrlConnection 作为 Http 默认客户端。 试试这个
public JSONObject function(String value_to_post, String value_to_post,....){
try {
HashMap<String, String> params = new HashMap<>();
params.put("your_database_field", value_to_post);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
your_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
从您的 Activity 中调用此函数
关于android - 如何将 ArrayList 值存储到 MySQL 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35693383/