我试图以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));
}
}
我的问题是我现在如何将数组中的数据放入我的表格布局视图?
将所有文本存储为@string资源是一种很好的做法,那么有没有办法处理我的数组值?
答案 0 :(得分:0)
可以通过以下方式完成:
DriverManager.getConnection("jdbc:mysql://localhost:3306/database","localhost","root");
PreparedStatement stmt = con.prepareStatement("select * from stock");
ResultSet result = stmt.executeQuery("select * from stock");
TableLayout tableLayout = new TableLayout(this);
while(result.next()){
TableRow tableRow = new TableRow(this);
TextView stockNo = new TextView(this);
TextView stockName = new TextView(this);
TextView stockQuantity = new TextView(this);
TextView stockUnit = new TextView(this);
TextView stockThreshold = new TextView(this);
stockNo.setText(String.valueOf(result.getInt(1)));
stockName.setText(String.valueOf(result.getInt(2)));
stockQuantity.setText(String.valueOf(result.getInt(3)));
stockUnit.setText(String.valueOf(result.getInt(4)));
stockThreshold.setText(String.valueOf(result.getInt(5)));
tableRow.addView(stockNo);
tableRow.addView(stockName);
tableRow.addView(stockQuantity);
tableRow.addView(stockUnit);
tableRow.addView(stockThreshold);
tableLayout.addView(tableRow);
}
答案 1 :(得分:0)
您可以将这五个属性封装在一个新的类中,而不是五个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?您应该小心内存消耗并避免创建不必要的多个视图。我建议实现自定义适配器和Gridlayout,请看一下本教程(GridView Custom Adapter示例):