android - Activity 无法使用 json 填充 recyclerView

标签 android json

我使用 ny times api 编写示例应用程序。 当我测试 json 时,没问题。在 Activity 中,当我收到 json 时。我无法使用 json 填充 recyclerView 。幸运的是,有时 recyclerView 会填充 json,有时什么也不填充。当我在模拟器上运行应用程序时,Android Monitor 会显示:

11226-11226/com.nytimes.nytimes E/RecyclerView: No adapter attached; skipping layout

这是 PostListActivity.java,其中 recyclerView 用 json 填充:

package com.nytimes.nytimes.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.nytimes.nytimes.R;
import com.nytimes.nytimes.adapters.postListRecyclerViewAdapter;
import com.nytimes.nytimes.app.AppController;
import com.nytimes.nytimes.pojos.PostData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class PostListActivity extends AppCompatActivity {
    RecyclerView posListRecyclerView;
    private List<PostData> postDataList = new ArrayList<PostData>();

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_list);

        setUpToolbar();

        //=============== hit sendJsonResquest ===================//
        sendJsonRequest();


        //=============== Initialize the RecyclerView ===================//
        posListRecyclerView = (RecyclerView) findViewById(R.id.recyclerPostList);
        posListRecyclerView.setHasFixedSize(true);
        posListRecyclerView.setLayoutManager(new LinearLayoutManager(PostListActivity.this));

    }

    //===================  setupToolbar =====================//
    private void setUpToolbar() {
        Toolbar postListToolbar = (Toolbar) findViewById(R.id.postListToolbar);
        setSupportActionBar(postListToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_left);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    //===================  send json request =====================//
    private void sendJsonRequest() {

        //getIntent Category
        Intent intentGetCategory = getIntent();
        String category = intentGetCategory.getExtras().getString("category");


        //find specific url with String format
        String tUrl = String.format("http://api.nytimes.com/svc/topstories/v1/%s.json?api-key=626663e02b8fe9d8:7:74012032", category);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, tUrl, (String) null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                //hit parseJsonResponse
                parseJsonResponse(response);

                //setAdapter RecyclerView
                posListRecyclerView.setAdapter(new postListRecyclerViewAdapter(PostListActivity.this, postDataList));


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(PostListActivity.this, "onErrorResponse Volley Error listener", Toast.LENGTH_SHORT).show();
            }
        });

        //add request to request queue
        AppController.getInstance().addToRequestQueue(request);

    }


    //===================  parseJsonResponse =====================//
    private void parseJsonResponse(JSONObject response) {
        if (response != null) {

            try {
                JSONArray results = response.getJSONArray("results");

                for (int i = 0; i < results.length(); i++) {

                    JSONObject currentResult = results.getJSONObject(i);

                    PostData postData = new PostData();

                    postData.setPostTitle(currentResult.getString("title"));
                    postData.setPostUrl(currentResult.getString("url"));

                    JSONArray multiMedias = currentResult.getJSONArray("multimedia");

                    for (int m = 0; m < multiMedias.length(); m++) {
                        JSONObject thumbnail = multiMedias.getJSONObject(0);
                        postData.setPostThumbnail(thumbnail.getString("url"));
                    }
                    postDataList.add(postData);
                }

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


        } else {
            Toast.makeText(PostListActivity.this, "response is empty else parsejsonresponse", Toast.LENGTH_SHORT).show();
        }
    }
}

我认为我的适配器位置不对。

最佳答案

在下载 JSON 数据时首次初始化 Adapter,在此之前 RecyclerView 没有可使用的 Adapter。

我建议:

1) 在类级别定义适配器和数据数组(在 onCreate 之外):

postListRecyclerViewAdapter adapter;
ArrayList<PostData> postDataList;

2) 在使用空的 postDataList 初始化 RecyclerView 时,仅在 onCreate 中初始化一次空适配器。

    //=============== Initialize the RecyclerView ===================// 
        posListRecyclerView = (RecyclerView) findViewById(R.id.recyclerPostList);
        posListRecyclerView.setHasFixedSize(true);
        posListRecyclerView.setLayoutManager(new LinearLayoutManager(PostListActivity.this));

    //=============== Initialize the Adapter, Data Array and set Adapter ===================// 

         postDataList = new ArrayList<PostData>();
         postListRecyclerViewAdapter adapter = new postListRecyclerViewAdapter(this, postDataList)

         posListRecyclerView.setAdapter(adapter);

3) 下载新数据并插入 postDataList 时更新 postDataList

4) 在适配器上调用 notifyDataSetChanged 以通知数据已更改。

之前在 onResponse 中设置适配器的地方,只需在将新数据插入到 postDataList 后调用以下函数即可。

adapter.notifyDataSetChanged();

关于android - Activity 无法使用 json 填充 recyclerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34828546/

相关文章:

Android - 找出现在是几点钟

android - 如何在所有 Activity 中保持操作栏固定?

android - 一起使用 firestore 和 firebase auth/core 时出现问题

android - 如何在android中获取和读取traces.txt文件

javascript - 为什么我的嵌入式 ruby​​ json 字符串在 View 中解析时会使用 html 实体进行编码?

php - android 无法从 php 获取 Json?

javascript - 如何在 Struts 2 中返回 JSON 数组

java - Android - Firebase - 无法将 java.util.HashMap 类型的值转换为字符串

json - Azure逻辑应用标准解析JSON错误

java - spring通用json响应