首页 > 解决方案 > 动态地将数据填充到微调器中

问题描述

我目前正纠结于如何将我的数据显示给我的微调器。所以基本上我使用 Websocket 接收数据并在我的 UI 线程上运行它我的问题是我的微调器中没有显示数据列表。

这是我的代码:

    WayPointData = new SubscribedData<>();
    final Type WayPointType = new TypeToken<SubscribedData<WayPoint>>() {
    }.getType();


    /** an ID for the spinner **/
    spin = (Spinner) findViewById(R.id.spinner);

    final SpinnerAdapter adapter = new ArrayAdapter<String>(Pop.this, android.R.layout.simple_spinner_item);
    spin.setAdapter(adapter);

    rosbridge = new RosbridgeListener("ws://10.24.204.231:9090");
    rosbridge.setOnDataReceivedListener(new RosbridgeMessageListener() {

        /**
         * a running thread that when the connection is made the data of the topic will serialize and deserialized java objects
         * to (and from) JSON.
         * @param msg
         */
        @Override
        public void onDataReceived(final String msg) {
            try {
                runOnUiThread(  new Runnable() {
                    @Override
                    public void run() {
                        try {
                            WayPointData = new Gson().fromJson(msg,WayPointType);
                            JSONObject jsonObject = new JSONObject();
                            JSONArray wayPointJsonArray = jsonObject.getJSONObject("msg").getJSONArray("waypoints");
                            for (int i = 0; i < wayPointJsonArray.length(); i++) {
                                JSONObject wayPointJsonObject = wayPointJsonArray.getJSONObject(i);
                                // Parse name
                                String name = wayPointJsonObject.getString("name");
                                WayPoint wayPoint = new WayPoint();
                                wayPoint.name = name;

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

                    }
                });

                /** a msg that will display once the data is received **/
                Log.d("B9T", String.format("Received data: %s", msg));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });

    spin.setAdapter(adapter);
    spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int p, long id) {
            WayPoint wayPoint = (WayPoint) parent.getItemAtPosition(p);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

感谢任何可以帮助我的人!

标签: javaandroidwebsocket

解决方案


初始化适配器时添加数组:

final SpinnerAdapter adapter = new ArrayAdapter<String>(Pop.this, android.R.layout.simple_spinner_item, yourStringArray);

如果您稍后进行更改(将从服务器接收列表),只需设置您之前使用的数组与新数据并使用adapter.notifyDataSetChanged()


推荐阅读