int android.support.v7.widget.GridLayoutManager.getItemCount()'对空对象的引用

时间:2018-06-23 07:35:32

标签: android android-recyclerview adapter

此处getItemCount()不为空,但此处getlayoutmanager为空。请帮我解决这个问题。当用户在滚动结束时向下滚动recyclerview时,我正在尝试加载更多数据,以此类推。该错误发生在适配器中。

这里getLayoutManager()为空:

final GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();

我的适配器代码:

public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context mCtx;
private ImageView link;
private boolean isLoading;
private List<Image> imageList;
private int visibleThreshold = 5;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private int lastVisibleItem, totalItemCount;
private OnLoadMoreListener onLoadMoreListener;

public ImageAdapter(RecyclerView recyclerView, List<Image> imageList, Context mCtx) {
    this.imageList = imageList;
    this.mCtx = mCtx;
    final GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            Log.d(TAG, "Tj_getItemCount" + getItemCount());
            Log.d(TAG, "Tj_linearLayoutManager" + gridLayoutManager);


                totalItemCount = gridLayoutManager.getItemCount();
                lastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();

                if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                    if (onLoadMoreListener != null) {
                        onLoadMoreListener.onLoadMore();
                    }
                    isLoading = true;
            }
        }
    });
}


public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
    this.onLoadMoreListener = mOnLoadMoreListener;
}

@Override
public int getItemViewType(int position) {
    return imageList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}


@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    if (viewType == VIEW_TYPE_ITEM) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.list_items, parent, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    } else if (viewType == VIEW_TYPE_LOADING) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_loading, parent, false);
        LoadingViewHolder vh1 = new LoadingViewHolder(view);
        return vh1;
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    if (holder instanceof ViewHolder) {
        final Image image = imageList.get(position);
        final String imgUrl = image.getThumb();
        link.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(v.getContext(), ViewImage.class);
                intent.putExtra("URL", imgUrl);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                v.getContext().startActivity(intent);
            }
        });

        Glide.with(mCtx).load(imgUrl).into(link);

    } else if (holder instanceof LoadingViewHolder) {
        LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
        loadingViewHolder.progressBar.setIndeterminate(true);
    }

}


@Override
public int getItemCount() {
    return imageList == null ? 0 : imageList.size();
}

public void setLoaded() {
    isLoading = false;
}

private class LoadingViewHolder extends RecyclerView.ViewHolder {
    public ProgressBar progressBar;

    LoadingViewHolder(View view) {
        super(view);
        progressBar = view.findViewById(R.id.progressBar1);
    }
}

class ViewHolder extends RecyclerView.ViewHolder {

    ViewHolder(View v) {
        super(v);
        link = v.findViewById(R.id.link);
    }
}
}

我的活动代码:

    public class MainActivity extends AppCompatActivity {

//the URL having the json data     https://api.unsplash.com/search/photos?query=canada&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c
//    private static final String JSON_URL = "https://api.unsplash.com/photos/random?count=25&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c";
//    private static final String JSON_URL = "https://api.unsplash.com/photos/?client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c";

int i = 2;
Image hero;
String query;
List<Image> imageList;
RecyclerView listView;
private static String JSON_URL;
private static final String TAG = "Tj";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //initializing listview and hero list
    listView = findViewById(R.id.listView);
    imageList = new ArrayList<>();

    Intent intent = getIntent();
    query = intent.getStringExtra("category");
    JSON_URL = "https://api.unsplash.com/search/photos?query=" + query + "&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c&page=1";
    Log.d(TAG, "Query" + JSON_URL);

    loadHeroList();
}

