从服务器获取数据时如何更新ListView

时间:2015-02-23 20:19:48

标签: android listview

这就是我的ListFragment看起来

的方式
public class TransactionListFragment extends ListFragment {
    private List<Transaction> mTransactions;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().setTitle(R.string.transactions);
        mTransactions = Transactions.get(getActivity()).getTransactionsFromServer();

        ArrayAdapter<Transaction> adapter = new ArrayAdapter<>(getActivity(),
                android.R.layout.simple_list_item_1, mTransactions);
        setListAdapter(adapter);
    }
}

Transactions.get(getActivity()).getTransactionsFromServer();看起来像

private void getTransactionsFromServer() {
        final String url = "myURL";
        RequestQueue queue = Volley.newRequestQueue(mContext);

        JsonObjectRequest request = new JsonObjectRequest(url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("GET /Transactions:", response.toString());
                        generateTransactionCollectionFromResponse(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // handle error
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("BEARER", "55b885274e7912280095ef80ac1cb937:d8922b44-75af-4810-a87e");
                return headers;
            }
        };

        queue.add(request);
    }

    private void generateTransactionCollectionFromResponse(JSONObject response) {
        JSONArray transactionsJson = null;
        try {
            transactionsJson = response.getJSONArray("transactions");
            Log.d("TransactionsJson:", transactionsJson.toString());

            for (int i = 0; i < transactionsJson.length(); i++) {
                JSONObject transactionJson = transactionsJson.getJSONObject(i);
                Transaction transaction = new Transaction(transactionJson.getString("id"), transactionJson.getString("name"));
                mTransactions.add(transaction);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

鉴于任务将异步发生,ListView最初将为空。

问题

一旦我收到结果,我如何从Transactions指示重新加载listView?

更新
这就是Transaction的构建方式

public class Transactions {
    private List<Transaction> mTransactions;
    private static Transactions sTransactions;
    private Context mContext;

    private Transactions(Context appContext) {
        mContext = appContext;
        mTransactions = new ArrayList<>();
    }

问题
如何获得AdapterListView

3 个答案:

答案 0 :(得分:2)

快速简单/脏的解决方案可能是将ListViewAdapter实例提供给Transactions的构造函数,当您完成解析数据时,您只需调用:

((BaseAdapter)mListView.getAdapter()).notifyDataSetChanged();

请注意,它必须在UI线程上运行。

或者,

使用LocalBroadcast

的解决方案

在片段中声明BroadcastReceiver

public class MyReceiver extends BroadcastReceiver {    
    @Override
    public void onReceive(Context context, Intent intent) {
    }
} 

以及IntentFilter

的操作
public static final String DATA_READY_ACTION = "DATA_READY_ACTION";
public MyBrodacastReceiver mReceiver;

您需要注册并取消注册。您可以使用onResume注册它,onPause注销它:

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter(DATA_READY_ACTION));

取消注册

LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mMessageReceiver);

在您的Transactions类中,当新数据可用时,您可以广播事件“数据就绪”

  Intent intent = new Intent(TransactionFragment.DATA_READY_ACTION);
  LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);

当onReceive被解雇时,您可以更新/刷新ListView

使用接口的解决方案

让Activity实现一个接口,

public interface DataListener {
    public void onDataReceived(List<Transaction> t);
}

并传递实现此接口的类的引用,例如你的ListFragment,你的Transactions课程。完成填充数据后,您可以通过此对象通知事件。 E.g

private final DataListener mListener;
private Transactions(Context appContext, DataListener listener) {
    mContext = appContext;
    mListener = listener;
    mTransactions = new ArrayList<>();           
}

//.. fetch data code
if (mListener != null) {
    mListener.onDataReceived(mTransactions);
} 

请检查拼写错误

答案 1 :(得分:0)

你应该使用adapter.notifyDataSetChanged(),

更多信息:http://developer.android.com/reference/android/widget/BaseAdapter.html#notifyDataSetChanged()

答案 2 :(得分:0)

您需要创建一个AsyncTask,您可以在创建方法中调用,然后您可以:

  • Transactions.get(getActivity()).getTransactionsFromServer();方法中运行doInBackground
  • onPostExecute方法

    中创建/更新 ListAdapter