从JSON数据创建动态单选按钮

时间:2018-07-05 14:37:19

标签: android radio-button radio-group jsonparser

我已经从api中获取了数据,并且我希望将小数组显示为单选按钮,因为用户应该只能选择一个。

这是我从网络获取数据的代码:

if (coachName != null && coachId != null) {
        nameTV.setText(coachName);
        fetchBatches(coachId);
        createGroups();
    }

fetchBatches(id)中,我已经在json响应方法中完成了此操作:

if (response != null) {
                        Log.d(TAG, "Batches Response:\t" + response.toString());
                        try {
                            JSONObject object = new JSONObject(response.toString());

                            String message = object.getString("message");

                            JSONArray array = object.getJSONArray("batch_details");
                            for (int m = 0; m < array.length(); m++) {

                                JSONObject jsonObject = array.getJSONObject(m);

                                name_batch = jsonObject.getString("batch_name");
                                id_batch = jsonObject.getString("batch_id");

                                batch = new BatchResponse();
                                batch.setBatchId(id_batch);
                                batch.setBatchName(name_batch);

                                list.add(batch);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

它运行良好,并且创建单选按钮的方法:

radioButtons = new RadioButton[list.size()];
    for (int i = 0; i < list.size(); i++) {
        radioButtons[i] = new RadioButton(this);
        radioButtons[i].setGravity(Gravity.CENTER_HORIZONTAL);
        batchGroup.addView(radioButtons[i]);
        radioButtons[i].setText(list.get(i).getBatchName());
        radioButtons[i].setChecked(false);
    }

,但屏幕上没有任何显示。这是每种方法使用的全局变量:

private RadioGroup batchGroup;
private BatchResponse batch;
private List<BatchResponse> list = new ArrayList<>();
private String name_batch, id_batch;
private RadioButton[] radioButtons;

我设置错误吗?我需要这个问题的帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

尝试在fetchBatches(coachId)方法中的for循环之后调用createGroups()方法。