尝试在null对象上调用接口方法'int java.util.List.size()'如何解决它? [重复]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了尝试在null对象上调用接口方法'int java.util.List.size()'如何解决它? [重复]相关的知识,希望对你有一定的参考价值。

这个问题在这里已有答案:

错误日志 -

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                          at in.hareshsaliya.itijobs.Adapter.ListSourceAdapter.getItemCount(ListSourceAdapter.java:115)
                          at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3603)
                          at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3408)
                          at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3962)
                          at android.view.View.layout(View.java:17953)
                          at android.view.ViewGroup.layout(ViewGroup.java:5717)
                          at android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:610)
                          at android.view.View.layout(View.java:17953)
                          at android.view.ViewGroup.layout(ViewGroup.java:5717)
                          at android.widget.FrameLayout.layoutChildren(FrameLayout.java:383)
                          at android.widget.FrameLayout.onLayout(FrameLayout.java:321)
                          at android.view.View.layout(View.java:17953)
                          at android.view.ViewGroup.layout(ViewGroup.java:5717)
                          at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1982)
                          at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1826)
                          at android.widget.LinearLayout.onLayout(LinearLayout.java:1735)
                          at android.view.View.layout(View.java:17953)
                          at android.view.ViewGroup.layout(ViewGroup.java:5717)
                          at android.widget.FrameLayout.layoutChildren(FrameLayout.java:383)
                          at android.widget.FrameLayout.onLayout(FrameLayout.java:321)
                          at android.view.View.layout(View.java:17953)
                          at android.view.ViewGroup.layout(ViewGroup.java:5717)
                          at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1982)
                          at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1826)
                          at android.widget.LinearLayout.onLayout(LinearLayout.java:1735)
                          at android.view.View.layout(View.java:17953)
                          at android.view.ViewGroup.layout(ViewGroup.java:5717)
                          at android.widget.FrameLayout.layoutChildren(FrameLayout.java:383)
                          at android.widget.FrameLayout.onLayout(FrameLayout.java:321)
                          at com.android.internal.policy.DecorView.onLayout(DecorView.java:753)
                          at android.view.View.layout(View.java:17953)
                          at android.view.ViewGroup.layout(ViewGroup.java:5717)
                          at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2715)
                          at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2383)
                          at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1470)
                          at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7001)
                          at android.view.Choreographer$CallbackRecord.run(Choreographer.java:910)
                          at android.view.Choreographer.doCallbacks(Choreographer.java:712)
                          at android.view.Choreographer.doFrame(Choreographer.java:646)
                          at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:896)
                          at android.os.Handler.handleCallback(Handler.java:836)
                          at android.os.Handler.dispatchMessage(Handler.java:103)
                          at android.os.Looper.loop(Looper.java:203)
                          at android.app.ActivityThread.main(ActivityThread.java:6293)
                          at java.lang.reflect.Method.invoke(Native Method)
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1084)
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:945)

代码 -

这是我的适配器代码**

@Override
    public int getItemCount() {
        return webSite.getSources().size();
    }

这是问题**

 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 IconBetterIdeaService mService;

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

        mService = Common.getIconService();
    }

    @Override
    public ListSourceViewHolder onCreateViewHolder(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 iconBetterAPI = new StringBuilder("https://icons.better-idea.org/allicons.json?url=");
        iconBetterAPI.append(webSite.getSources().get(position).getUrl());

        mService.getIconUrl(iconBetterAPI.toString())
                .enqueue(new Callback<IconBetterIdea>() {
                    @Override
                    public void onResponse(Call<IconBetterIdea> call, Response<IconBetterIdea> 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<IconBetterIdea> call, Throwable t) {

                    }
                });


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

        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onClick(View view, int postion, boolean isLongClick) {

            }
        });
    }

    @Override
    public int getItemCount() {
        return webSite.getSources().size();
    }
}

初始化并调用适配器

`

RecyclerView listWebsite;
    RecyclerView.LayoutManager layoutManager;
    NewsService mService;
    ListSourceAdapter adapter;
    android.app.AlertDialog dialog;
    SwipeRefreshLayout swipeRefreshLayout;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news);


    Paper.init(this);

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

    mService = Common.getNewsService();

    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);
            adapter = new ListSourceAdapter(getBaseContext(),webSite);
            adapter.notifyDataSetChanged();
            listWebsite.setAdapter(adapter);

        } else
        {
            dialog.show();
            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);

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

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

                }
            });
        }

    }
    else
    {

        dialog.show();
        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);

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

                swipeRefreshLayout.setRefreshing(false);
            }

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

            }
        });
    }

}

`

答案

使用初始化创建List引用,如下所示

List list = new ArrayList();

如果要更新现有使用以下内容

list.clear();
list.addAll(newList);

而已。如果没有修复,请先发布您的代码。

另一答案

您没有将数组列表传递给此Adapter类。您是否可以期望它不会给出空指针异常。

将数组列表初始化为:

ArrayList list=new ArrayList();

public ListSourceAdapter(Context context, ArrayList list) {
    this.context = context;
    this.list = list;

    mService = Common.getIconService();
}

如果是回收者视图,请将此适配器称为 - :

adapter=new ListSourceAdapter(context,list);
recyclerview.setAdapter(adapter);

以上是关于尝试在null对象上调用接口方法'int java.util.List.size()'如何解决它? [重复]的主要内容,如果未能解决你的问题,请参考以下文章

错误:java.lang.NullPointerException:尝试在空对象引用上调用接口方法“int java.util.List.size()”

引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'int org.json.JSONArray.length()'[duplicate]

获取'无法在grails Spring安全性休息中调用null对象上的方法loadUserByUsername()'

尝试在空对象引用上调用虚方法'double android.location.Location.getLatitude()'[duplicate]

原因:java.lang.NullPointerException:尝试在空对象引用上调用接口方法

NullPointerException:在null对象引用上使用ActionBar.setDisplayHomeAsUpEnabled(boolean)'