Как получить API для возврата списка целых чисел в Android? - PullRequest
2 голосов
/ 20 февраля 2020

Еще раз, я новичок в кодировании и пытаюсь написать приложение Android для моей команды робототехники. Я продвинулся довольно далеко, но я застрял, пытаясь вернуть только ранг некоторых команд.

Вот мой текущий код onClick

public void onClick(final View v) {
    v.setEnabled(false);
    switch (v.getId()) {
        case R.id.btnGetRanks:
            try {
                TextView textHeyo = (TextView) getView().findViewById(R.id.textGetRanks);
                textHeyo.setText(new EventRanking().execute(tba).get().toString());
            } catch (  ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
            break;
       //... more code not related to issue ...
    }
    // ...
}

Это моя вещь doInBackground (как я уже сказал , Я новичок)

public class EventRanking extends AsyncTask<TBA, Void, EventRankings> {

    protected EventRankings doInBackground(TBA... tbas) {

        try {
            EventRankings ourEventRankings = tbas[0].eventRequest.getRankings( "2019cada");
            EventRankings event = ourEventRankings;
            return ourEventRankings;
        } catch (IOException e) {
            e.printStackTrace();
            return  null;
        }
    }
 }

Это полный список вещей, которые я могу получить с помощью EventRequest

public class EventRequest {

    private DataRequest tba;

    /**
    * Creates an EventRequest object
    *
    * @param tba A {@link DataRequest} object with the appropriate auth key
    */
    public EventRequest(DataRequest tba) {
        this.tba = tba;
    }



    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return The {@link Event} object referenced by the given key
     * @throws IOException
     */
    public Event getEvent(String eventKey) throws IOException {
        String directory = "/event/" + eventKey;
        return Deserializer.toEvent(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/simple</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return The {@link SimpleEvent} object referenced by the given key
     * @throws IOException
     */
    public SimpleEvent getSimpleEvent(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/simple";
        return Deserializer.toSimpleEvent(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/teams</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A list of {@link Team} objects that competed in the given event.
     * @throws IOException
     */
    public Team[] getTeams(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/teams";
        return Deserializer.toTeamArray(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/teams/simple</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A list of {@link SimpleTeam} objects that competed in the given event.
     * @throws IOException
     */

    public SimpleTeam[] getSimpleTeams(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/teams/simple";
        return Deserializer.toSimpleTeamArray(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/teams/keys</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A list of {@link Team} keys that competed in the given event.
     * @throws IOException
     */

    public String[] getTeamKeys(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/teams/keys";
        return Deserializer.toStringArray(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/events/{year}</code>
     *
     * @param year Competition year (or season). Must be four digits.
     * @return A list of {@link Event} objects that occurred in a given year
     * @throws IOException
     */

    public Event[] getEvents(int year) throws IOException {
        String directory = "/events/" + year;
        return Deserializer.toEventArray(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/events/{year}/simple</code>
     *
     * @param year Competition year (or season). Must be four digits.
     * @return A list of {@link SimpleEvent} objects that occurred in a given year
     * @throws IOException
     */
    public SimpleEvent[] getSimpleEvents(int year) throws IOException {
        String directory = "/events/" + year + "/simple";
        return Deserializer.toSimpleEventArray(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/events/{year}/keys</code>
     *
     * @param year Competition year (or season). Must be four digits.
     * @return A list of {@link Event} keys that occurred in a given year
     * @throws IOException
     */
    public String[] getEventKeys(int year) throws IOException {
        String directory = "/event/" + year + "/keys";
        return Deserializer.toStringArray(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/district_points</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A list of team rankings for the event
     * @throws IOException
     */
    public EventDistrictPoints getDistrictPoints(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/district_points";
        return Deserializer.toEventDistrictPoints(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/alliances</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A list of {@link EliminationAlliance}s for the event
     * @throws IOException
     */
    public EliminationAlliance[] getAlliances(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/alliances";
        return Deserializer.toEliminationAllianceArray(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/oprs</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A set of {@link OPRs} (includeing OPR, DPR, and CCWM) for the event
     * @throws IOException
     */
    public OPRs getOPRs(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/oprs";
        return Deserializer.toOPRs(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/rankings</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A list of team rankings for the event
     * @throws IOException
     */
    public EventRankings getRankings(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/rankings";
        return Deserializer.toEventRankings(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/matches</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A list of {@link Match}es for the event
     * @throws IOException
     */
    public Match[] getMatches(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/matches";
        return Deserializer.toMatchArray(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/matches/simple</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A list of {@link SimpleMatch}es for the event
     * @throws IOException
     */
    public SimpleMatch[] getSimpleMatches(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/matches/simple";
        return Deserializer.toSimpleMatchArray(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/matches/keys</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A list of match keys for the event
     * @throws IOException
     */
    public String[] getMatchKeys(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/matches/keys";
        return Deserializer.toStringArray(tba.getDataTBA(directory).getJson());
    }

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/awards</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A list of {@link Award}s from the given the event
     * @throws IOException
     */
    public Award[] getAwards(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/awards";
        return Deserializer.toAwardArray(tba.getDataTBA(directory).getJson());
    }
}

Более конкретно, это тот, который я пытаюсь получить этот

    /**
     * Makes API requests with the subdirectory <code>/event/{eventKey}/rankings</code>
     *
     * @param eventKey TBA Event Key, e.g. <code>2016nytr</code>
     * @return A list of team rankings for the event
     * @throws IOException
     */
    public EventRankings getRankings(String eventKey) throws IOException {
        String directory = "/event/" + eventKey + "/rankings";
        return Deserializer.toEventRankings(tba.getDataTBA(directory).getJson());
    }

Это то, что вы можете получить с помощью EventRankings

    /**
     * The event rankings and tiebreaker information for an event
     */
    @Value
    public class EventRankings {

        /**
         * List of rankings at the event
         */
        public Ranking[] rankings;
        /**
         * List of year-specific values provided in the `sort_orders` array for each team.
         */
        public SortOrderInfo[] sort_order_info;

        /**
         * The Sort order of the rankings for a particular year
         */
        @Value
        public class SortOrderInfo {
            /**
             * Name of the field used in the <code>sort_order</code> array.
             */
            public String name;
            /**
             * Integer expressing the number of digits of precision in the number provided in sort_orders.
             */
            public int precision;

        }

Это то, что я получаю, но я просто хочу номер команды и ее ранг

enter image description here

1 Ответ

2 голосов
/ 20 февраля 2020

Хорошо, поэтому вы получаете объект EventRankings, когда используете EventRankings getRankings(String eventKey), и вам нужен объект с номерами команд и рангом.

В зависимости от изображения, которым вы поделились:

  • EventRankings
  • имеет коллекцию Ranking
  • Ranking имеет int Rank
  • Ranking также имеет строку team_key (что я собираюсь угадать, это «номер команды»

Вы можете сделать это несколькими способами:

1

Допустим, вы хотите это как-то тип карты Map<TeamNumber, Rank>

EventRankings eventRankings = getRankings("eventKey");

Map<String, Int> teamsRanked = new HashMap<>();
for(Ranking ranking : eventsRankings.rankings) {
    teamsRanked.put(ranking.teamKey, ranking.rank);
}

Вы можете проверить то, что у вас есть, напечатав его:

for (Map.Entry<String, Int> entry : teamsRanked.entrySet()) {
    Log.d("TUT", entry.getKey() + ":" + entry.getValue());
}

Распечатать ранг команды:

Log.d("TUT", "frc1323 is ranked: " + teamsRanked.get("frc1323"));

2

Если вы знаете, что рейтинги уникальны, вы также можете иметь свою карту наоборот:

Map<String, Int> rankedTeams = new HashMap<>();
for(Ranking ranking : eventsRankings.rankings) {
    rankedTeams.put(ranking.rank, ranking.teamKey);
}

И тогда вы можете получить команду на основе ранга, то есть выведите верхнюю 3:

Log.d("TUT", "Ranked #1 is: " + rankedTeams.get(1));
Log.d("TUT", "Ranked #2 is: " + rankedTeams.get(2));
Log.d("TUT", "Ranked #3 is: " + rankedTeams.get(3));

3

Или, наконец, если вы не хотите легко искать по рангу или имени, вы можете получить список новых объектов, возможно List<Result>.

class Result {

   private final String teamName;
   private final int rank;

   public Result(String teamName, int rank) {
       this.teamName = teamName;
       this.rank = rank;
   }

   public String getTeamName() {
       return teamName;
   }

   public int getRank() {
       return rank;
   }
}

List<Result> results = new HashMap<>();
for(Ranking ranking : eventsRankings.rankings) {
    results.add(new Result(ranking.teamKey, ranking.rank));
}

и распечатайте каждый результат:

for(Result result : results) {
    Log.d("TUT", result.getTeamName() + " : " + result.getRank());
}

Взято из:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...