java - 将数组中的数据放入 Android View 中

标签 java android mysql arrays output

我正在尝试在 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 自定义适配器示例):

http://www.mkyong.com/android/android-gridview-example/

关于java - 将数组中的数据放入 Android View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22389266/

相关文章:

android - 无法在 Android 中使用 Aquery 获取 JsonObject 值

Android Action Bar SearchView 菜单图标大小

php - 操作数组中的数据

php - 由于 INSERT INTO .. SELECT 导致的触发错误,错误 #1442

java - fragment 错误 : Incompatible Types Required: android. support.v4.app.Fragment,找到 : package_name. app_name.Fragment_name

java - "java -server"和 "java -client"之间的真正区别?

java - 如何使用 Java 反射访问私有(private)数组?

android - 如何在 android 3.x 上运行 linux 命令挂载和卸载 sd 卡

java - 通过 EntrySet() 进行迭代不会创建太多 Map.Entry 实例吗?

mysql - 同一个表中相关项的 SQL 查询