
本文档旨在指导 Android 开发者如何将从 Timesquare CalendarPicker 中获取的日期 ArrayList 数据,通过 PHP 脚本传输并存储到 MySQL 数据库中。我们将详细介绍数据模型的构建、数据封装、以及如何通过循环遍历 ArrayList 将数据发送到服务器。 适用于Android和PHP初学者。
将 ArrayList 中的数据发送到 MySQL 数据库是一个常见的需求,尤其是在处理日期、时间等数据时。以下步骤将详细介绍如何实现这一目标。
1. 定义数据模型 (Profile 类)
首先,需要在 Android 应用中定义一个数据模型类,该类将用于表示要存储到 MySQL 数据库中的数据。这个类应该包含与数据库表中列相对应的属性。
public class Profile {
private Integer id;
private String id_card;
private String name;
private String phone;
private String address;
public Profile() {
super();
}
public Profile(Integer id, String id_card, String name, String phone,
String address) {
super();
this.id = id;
this.id_card = id_card;
this.name = name;
this.phone = phone;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getIdCard() {
return id_card;
}
public void setIdCard(String id_card) {
this.id_card = id_card;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}注意: 确保 Profile 类中的属性与 MySQL 数据库表中的列名和数据类型相匹配。
2. 从 JSON 字符串填充数据
如果数据以 JSON 字符串的形式存在,可以使用 JSONObject 和 JSONArray 来解析 JSON 数据并填充 Profile 对象。
private ListprocessResponse(String response){ List myProfileList = new ArrayList<>(); try { JSONObject jsonObj = new JSONObject(response); JSONArray jsonArray = jsonObj.getJSONArray("params_name1"); for(int i = 0; i < jsonArray.length(); i++){ JSONObject obj = jsonArray.getJSONObject(i); Profile myProfile = new Profile(); myProfile.setId(obj.getInt("id")); myProfile.setIdCard(obj.getString("id_card")); myProfile.setName(obj.getString("full_name")); myProfile.setPhone( obj.getString("phone_num") ); myProfile.setAddress(obj.getString("adress1")); myProfileList.add(myProfile); } } catch (JSONException e) { e.printStackTrace(); // 建议使用更完善的错误处理机制 } return myProfileList; }
注意事项:
芝麻乐开源众筹系统采用php+mysql开发,基于MVC开发,适用于各类互联网金融公司使用,程序具备模板分离技术,您可以根据您的需要进行应用扩展来达到更加强大功能。前端使用pintuer、jquery、layer等....系统易于使用和扩展简单的安装和升级向导多重业务逻辑判断,预防出现bug后台图表数据方式,一目了然后台包含但不限于以下功能:用户认证角色管理节点管理管理员管理上传配置支付配置短信平
- params_name1 应替换为 JSON 字符串中包含 Profile 对象数组的键。
- 确保 JSON 对象的键与 Profile 类的属性名匹配。
- 使用 try-catch 块来处理 JSONException 异常。
- 建议使用更完善的错误处理机制,例如记录日志或向用户显示错误消息。
3. 从 ArrayList 填充数据
如果数据已经存在于 ArrayList 中,可以使用 for-each 循环遍历 ArrayList 并填充 Profile 对象。
ArrayListnamesList = new ArrayList<>(Arrays.asList( "alex", "brian", "charles") ); List list = new ArrayList<>(); int iNum = 0; for(String name : namesList) { iNum++; Profile myProfile = new Profile(); myProfile.setId(iNum); myProfile.setName(name); list.add(myProfile); }
注意事项:
- 根据 ArrayList 中数据的类型和结构,相应地设置 Profile 对象的属性。
- 在循环中创建新的 Profile 对象,以避免所有列表元素引用同一个对象。
4. 通过 AsyncTask 发送数据
为了避免阻塞主线程,可以使用 AsyncTask 在后台线程中执行网络操作。
private class SendDataTask extends AsyncTask, Void, Boolean> { @Override protected Boolean doInBackground(List
... lists) { List profileList = lists[0]; // TODO: Implement your network logic here to send data to PHP script. // You can use HttpURLConnection or libraries like Retrofit or Volley. // Example using HttpURLConnection (requires proper exception handling): for (Profile profile : profileList) { try { URL url = new URL("http://your-server.com/your-php-script.php"); // Replace with your PHP script URL HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); // Prepare data to send (e.g., using URLEncodedFormEntity) String postData = "id=" + profile.getId() + "&name=" + profile.getName() + "&address=" + profile.getAddress(); // And other fields OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(postData); writer.flush(); writer.close(); os.close(); int responseCode = connection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { // Handle error (e.g., log the error) Log.e("SendDataTask", "HTTP error code: " + responseCode); return false; } // Read the response from the server (optional) BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); connection.disconnect(); Log.d("SendDataTask", "Server response: " + response.toString()); } catch (Exception e) { // Handle exceptions (e.g., network errors) Log.e("SendDataTask", "Exception during network request: " + e.getMessage(), e); return false; } } return true; // Indicate success } @Override protected void onPostExecute(Boolean success) { if (success) { // Update UI to indicate success Toast.makeText(getApplicationContext(), "Data sent successfully!", Toast.LENGTH_SHORT).show(); } else { // Update UI to indicate failure Toast.makeText(getApplicationContext(), "Failed to send data.", Toast.LENGTH_SHORT).show(); } } }
注意事项:
- 替换 "http://your-server.com/your-php-script.php" 为实际的 PHP 脚本 URL。
- 根据 Profile 类的属性和数据库表中的列,准备要发送的数据。
- 使用 URLEncodedFormEntity 或其他适当的方法来编码数据。
- 在 onPostExecute 方法中更新 UI,以指示数据发送成功或失败。
- 考虑使用更高级的网络库,例如 Retrofit 或 Volley,以简化网络操作。
5. PHP 脚本
在服务器端,需要创建一个 PHP 脚本来接收 Android 应用发送的数据并将其插入到 MySQL 数据库中。
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get data from POST request
$id = $_POST["id"];
$name = $_POST["name"];
$address = $_POST["address"];
// Prepare SQL statement
$sql = "INSERT INTO your_table (id, name, address) VALUES ('$id', '$name', '$address')";
// Execute SQL statement
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
// Close connection
$conn->close();
?>注意事项:
- 替换 "localhost", "your_username", "your_password" 和 "your_database" 为实际的数据库凭据。
- 替换 "your_table" 为实际的数据库表名。
- 使用 $_POST 或 $_GET 来获取 Android 应用发送的数据。
- 使用预处理语句来防止 SQL 注入攻击。
- 在生产环境中,应该对输入数据进行验证和清理,以确保数据的安全性和完整性。
- 使用适当的错误处理机制,例如记录日志或返回错误消息。
6. 调用 AsyncTask
最后,在 Android 应用中,需要创建 Profile 对象的列表并调用 SendDataTask 来发送数据。
public void publishContact(View v) {
List list = new ArrayList<>();
// Fill the list with Profile objects (e.g., from grantUp() method)
ArrayList namesList = new ArrayList<>(Arrays.asList( "alex", "brian", "charles") );
int iNum = 0;
for(String name : namesList)
{
iNum++;
Profile myProfile = new Profile();
myProfile.setId(iNum);
myProfile.setName(name);
list.add(myProfile);
}
// Execute the AsyncTask to send the data
new SendDataTask().execute(list);
} 总结:
通过以上步骤,你可以将 ArrayList 中的数据发送到 MySQL 数据库。请确保仔细检查代码,并根据实际情况进行调整。 特别注意安全性,例如使用预处理语句来防止 SQL 注入攻击。 另外,要处理网络连接和数据库操作期间可能发生的异常。









