gpt4 book ai didi

java - 将外部类中的值设置为内部类中检索到的值

转载 作者:行者123 更新时间:2023-12-02 09:46:43 25 4
gpt4 key购买 nike

我的 Android 应用程序中有一个 fragment ,其想法是从 json 文件(github)中提取信息并解析标题,然后将其更新到我的 recyclerview 中。我可以很好地提取数据,将其放入列表中,这是我的模式。

现在这些数据位于“onResponse”内部类中,也位于“onCreateView”内部类中。

更新我的 recyclerview 的代码位于 onCreateView 内部类中。如何将列表从 onResponse 传递到 onCreate,甚至传递到全局级别?

在该类中,我有 2 个全局变量:

static List<GithubRepo> list  = new ArrayList<>();
static List<String> List_body = new ArrayList<>();

现在,在创建 View 的内部类“Create”方法中,我使用 Retrofit 解析 github 的 json 以获取一些存储库名称。

我可以很好地获取它们,但是当我从“response.body”获取列表时,然后使用以下方法将其正确解析为仅获取标题的字符串:

private void setList(List<GithubRepo> repo){
if (repo != null) {
int counter = 0;
for (GithubRepo r : repo) {
String name = r.getName().toString();
List_body.add(name);
counter++;
}


}
else{
Log.d("test:empty", "empty");
}
}

上面的 GithubRepo 只是 json 的对象结构,我在内部类中获取名称,设置它们,但当我尝试将新列表应用到我的 View 时,它们仍然为空。如何从内部类中的变量设置全局/静态变量的值?

这是整个事情:

public class primary_fragment extends Fragment implements Agg_Adapter.ItemClickListener {

static List<GithubRepo> list = new ArrayList<>(); <--------HOLDS value of schema object temporarily
static List<String> List_body = new ArrayList<>(); <--------UPDATES the recyclerview, currently empty
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {


.... Some code

call.enqueue(new Callback<List<GithubRepo>>() {
@Override <------------------------- From here is the inner class
public void onResponse(Call<List<GithubRepo>> call, Response<List<GithubRepo>> response) {
// 1. start
if (response.isSuccessful()) {
if (response.body() != null) {

list.addAll(response.body());
setList(list);
});

Log.d("testedB2!:", (List_body.toString())); <------Should have the values set but it is null

这可能是非常简单的事情,但我忘了!如果我需要澄清任何事情,请告诉我。

最佳答案

您使用 Retrofit 的方式使调用异步。这没有什么错,事实上就应该这样。但是,应该在将其打印到日志的行中填充 List_body 的假设是不正确的。简而言之,在网络调用完成之前,Log.d 将运行并且不打印任何内容。

有多种方法可以解决此问题。最简单的方法是从 onResponse 中调用一个方法,让 fragment 知道列表已准备就绪。例如:

call.enqueue(new Callback<List<GithubRepo>>() {
@Override
public void onResponse(Call<List<GithubRepo>> call, Response<List<GithubRepo>> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
list.addAll(response.body());
setList(list);
onListReady();
});

一旦调用方法 onListReady() ,您就可以根据需要打印日志语句:

private void onListReady () {
Log.d("testedB2!:", (List_body.toString()));
}

您可以在 fragment 中实现这一点。

就像我说的,有不同的方法可以做到这一点。我只是想向您展示该调用实际上是异步运行的。

关于java - 将外部类中的值设置为内部类中检索到的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56594335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com