我正在尝试在 Android 应用程序中以表格的形式显示 MySQL 数据库中的数据。到目前为止,我已使用以下代码将表中的所有数据读取到数组中:
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/database","localhost","root");
PreparedStatement stmt = con.prepareStatement("select * from stock");
ResultSet result = stmt.executeQuery("select * from stock");
ArrayList<Integer> stockNo = new ArrayList<Integer>();
ArrayList<String> stockName = new ArrayList<String>();
ArrayList<Integer> stockQuantity = new ArrayList<Integer>();
ArrayList<String> stockUnit = new ArrayList<String>();
ArrayList<Integer> stockThreshold = new ArrayList<Integer>();
while(result.next()){
stockNo.add(result.getInt(1));
stockName.add(result.getString(2));
stockQuantity.add(result.getInt(3));
stockUnit.add(result.getString(4));
stockThreshold.add(result.getInt(5));
}
}
我的问题是现在如何将数组中的数据放入表布局 View 中?
将所有文本存储为 @string 资源是一种很好的做法,那么有没有办法像这样存储我的数组值?
最佳答案
您可以将这五个属性封装在一个新类中,而不是五个 ArrayList 吗?
public class Stock{
public int number;
public String name;
public int quantity;
public String unit;
public int stockThreshold;
}
并替换 while 循环:
ArrayList<Stock> stockList = new ArrayList<MainActivity.Stock>();
while(result.next()){
Stock stock = new Stock();
stock.number = result.getInt(1);
stock.name = result.getString(2);
stock.quantity = result.getInt(3);
stock.unity = result.getString(4);
stock.stockThreshold = result.getInt(5);
stockList.add(stock);
}
为什么使用 TableLayout?您应该小心内存消耗并避免创建不必要的多个 View 。我建议实现自定义适配器和 Gridlayout,请查看本教程(GridView 自定义适配器示例):
关于java - 将数组中的数据放入 Android View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22389266/