
本文档旨在指导 Android 开发者如何将从 Timesquare CalendarPicker 中获取的日期 ArrayList 数据,通过 PHP 脚本传输并存储到 MySQL 数据库中。我们将详细介绍数据模型的构建、数据封装、以及如何通过循环遍历 ArrayList 将数据发送到服务器。 适用于Android和PHP初学者。
将 ArrayList 中的数据发送到 MySQL 数据库是一个常见的需求,尤其是在处理日期、时间等数据时。以下步骤将详细介绍如何实现这一目标。
首先,需要在 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 数据库表中的列名和数据类型相匹配。
如果数据以 JSON 字符串的形式存在,可以使用 JSONObject 和 JSONArray 来解析 JSON 数据并填充 Profile 对象。
private List<Profile> processResponse(String response){
List<Profile> 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;
}注意事项:
如果数据已经存在于 ArrayList 中,可以使用 for-each 循环遍历 ArrayList 并填充 Profile 对象。
ArrayList<String> namesList = new ArrayList<>(Arrays.asList( "alex", "brian", "charles") );
List<Profile> list = new ArrayList<>();
int iNum = 0;
for(String name : namesList)
{
iNum++;
Profile myProfile = new Profile();
myProfile.setId(iNum);
myProfile.setName(name);
list.add(myProfile);
}注意事项:
为了避免阻塞主线程,可以使用 AsyncTask 在后台线程中执行网络操作。
private class SendDataTask extends AsyncTask<List<Profile>, Void, Boolean> {
@Override
protected Boolean doInBackground(List<Profile>... lists) {
List<Profile> 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();
}
}
}注意事项:
在服务器端,需要创建一个 PHP 脚本来接收 Android 应用发送的数据并将其插入到 MySQL 数据库中。
<?php
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->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 . "<br>" . $conn->error;
}
// Close connection
$conn->close();
?>注意事项:
最后,在 Android 应用中,需要创建 Profile 对象的列表并调用 SendDataTask 来发送数据。
public void publishContact(View v) {
List<Profile> list = new ArrayList<>();
// Fill the list with Profile objects (e.g., from grantUp() method)
ArrayList<String> 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 注入攻击。 另外,要处理网络连接和数据库操作期间可能发生的异常。
以上就是将 ArrayList 数据发送到 MySQL 表的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号