Android 具有全局 arrayList 的 AsyncHttpClient onSuccess()

Android AsyncHttpClient onSuccess() with global arrayList

我有一个全局数组列表,用于显示 android cardViews

ArrayList<Transaction> listTransactions;

在 AsyncHttpClient 的 onSuccess 中使用 listTransactions.add 时,它工作正常,但在 onSuccess 函数之外(在 initializeAdapter 中),listTransactions 变为空

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getTransactions();
    initializeAdapter();
}

private void initializeAdapter(){
    Transaction_Adapter adapter = new Transaction_Adapter(listTransactions);
    transaction_card.setAdapter(adapter);
    LinearLayoutManager llm = new LinearLayoutManager(getContext());
    transaction_card.setLayoutManager(llm);
    transaction_card.setHasFixedSize(true);
    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(transaction_card.getContext(),1);
    transaction_card.addItemDecoration(dividerItemDecoration);
}

public void getTransactions() {
    listTransactions=new ArrayList<>();
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(ip,params ,new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(String response) {
            try {
                JSONObject obj = new JSONObject(response);
                if(obj.getBoolean("status")){
                    int count = obj.getInt("count");
                    for(int i=0;i<count;i++) {
                        JSONObject o = obj.getJSONObject("Transaction_" + i);
                        listTransactions.add(new Transaction(o.getInt("Sender"),o.getInt("Receiver"),o.getDouble("Amount"),o.getString("Date"),o.getString("Type")));
                    }
                    //testing 
                    for(Transaction t:listTransactions){
                        Log.e("transaction",String.valueOf(t.type)); //this shows the type of all transactions correctly
                    }
                }
            .
            .
            .
            }
        }//catch & onFailure...
    });}

没有异常或错误。

此外,当我尝试在 initializeAdapter() 之前手动添加它时,它显示手动添加的卡正常

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getTransactions();
    listTransactions.add(new Transaction(1,2,111,"01-12-2016 12:15","test")); //manually added card
    initializeAdapter();
}

当您调用initializeAdapter() 时,onSuccess 尚未执行,因为它是异步的。在 ArrayList 中添加元素后,您应该初始化适配器 onSuccess 或 notifyDataSetChanged()。