RecyclerView:没有连接适配器;跳过布局 - recycleView错误

时间:2016-07-07 09:25:45

标签: java android android-recyclerview recycler-adapter

它给我" RecyclerView:没有附加适配器;跳过布局"错误,但在我看来适配器已正确连接。请帮忙。

    public class MainActivity extends AppCompatActivity {

    private final String TAG = "MainActivity";
    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private RecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
        layoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(layoutManager);
        requestJsonObject();
    }

    private void requestJsonObject(){
        RequestQueue queue = Volley.newRequestQueue(this);
        String url ="https://api.myjson.com/bins/2t4j3";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Response " + response);
                GsonBuilder builder = new GsonBuilder();
                Gson mGson = builder.create();
                List<ItemObject> posts = new ArrayList<ItemObject>();
                posts = Arrays.asList(mGson.fromJson(response, ItemObject[].class));
                adapter = new RecyclerViewAdapter(MainActivity.this, posts);
                recyclerView.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error " + error.getMessage());
            }
        });
        queue.add(stringRequest);
    }
}

我正在移动我的方法,但它不起作用。我在这里寻找答案,但只有错误实现的适配器的问题。我不知道这里有什么不对。

2 个答案:

答案 0 :(得分:0)

尝试把这一行:

adapter = new RecyclerViewAdapter(MainActivity.this, posts);

LayoutManager添加到RecyclerView后。当然,列表将为空,但只是初始化RecyclerAdapter并将其分配给RecyclerView

然后,当Volley完成它的请求时,请使用:

recyclerView.getAdapter().addAll(posts);
recyclerView.getAdapter().notifyDataSetChaged();

最后一个命令将元素添加到RecyclerView的适配器并通知LayoutManager更改。

答案 1 :(得分:0)

您正在延迟线程中调用setAdapter。在主线程中创建视图时,Recyclerview没有适配器。

将这两行放在setLayoutManager

之前
List<ItemObject> posts = new ArrayList<ItemObject>();
adapter = new RecyclerViewAdapter(MainActivity.this, posts);

onResponse中,您可以设置新的adpater或更新适配器中的数据,具体取决于您的实施。