簡體   English   中英

如何使用Retrofit將數據設置為listview?

[英]How to set data to listview using Retrofit?

首先這是代碼。 但這不是真正的代碼。

API_Interface.java

public interface API_Interface{
    @GET("/api/foo")
    Call<Foo> foo_API();
}

foo.java

public class foo{
    @SerializedName("foo")
    @Expose
    private String foo;

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity{
    String buzz;
    Retrofit foo_retro;

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

        ListView listView = (ListView) findViewById(R.id.list_view);
        ArrayList<foo> fooList = new ArrayList<foo>();
        FooAdapter fooAdapter = new FooAdapter(this, 0, fooList);
        listView.setAdapter(fooAdapter);

        ...

        foo_retro = new Retrofit.Builder()
                .baseUrl("http://api.foo.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();  

        API_Interface foo_service = foo_retro.create(API_Interface.class)

        Call<foo> foo_call=foo_service.foo_API();
        foo_call.enqueue(new Callback<foo>() {             
            @Override
            public void onResponse(Call<foo> call, Response<foo> response) {
                buzz = response.body().getFoo();
                System.out.println(buzz);
            } 

            @Override
            public void onFailure(Call<zaifExchange> call, Throwable t) {
                Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT);
            }
        });
        fooList.add(new foo(buzz));
        System.out.println(buzz);
    }
}

當我運行此代碼時,我可以在onResponse方法中獲取並打印buzz (如“Apple”)。 但是,我無法將數據設置為listviewbuzz為null)。 我知道原因是enqueue是異步的,所以終端顯示:

I/System.out: null
I/System.out: Apple

所以我該怎么做? 謝謝。

將響應添加到fooList內的onResponse否則您將添加null值作為

@Override
public void onResponse(Call<foo> call, Response<foo> response) {
    buzz = response.body().getFoo();
    fooList.add(new foo(buzz));
    System.out.println(buzz);
    fooAdapter.notifyDataSetChanged();
   // ^^^^ notify changes to display data 
   // you might want to declare references outside oncreate to avoid local variables
} 

去掉

fooList.add(new foo(buzz));
System.out.println(buzz);

(在enqueue之外)因為在響應之前buzz將為null

在我看來,你的問題是雙重的:

  1. 考慮在onCreate()方法本身打印之前添加延遲。 更好的是,在繼續之前驗證是否已實際設置了buzz
  2. 因為enqueue()是異步的,所以無論發生什么,打印的父線程都可能看不到buzz 相反,請考慮使用AtomicReference類包裝buzz字段。 這樣,無論線程如何,任何線程都可以看到最新的buzz值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM