【问题标题】:Using retrofit to return information from an API, how do I use this in other classes?使用改造从 API 返回信息,我如何在其他类中使用它?
【发布时间】:2016-03-22 18:19:23
【问题描述】:

所以我(我认为)为我的应用程序设置了一种从 Web 服务中提取信息的方法。但是我不确定如何将这些信息放入变量/在其他类中使用这些信息?

我在一类中设置改造:

public static final String URL = "baseURLhere";

public void setupRF(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}

我有另一个类镜像将返回的 JSON:

public class Friends {
private String name;
private double lon;
private double lat;
private List<Friends> friends;
getters and setters (omitted)...
}

最后我有:

public interface FriendsInterface {
@GET("restofURLhere.php")
Friends getFriends();
}

因此,据我所知,如果到目前为止我所做的一切都正确,那么 getFriends() 方法应该从 API 调用信息 - 但是如何将这些信息存储到我的特定变量中?我假设一旦它们被存储,我就可以像其他类/活动中的常规变量一样调用它们?

提前谢谢各位。

【问题讨论】:

  • 我使用 dagger2 并使用单例模式,然后我可以在活动或片段中注入我需要的任何模块
  • 我对使用这些库还很陌生,所以我不太清楚这意味着什么

标签: java android api retrofit2


【解决方案1】:

使用您的 Retrofit 实例创建单例。下载数据通话:

Friends friends = retrofit.createService(FriendsInterface.class).getFriends();

这些是基础。阅读:123 也可以考虑使用 Retrofit ver 2,它现在已经稳定了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    相关资源
    最近更新 更多