How do I fix this NullPointerException for webSite.getSources().size(); Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How do I fix this NullPointerException for webSite.getSources().size(); without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I cant figure out how to fix this NullPointerException error for this project: (saw similar question but it wasn’t helpful)

MainActivity.java

    public class MainActivity extends AppCompatActivity {

    RecyclerView listWebsite;
    RecyclerView.LayoutManager layoutManager;
    NewsService mService;
    ListSourceAdapter adapter;
    SpotsDialog dialog;
    SwipeRefreshLayout swipeLayout;


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

        //Init cache
        Paper.init(this);

        //Init Service
        mService = Common.getNewsService();

        //Init View
        swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadWebsiteSource(true);
            }
        });

        listWebsite = (RecyclerView) findViewById(R.id.list_source);
        listWebsite.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        listWebsite .setLayoutManager(layoutManager);

        dialog = new SpotsDialog(this);

        loadWebsiteSource(false);

    }

    private void loadWebsiteSource(boolean isRefreshed) {
        if(!isRefreshed)
        {
            String cache = Paper.book().read("cache");
            if(cache != null && !cache.isEmpty())
            {
                WebSite webSite = new Gson().fromJson(cache,WebSite.class);  //Convert cache from Json to Object
                adapter = new ListSourceAdapter(getBaseContext(),webSite);
                adapter.notifyDataSetChanged();
                listWebsite.setAdapter(adapter);
            }
            else
            {
                dialog.show();
                //Fetch new data
                mService.getSources().enqueue(new Callback<WebSite>() {
                    @Override
                    public void onResponse(Call<WebSite> call, Response<WebSite> response) {
                        adapter = new ListSourceAdapter(getBaseContext(),response.body());
                        adapter.notifyDataSetChanged();
                        listWebsite.setAdapter(adapter);

                        //Save to cache
                        Paper.book().write("cache", new Gson().toJson(response.body()));
                    }

                    @Override
                    public void onFailure(Call<WebSite> call, Throwable t) {

                    }
                });
            }
        }
        else   //If from Swipe to Refresh
        {
            dialog.show();
            //Fetch new data
            mService.getSources().enqueue(new Callback<WebSite>() {
                @Override
                public void onResponse(Call<WebSite> call, Response<WebSite> response) {
                    adapter = new ListSourceAdapter(getBaseContext(),response.body());
                    adapter.notifyDataSetChanged();
                    listWebsite.setAdapter(adapter);

                    //Save to cache
                    Paper.book().write("cache", new Gson().toJson(response.body()));

                    //Dismiss refresh progressing
                    swipeLayout.setRefreshing(false);
                }

                @Override
                public void onFailure(Call<WebSite> call, Throwable t) {

                }
            });

        }
    }

}

ListSourceAdapter.java

    class ListSourceViewHolder extends RecyclerView.ViewHolder
    implements View.OnClickListener
{
    ItemClickListener itemClickListener;

    TextView source_title;
    CircleImageView source_image;

    public ListSourceViewHolder(View itemView) {
        super(itemView);

        source_image = (CircleImageView) itemView.findViewById(R.id.source_image);
        source_title = (TextView) itemView.findViewById(R.id.source_name);
    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @Override
    public void onClick(View view) {
        itemClickListener.onClick(view,getAdapterPosition(),false);
    }
}

    public class ListSourceAdapter extends RecyclerView.Adapter<ListSourceViewHolder> {
        private Context context;
        private WebSite webSite;

        private FaviconGrabberService mService;

        public ListSourceAdapter(Context context, WebSite webSite) {
            this.context = context;
            this.webSite = webSite;

            mService = Common.getIconService();
        }

        @NonNull
        @Override
        public ListSourceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View itemView = inflater.inflate(R.layout.source_layout, parent, false);
            return new ListSourceViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(final ListSourceViewHolder holder, int position) {

            StringBuilder faviconAPI = new StringBuilder("https://favicongrabber.com/");
            faviconAPI.append(webSite.getSources().get(position).getUrl());

            mService.getIconUrl(faviconAPI.toString())
                    .enqueue(new Callback<FaviconGrabber>() {
                        @Override
                        public void onResponse(Call<FaviconGrabber> call, Response<FaviconGrabber> response) {
                            if(response.body().getIcons().size() > 0)
                            {
                                Picasso.with(context)
                                        .load(response.body().getIcons().get(0).getUrl())
                                        .into(holder.source_image);

                            }
                        }

                        @Override
                        public void onFailure(Call<FaviconGrabber> call, Throwable t) {

                        }
                    });

            holder.source_title.setText(webSite.getSources().get(position).getName());

            holder.setItemClickListener(new ItemClickListener() {
                @Override
                public void onClick(View view, int position, boolean isLongClick) {
                     //Implement part 2

                }
            });
        }

        @Override
        public int getItemCount() {
                return webSite.getSources().size();        //here I get a NullPointerException
        }

    }

I’m getting this error message by return webSite.getSources().size(); :

java.lang.NullPointerException: Attempt to invoke virtual method ‘java.util.List …Model.WebSite.getSources()’ on a null object reference at …Adapter.ListSourceAdapter.getItemCount(ListSourceAdapter.java:110)

I can give other part of project if you need, tnx!

Answer

The error is telling you that the object reference webSite is null. You need to check the process that is calling the ListSourceAdapter constructor to see what is causing it to send null to the constructor call.

We are here to answer your question about How do I fix this NullPointerException for webSite.getSources().size(); - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji