使用Volley将数据从MySQL数据库添加到TableLayout的步骤如下:
dependencies {
implementation 'com.android.volley:volley:1.2.1'
}
<TableLayout
android:id="@+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- Add table rows dynamically -->
</TableLayout>
<Button
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Data" />
TableLayout tableLayout = findViewById(R.id.tableLayout);
Button addButton = findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Add data to TableLayout
fetchDataFromMySQL();
}
});
private void fetchDataFromMySQL() {
String url = "YOUR_PHP_SCRIPT_URL"; // 替换为你的PHP脚本URL
// 创建一个StringRequest对象
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
// 遍历JSON数组并添加数据到TableLayout
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String data1 = jsonObject.getString("data1");
String data2 = jsonObject.getString("data2");
// 创建一个新的TableRow
TableRow tableRow = new TableRow(MainActivity.this);
// 创建TextView并设置数据
TextView textView1 = new TextView(MainActivity.this);
textView1.setText(data1);
TextView textView2 = new TextView(MainActivity.this);
textView2.setText(data2);
// 将TextView添加到TableRow
tableRow.addView(textView1);
tableRow.addView(textView2);
// 将TableRow添加到TableLayout
tableLayout.addView(tableRow);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error fetching data", Toast.LENGTH_SHORT).show();
}
});
// 将StringRequest对象添加到请求队列
Volley.newRequestQueue(this).add(stringRequest);
}
这样,当用户点击"Add Data"按钮时,Volley将从MySQL数据库获取数据,并将其以表格形式添加到TableLayout中。
注意:以上代码仅提供了一个基本的示例,实际应用中可能需要进行错误处理、数据解析和适当的布局调整。
企业创新在线学堂
云+社区沙龙online [国产数据库]
小程序云开发官方直播课(应用开发实战)
云+社区技术沙龙[第20期]
云+社区技术沙龙[第17期]
云+社区技术沙龙[第25期]
领取专属 10元无门槛券
手把手带您无忧上云