private void loadHeroList() {
    //getting the progressbar
    final ProgressBar progressBar = findViewById(R.id.progressBar);

    //making the progressbar visible
    progressBar.setVisibility(View.VISIBLE);

    //creating a string request to send request to the url
    StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, JSON_URL,
            new Response.Listener<String>() {
                //        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
               //                Request.Method.GET,
                //                JSON_URL,
                //                null,
               //                new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(String response) {
                    //hiding the progressbar after completion
                    progressBar.setVisibility(View.INVISIBLE);


                    try {
                        //getting the whole json object from the response
                        JSONObject obj = new JSONObject(response);

                        //we have the array named hero inside the object
                        //so here we are getting that json array
                        JSONArray heroArray = obj.getJSONArray("results");

                        //now looping through all the elements of the json array
                        for (int i = 0; i < heroArray.length(); i++) {
                            //getting the json object of the particular index inside the array
                            JSONObject jsonObject = heroArray.getJSONObject(i);

                            JSONObject jsonObject1 = jsonObject.getJSONObject("urls");

                            //creating a hero object and giving them the values from json object
                            hero = new Image(jsonObject.getString("id"),
                                    jsonObject.getString("color"),
                                    jsonObject1.getString("full"));


                            //adding the hero to herolist
                            imageList.add(hero);
                        }

                        //creating custom adapter object
                        final ImageAdapter adapter = new ImageAdapter(listView, imageList, getApplicationContext());

                        listView.setHasFixedSize(true);
                        // use a grid layout manager
                        listView.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));

                        //adding the adapter to listview
                        listView.setAdapter(adapter);

                        adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
                            @Override
                            public void onLoadMore() {
                                if (imageList.size() <= 20) {
                                    imageList.add(null);
                                    adapter.notifyItemInserted(imageList.size() - 1);
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            imageList.remove(imageList.size() - 1);
                                            adapter.notifyItemRemoved(imageList.size());

                                            JSON_URL = "https://api.unsplash.com/search/photos?query=" + query + "&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c&page=" + i;
                                            Log.d(TAG, "QueryLoadMore" + JSON_URL);
                                            i++;
                                            StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, JSON_URL,
                                                    new Response.Listener<String>() {
                                                        @Override
                                                        public void onResponse(String response) {
                                                            //hiding the progressbar after completion
                                                            progressBar.setVisibility(View.INVISIBLE);


                                                            try {
                                                                //getting the whole json object from the response
                                                                JSONObject obj = new JSONObject(response);

                                                                //we have the array named hero inside the object
                                                                //so here we are getting that json array
                                                                JSONArray heroArray = obj.getJSONArray("results");

                                                                //now looping through all the elements of the json array
                                                                for (int i = 0; i < heroArray.length(); i++) {
                                                                    //getting the json object of the particular index inside the array
                                                                    JSONObject jsonObject = heroArray.getJSONObject(i);

                                                                    JSONObject jsonObject1 = jsonObject.getJSONObject("urls");

                                                                    //creating a hero object and giving them the values from json object
                                                                    hero = new Image(jsonObject.getString("id"),
                                                                            jsonObject.getString("color"),
                                                                            jsonObject1.getString("full"));


                                                                    //adding the hero to herolist
                                                                    imageList.add(hero);
                                                                }
                                                            } catch (JSONException e) {
                                                                e.printStackTrace();
                                                            }
                                                        }
                                                    },
                                                    new Response.ErrorListener() {
                                                        @Override
                                                        public void onErrorResponse(VolleyError error) {
                                                            //displaying the error in toast if occurrs
                                                            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                                                        }
                                                    });
                                            //creating a request queue
                                            RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                                            //adding the string request to request queue
                                            requestQueue.add(jsonArrayRequest);

                //                                                imageList.add(hero);
               //                                                }
                                            adapter.notifyDataSetChanged();
                                            adapter.setLoaded();
                                        }
                                    }, 5000);
                                } else {
                                    Toast.makeText(MainActivity.this, "Loading data completed", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //displaying the error in toast if occurrs
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

    //creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //adding the string request to request queue
    requestQueue.add(jsonArrayRequest);
}

}

1 个答案:

答案 0 :(得分:0)

您从未为LayoutManager设置任何类型的listView

在创建自定义适配器对象之前,您必须设置布局管理器。

您可以通过调用以下内容进行设置:recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));然后可以在您的ImageAdapter类中获取它。