从db获取并将其显示到android表

时间:2018-04-04 17:41:05

标签: java android

我正在尝试从MySQL表中获取数据并将其显示到Android表中。

对于表格设计,我使用以下依赖项。

de.codecrafters.tableview:tableview:2.8.0

我的JsonArray

{
    "result": [
        {
            "sl": "36",
            "user_id": "575512",
            "email": "m@gmail.com",
            "password": "123",
            "name": "Moderator",
            "gender": "Male",
            "phone": "1223345",
            "lvl": "Moderator",
            "stat": "1"
        },
        {
            "sl": "68",
            "user_id": "814769",
            "email": "m2@gmail.com",
            "password": "1WCcvnhp",
            "name": "Test Moderator",
            "gender": "Male",
            "phone": "7412589630",
            "lvl": "Moderator",
            "stat": "1"
        },
        {
            "sl": "69",
            "user_id": "742136",
            "email": "m3@gmail.com",
            "password": "YG5*3Kj9",
            "name": "Mod3",
            "gender": "Male",
            "phone": "1423687450",
            "lvl": "Moderator",
            "stat": "1"
        }
    ]
}

直到我的代码:

JSONArray result = response.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
    JSONObject jsonObject = result.getJSONObject(i);

    String name = jsonObject.getString("name");
    String phone = jsonObject.getString("phone");
    String email = jsonObject.getString("email");

    modUpdateAdapter.setName(name);
    modUpdateAdapter.setPhone(phone);
    modUpdateAdapter.setEmail(email);
    arrayList.add(modUpdateAdapter);
}

showData();

showData功能

public void showData(){
    data = new String[arrayList.size()][10];

    for (int j = 0; j < arrayList.size(); j++) {
        modUpdateAdapter = arrayList.get(j);
        data[j][0] = modUpdateAdapter.getName();
        data[j][1] = modUpdateAdapter.getEmail();
        data[j][2] = modUpdateAdapter.getPhone();
    }

    tableView.setDataAdapter(new SimpleTableDataAdapter(getActivity(), data));
}

问题是,即使我在for循环中调用showData(),也只显示最后一个值3次。我想显示数组中的所有3个对象,而不是单个对象3次。请帮帮我。

1 个答案:

答案 0 :(得分:2)

当您从JSON解析数据并将数据放入ArrayList modUpdateAdapter时,您遇到了问题。每次设置名称,电子邮件和电话时,您都不会创建ModUpdateAdapter的新实例。因此,每次解析数据并将其保存在同一modUpdateAdapter类中时。所以函数需要修改如下。

JSONArray result = response.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
    JSONObject jsonObject = result.getJSONObject(i);

    String name = jsonObject.getString("name");
    String phone = jsonObject.getString("phone");
    String email = jsonObject.getString("email");

    // Each time create a new instance and then save the value.
    ModUpdateAdapter modUpdateAdapter = new ModUpdateAdapter();

    modUpdateAdapter.setName(name);
    modUpdateAdapter.setPhone(phone);
    modUpdateAdapter.setEmail(email);
    arrayList.add(modUpdateAdapter);
}