2017-02-12 73 views
0

我有我使用Android的展示cardViews的Android AsyncHttpClient的onSuccess()與全球的ArrayList

ArrayList<Transaction> listTransactions; 

當內部的onSuccess AsyncHttpClient的,它工作正常使用listTransactions.add全球ArrayList中,但出的onSuccess功能( inside 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(); 
} 
+0

你定義了'listTransactions = new ArrayList <>();'在'getTransactions'函數中,你如何期望在'initializeAdapter'外面使用它? –

+0

我定義了它全局ArrayList listTransactions; 這是初始化 – wkh

+0

:D對不起,我的錯誤。我想你應該先設置適配器然後初始化你的數組。這是正確的方法。 –

回答

0

的的onSuccess,當你調用initializeAdapter(尚未執行),因爲它是異步的。添加ArrayList中的元素後,您應該初始化適配器onSuccess或notifyDataSetChanged()。

+0

添加transaction_card。在添加listTransactions ArrayList中的所有元素後,在onSuccess中調用getAdapter()。notifyDataSetChanged()。 –

+0

它在我在onSuccess中添加初始化時起作用。 謝謝 – wkh

+0

你很好;) –