
本教程旨在指导Android开发者如何将从日历选择器获取的日期ArrayList数据,通过PHP脚本发送并存储到MySQL数据库表中。我们将详细介绍数据结构定义、数据处理以及异步任务的实现,帮助初学者理解Android与PHP之间的数据交互。
1. 数据结构定义:Profile类
为了方便数据的传输和存储,首先需要定义一个与MySQL数据库表结构相对应的Java类。这个类将作为数据载体,封装需要传输的数据。
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. 数据处理:从ArrayList到Profile对象列表
假设我们有一个ArrayList
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DateConverter {
public static List<profile> convertDatesToProfiles(ArrayList<date> dates) {
List<profile> profileList = new ArrayList();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
for (int i = 0; i <p>在这个例子中,我们将日期格式化为字符串,并将其设置为Profile对象的name属性。你可以根据实际需求修改Profile对象的属性设置。</p><h3>3. 通过AsyncTask发送数据</h3><p>为了避免阻塞主线程,我们使用AsyncTask来执行网络请求。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2500" title="度加AI"><img
src="https://img.php.cn/upload/manual/000/969/633/6a61700fe297c535.jpg" alt="度加AI" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/gongju/2500" title="度加AI" class="overflowclass">度加AI</a>
<p class="overflowclass">度加AI官网入口,百度官方 AIGC 创作平台,支持 AI 成片、AI 生文、数字人、声音克隆、配音字幕与智能剪辑等在线创作能力。</p>
</div>
<a rel="nofollow" href="/xiazai/gongju/2500" title="度加AI" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><pre class="brush:php;toolbar:false;">import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import com.google.gson.Gson;
public class SendDataTask extends AsyncTask<list>, Void, String> {
private static final String PHP_URL = "YOUR_PHP_SCRIPT_URL"; // 替换为你的PHP脚本URL
@Override
protected String doInBackground(List<profile>... lists) {
List<profile> profileList = lists[0];
Gson gson = new Gson();
String jsonString = gson.toJson(profileList); // 将List<profile>转换为JSON字符串
try {
URL url = new URL(PHP_URL + "?data=" + jsonString); // 将JSON字符串作为参数传递给PHP
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // 或者 POST
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
return result.toString();
} catch (Exception e) {
e.printStackTrace();
return "Error: " + e.getMessage();
}
}
@Override
protected void onPostExecute(String result) {
// 处理PHP返回的结果
System.out.println("PHP Response: " + result);
}
}</profile></profile></profile></list>使用示例:
ArrayList<date> selectedDates = (ArrayList<date>) calendarPickerView.getSelectedDates(); List<profile> profileList = DateConverter.convertDatesToProfiles(selectedDates); new SendDataTask().execute(profileList);</profile></date></date>
注意事项:
- 替换YOUR_PHP_SCRIPT_URL为你的PHP脚本的URL。
- 使用Gson库将List
转换为JSON字符串,需要在build.gradle文件中添加依赖:implementation 'com.google.code.gson:gson:2.8.8' (版本号可能需要更新). - 根据实际情况选择GET或POST请求方式。
- 确保在AndroidManifest.xml文件中添加网络权限:
android:name="android.permission.INTERNET" />
4. PHP脚本 (示例)
以下是一个简单的PHP脚本,用于接收JSON数据并将其插入到MySQL数据库中。
<?php $servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = $_GET["data"]; // 接收JSON数据
$profiles = json_decode($data, true); // 解码JSON数据
foreach ($profiles as $profile) {
$id = $profile["id"];
$name = $profile["name"];
$sql = "INSERT INTO your_table (id, name) VALUES ('$id', '$name')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>注意事项:
- 替换your_username,your_password,your_dbname和your_table为你的MySQL数据库的实际信息。
- 确保MySQL数据库表结构与Profile类的成员变量相匹配。
- 为了安全起见,应该对接收到的数据进行验证和转义,防止SQL注入攻击。
- 可以使用POST方法传递数据,并使用$_POST["data"]来接收数据。
5. 总结
本教程提供了一个将Android ArrayList数据发送到MySQL数据库的完整示例。通过定义数据结构、数据转换和使用异步任务,可以有效地实现Android与PHP之间的数据交互。请务必根据你的实际需求修改代码,并注意安全性。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










