【问题标题】:How do I get the API to return a list of integers in Android?如何让 API 在 Android 中返回整数列表?
【发布时间】:2020-02-20 18:57:56
【问题描述】:

再一次,我是编码新手,正在尝试为我的机器人团队编写一个 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;

        }

这是我要返回的,但我只想要团队编号和他们的排名

【问题讨论】:

    标签: java android api int


    【解决方案1】:

    好的,所以当您使用 EventRankings getRankings(String eventKey) 时,您会得到一个对象 EventRankings,并且您想要一个具有团队编号和排名的对象。

    根据你分享的图片:

    • EventRankings
    • 收藏了Ranking
    • Ranking 有一个 int Rank
    • Ranking 也有一个字符串team_key(我猜是“队号”

    您可以通过以下几种方式做到这一点:

    1

    假设您希望将其作为某种类型的地图 Map&lt;TeamNumber, Rank&gt;

    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&lt;Result&gt;

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

    取自:

    【讨论】:

    • 太感谢了,请问第一个和第二个,代码去哪了?就像我猜的那部分。对不起!我对此很陌生
    • ASyncTaskdoInBackground 内,您可以将其更改为返回不同类型的对象(类型参数&lt;&gt; 中的第三个参数将从EventRankings 更改为您选择的任何内容.)
    • 我收到此错误:java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on an null object reference at com.example .scoutingapp4.RankingsFragment.onClick(RankingsFragment.java:50)
    • 那么第 50 行是什么?似乎您的 ASyncTask 现在可能正在返回 null。我回答了您的问题 - 您可能需要将此标记为已回答并打开一个问题
    • @Cail 如果这回答了您的问题,请将其标记为已回答
    猜你喜欢
    • 1970-01-01
    • 2015-07-07
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2012-10-24
    相关资源
    最近更新 更多