【问题标题】:Android error while adding data to ArrayList向 ArrayList 添加数据时出现 Android 错误
【发布时间】:2016-02-03 19:24:40
【问题描述】:

我发送 POST 请求并获取 JSON 对象。我已经解析了它,但是当我尝试将它添加到 ArrayListRecyclerView 时,我得到 ArrayList 的 0 大小。我的AsyncTask

new AsyncTask<Void, Void, Void>() {
            ProgressDialog loading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(LectorsListActivity.this, null, "Please Wait", true, false);
            }

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    LoginLectorUtils httpUtils = new LoginLectorUtils();
                    String name, uniqueId, photoUrl;
                    JSONArray array = new JSONArray(httpUtils.sendPostRequest(REQUEST_URL));

                    for (int i = 0; i < array.length(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);

                        name = jsonObject.getString("name");
                        uniqueId = jsonObject.getString("unique_id");
                        photoUrl = jsonObject.getString("photo_url");

                        //if (!name.equals("") && !uniqueId.equals("") && !photoUrl.equals("")) {
                            data.add(new LectorsDataModel(name, uniqueId, photoUrl)); // Here i'm adding new items
                        //}
                    }

                } catch (Exception e) {
                    Log.e("LectorsListActivity", "Can't create JSONArray");
                }

                return null;
            }

            @Override
            protected void onPostExecute(final Void str) {
                super.onPostExecute(str);
                loading.dismiss();
            }
        }.execute();

        //data = new ArrayList<LectorsDataModel>();
        //data.add(new LectorsDataModel("", "", ""));

        Toast.makeText(LectorsListActivity.this, Integer.toString(data.size()), Toast.LENGTH_SHORT).show(); // Shows 0

        adapter = new LectorsAdapter(data, this);
        recyclerView.setAdapter(adapter);

【问题讨论】:

  • 您需要熟悉asyncasynctask 中的含义。

标签: java android arraylist android-asynctask


【解决方案1】:

你的代码在你得到结果之前就被执行了,因为你在数据可用之前找到了大小。

这里有两个解决方案

解决方案 1

添加

Toast.makeText(LectorsListActivity.this, Integer.toString(data.size()), Toast.LENGTH_SHORT).show(); // Shows 0
adapter = new LectorsAdapter(data, this);
recyclerView.setAdapter(adapter);

onPostExecute() 方法内。

解决方案 2

添加

adapter.notifyDataSetChanged();

onPostExecute() 方法内。

然后放

adapter = new LectorsAdapter(data, this);

在致电AsyncTask之前

【讨论】:

  • 你可以像我在解决方案2中提到的那样,但是你必须告诉适配器数据可用,现在你可以刷新了。
  • @Rohit5k2,解决方案 2 不起作用,我得到 NullPointer
【解决方案2】:

您也可以尝试使用RxAndroid(+可选Retrolambda)。检查以下示例,该示例也应针对您的问题。

创建将发出您的项目的可观察对象:

    rx.Observable<List<Item>> fetchItems() {
    return Observable.create(
        subscriber -> {
            try {
                Thread.sleep(2000); //simulate long operation
                subscriber.onNext(yourItems());
            } catch (InterruptedException e) {
                subscriber.onError(e);
            }
        }
    );
}

并订阅它:

    Subscription subscription = fetchItems()
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnSubscribe(() -> mProgressDialog = ProgressDialog.show(getContext(), "Progress", "Please Wait", true))
        .doOnTerminate(this::dismissProgressDialog)
        .subscribe(
            items -> {
                recyclerView.setAdapter(new SimpleAdapter(items));
                dismissProgressDialog();
            },
            e -> Log.e("onError", e.getMessage())
        );

'Observable.create' 中的代码将在新线程中执行,在 Android UI 线程中休息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 2018-08-18
    • 2014-04-02
    • 1970-01-01
    相关资源
    最近更新 更多