Android: динамически заполняйте данные с сервера - PullRequest
0 голосов
/ 25 сентября 2019

Я новичок в Android.Как вы динамически заполняете счетчик из данных сервера.

Поэтому я пытаюсь заполнить данные с сервера на мой счетчик.мой JSON

{"topic": "/waypoints", "msg": {"waypoints": [{"header": {"stamp": {"secs": 0, "nsecs": 0}, "frame_id": "map", "seq": 0}, "pose": {"position": {"y": -140.901899144836, "x": 44.36469369653882, "z": 0.0}, "orientation": {"y": 0.0, "x": 0.0, "z": 0.5062775131960053, "w": 0.8623706161692133}}, "name": "A"}, {"header": {"stamp": {"secs": 0, "nsecs": 0}, "frame_id": "map", "seq": 0}, "pose": {"position": {"y": -102.30524463734227, "x": 51.282396271771304, "z": 0.0}, "orientation": {"y": 0.0, "x": 0.0, "z": 0.6926372547579506, "w": 0.721286096719859}}, "name": "B"}]}, "op": "publish"}

Теперь я пытаюсь получить только «имя»: A и B, и когда я выберу каждое из них, будет информация об ориентации и положении.Заранее спасибо!

РЕДАКТИРОВАТЬ

, так что в основном это всплывающее окно моих путевых точек.и я изо всех сил пытаюсь исправить "(String json)" для моей части метода.

public class Pop extends Activity {

private SubscribedData<WaypointList> waypointlistData;
private RosbridgeListener rosbridge;
Spinner spin;
String json;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.popup);

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

    /** publisher definition with its type of message**/
    waypointlistData = new SubscribedData<>();
    final Type waypointlistType = new TypeToken<SubscribedData<WaypointList>>() {
    }.getType();


    /** A method to parse a jsonstring to waypoint list **/
    private List<Waypoint> getWayPointListFromJsonString(String json){
        List<Waypoint> wayPoints = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(json);
            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");

                // Parse pose to get position and orientation;
                JSONObject poseJsonObject = wayPointJsonObject.getJSONObject("pose");

                // Parse position form pose
                JSONObject positionJsonObject = poseJsonObject.getJSONObject("position");
                Position position = new Position();
                position.x = positionJsonObject.getFloat("x");
                position.y = positionJsonObject.getFloat("y");
                position.z = positionJsonObject.getFloat("z");

                // Parse orientation from pose.
                JSONObject orientationJsonObject = poseJsonObject.getJSONObject("orientation");
                Orientation orientation = new Orientation();
                orientation.x = orientationJsonObject.getFloat("x");
                orientation.y = orientationJsonObject.getFloat("y");
                orientation.z = orientationJsonObject.getFloat("z");
                orientation.w = orientationJsonObject.getFloat("w");

                Pose pose = new Pose();
                pose.position = position;
                pose.orientation = orientation;

                Waypoint wayPoint = new Waypoint();
                wayPoint.name = name;
                wayPoint.pose = pose;
                wayPoints.add(wayPoint);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return wayPoints;
    }

    // This is the json string returned from server.
    String jsonString = "{\"topic\": \"/waypoints\", \"msg\": {\"waypoints\": [{\"header\": {\"stamp\": {\"secs\": 0, \"nsecs\": 0}, \"frame_id\": \"map\", \"seq\": 0}, \"pose\": {\"position\": {\"y\": -140.901899144836, \"x\": 44.36469369653882, \"z\": 0.0}, \"orientation\": {\"y\": 0.0, \"x\": 0.0, \"z\": 0.5062775131960053, \"w\": 0.8623706161692133}}, \"name\": \"A\"}, {\"header\": {\"stamp\": {\"secs\": 0, \"nsecs\": 0}, \"frame_id\": \"map\", \"seq\": 0}, \"pose\": {\"position\": {\"y\": -102.30524463734227, \"x\": 51.282396271771304, \"z\": 0.0}, \"orientation\": {\"y\": 0.0, \"x\": 0.0, \"z\": 0.6926372547579506, \"w\": 0.721286096719859}}, \"name\": \"B\"}]}, \"op\": \"publish\"}";

    // This will convert the json string to list of WayPoint
    List<Waypoint> wayPoints = getWayPointListFromJsonString(jsonString);

    // Create adapter for spinner
    SpinnerAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, wayPoints);

    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);

            // Process position here
            Position position = wayPoint.pose.position;

            // Process orientation here
            Orientation orientation = wayPoint.pose.orientation;
        }

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

        /** a set of the waypoints popup window **/
    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);

        int width = dm.widthPixels;
        int height = dm.heightPixels;

        getWindow().setLayout((int) (width * .6), (int) (height * .6));


}

}

Ответы [ 3 ]

0 голосов
/ 25 сентября 2019
 for (int i = 0; i < arrResult.length(); i++) {
   arr_akun[i] = "string dinamycally";
 }
ArrayAdapter<String> adapter_akun = new ArrayAdapter<>(context, R.layout.spinner_akun_item, arr_akun);
spinner.setAdapter(adapter_akun);

spinner_akun.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
     // do something to get name
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
0 голосов
/ 25 сентября 2019

Каждый элемент в счетчике указывает одну «точку маршрута».Итак, первый шаг - создание класса модели для WayPoint.

class WayPoint {
    String name;
    Pose pose;

    @NonNull
    @Override
    public String toString() {
        return name;
    }
}

class Pose {
    Position position;
    Orientation orientation;
}

class Position {
    double x, y, z;
}

class Orientation {
    double x, y, z, w;
}

Во-вторых, напишите метод для анализа строки json в списке путевых точек

private List<WayPoint> getWayPointListFromJsonString(String json) {
    List<WayPoint> wayPoints = new ArrayList<>();

    try {
        JSONObject jsonObject = new JSONObject(json);
        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");

            // Parse pose to get position and orientation;
            JSONObject poseJsonObject = wayPointJsonObject.getJSONObject("pose");

            // Parse position form pose
            JSONObject positionJsonObject = poseJsonObject.getJSONObject("position");
            Position position = new Position();
            position.x = positionJsonObject.getDouble("x");
            position.y = positionJsonObject.getDouble("y");
            position.z = positionJsonObject.getDouble("z");

            // Parse orientation from pose.
            JSONObject orientationJsonObject = poseJsonObject.getJSONObject("orientation");
            Orientation orientation = new Orientation();
            orientation.x = orientationJsonObject.getDouble("x");
            orientation.y = orientationJsonObject.getDouble("y");
            orientation.z = orientationJsonObject.getDouble("z");
            orientation.w = orientationJsonObject.getDouble("w");

            Pose pose = new Pose();
            pose.position = position;
            pose.orientation = orientation;

            WayPoint wayPoint = new WayPoint();
            wayPoint.name = name;
            wayPoint.pose = pose;
            wayPoints.add(wayPoint);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return wayPoints;
}

Наконец поместите их в класс MainActivity.

public class MainActivity extends AppCompatActivity {

    private Spinner wayPointSpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wayPointSpinner = findViewById(R.id.spinner_way_point);

        // This is the json string returned from server.
        String jsonString = "{\"topic\": \"/waypoints\", \"msg\": {\"waypoints\": [{\"header\": {\"stamp\": {\"secs\": 0, \"nsecs\": 0}, \"frame_id\": \"map\", \"seq\": 0}, \"pose\": {\"position\": {\"y\": -140.901899144836, \"x\": 44.36469369653882, \"z\": 0.0}, \"orientation\": {\"y\": 0.0, \"x\": 0.0, \"z\": 0.5062775131960053, \"w\": 0.8623706161692133}}, \"name\": \"A\"}, {\"header\": {\"stamp\": {\"secs\": 0, \"nsecs\": 0}, \"frame_id\": \"map\", \"seq\": 0}, \"pose\": {\"position\": {\"y\": -102.30524463734227, \"x\": 51.282396271771304, \"z\": 0.0}, \"orientation\": {\"y\": 0.0, \"x\": 0.0, \"z\": 0.6926372547579506, \"w\": 0.721286096719859}}, \"name\": \"B\"}]}, \"op\": \"publish\"}";

        // This will convert the json string to list of WayPoint
        List<WayPoint> wayPoints = getWayPointListFromJsonString(jsonString);

        // Create adapter for spinner
        SpinnerAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, wayPoints);

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

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

                // Process position here
                Position position = wayPoint.pose.position;

                // Process orientation here
                Orientation orientation = wayPoint.pose.orientation;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
}
0 голосов
/ 25 сентября 2019

сначала необходимо десериализовать данные и сопоставить их с классом модели, а затем установить список моделей для адаптера счетчика.Проверьте модификацию, чтобы запросить и проанализировать ваш ответ Джейсона.

...