0

Stuck on this java.lang.NullPointerException: Attempt to invoke virtual method int java.util.ArrayList.size() on a null object reference. This above error has been resolved. But now the issue is: The array list that we assign to it from the MainActivity doesn't change our display when we setAdapter to our recycler view ,we just get an empty display i.e no data set was assigned to the adapter,how to rectify that

MainActivity.java

public class MainActivity extends AppCompatActivity {
ArrayList<News> arrayList;
RecyclerView recyclerView;
String abcnews="https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=e0322279ec2b4440b84cf4b9c8d2d348";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView=findViewById(R.id.rv);
    LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
    recyclerView.setLayoutManager(linearLayoutManager);
    OkHttpClient okHttpClient=new OkHttpClient();
    final Request request=new Request.Builder()
            .url(abcnews)
            .build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String string=response.body().string();
            try {
                Log.e("test","yolo");
                arrayList=jsonParse(string);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            final NewsAdapter newsAdapter=new NewsAdapter(MainActivity.this,arrayList);
            recyclerView.post(new Runnable() {
                @Override
                public void run() {
                    recyclerView.setAdapter(newsAdapter);

                }
            });
        }
    });
}
private ArrayList<News> jsonParse(String s)throws JSONException{
    ArrayList<News> list=new ArrayList<>();
    JSONObject jsonObject=new JSONObject(s);
    JSONArray jsonArray=jsonObject.getJSONArray("articles");
    for(int i=0;i<jsonArray.length();i++){
        JSONObject current=jsonArray.getJSONObject(i);
        String title=current.getString("title");
        String descrtiption=current.getString("description");
        String photo=current.getString("urlToImage");
        String more=current.getString("urt");
        News news=new News(title,descrtiption,photo,more);
        arrayList.add(news);
    }
    return list;
}

}

NewsAdapter.java

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsHolder> {
ArrayList<News> arrayList=null;
Context context;
NewsAdapter(Context c,ArrayList<News> list){
    this.context=c;
    this.arrayList=list;
}
class NewsHolder extends RecyclerView.ViewHolder {
    ImageView imageView;
    TextView title,description;
    public NewsHolder(View itemView) {
        super(itemView);
        title=itemView.findViewById(R.id.title);
        description=itemView.findViewById(R.id.description);
        imageView=itemView.findViewById(R.id.image);
    }
}

@Override
public NewsAdapter.NewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new NewsHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row,parent,false));
}

@Override
public void onBindViewHolder(NewsAdapter.NewsHolder holder, int position) {
    News news=arrayList.get(position);
    holder.title.setText(news.getTitle());
    holder.description.setText(news.getDescription());
    Picasso.with(context)
            .load(news.getPhoto())
            .error(R.mipmap.ic_launcher_round)
            .placeholder(R.mipmap.ic_launcher_round)
            .into(holder.imageView);
}

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

}

News.kt

data class News(val title:String,val description:String,val photo:String,val more:String)     

Error section in LogCat

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
                                                 at com.example.tanis.newsus.NewsAdapter.getItemCount(NewsAdapter.java:57)
                                                 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:16833)
                                                 at android.view.ViewGroup.layout(ViewGroup.java:5438)
                                                 at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
                                                 at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1732)
                                                 at android.widget.LinearLayout.onLayout(LinearLayout.java:1497)
                                                 at android.view.View.layout(View.java:16833)
                                                 at android.view.ViewGroup.layout(ViewGroup.java:5438)
                                                 at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                 at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                 at android.view.View.layout(View.java:16833)
                                                 at android.view.ViewGroup.layout(ViewGroup.java:5438)
                                                 at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:443)
                                                 at android.view.View.layout(View.java:16833)
                                                 at android.view.ViewGroup.layout(ViewGroup.java:5438)
                                                 at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                 at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                 at android.view.View.layout(View.java:16833)
                                                 at android.view.ViewGroup.layout(ViewGroup.java:5438)
                                                 at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
                                                 at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
                                                 at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
                                                 at android.view.View.layout(View.java:16833)
                                                 at android.view.ViewGroup.layout(ViewGroup.java:5438)
                                                 at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                 at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                 at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2680)
                                                 at android.view.View.layout(View.java:16833)
                                                 at android.view.ViewGroup.layout(ViewGroup.java:5438)
                                                 at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2469)
                                                 at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2126)
                                                 at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1228)
                                                 at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6523)
                                                 at android.view.Choreographer$CallbackRecord.run(Choreographer.java:919)
                                                 at android.view.Choreographer.doCallbacks(Choreographer.java:710)
                                                 at android.view.Choreographer.doFrame(Choreographer.java:645)
                                                 at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:905)
                                                 at android.os.Handler.handleCallback(Handler.java:739)
                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                 at android.os.Looper.loop(Looper.java:148)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5519)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Stuck on this for long time.

Warn section in LogCat This is the link

Thanks in advance!

  • 1
    because you passed arrayList is null. Please check why arrayList is null. In adapter you can use code in getCount: return null == arrayList? 0: arrayList.size(); – Brian Hoang Jan 19 '18 at 15:25
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Marek J Jan 19 '18 at 15:31
  • yes its null (on initialization) but we assign it some other value in constructor but somehow the array list that we assign to it doesn't change our display ,we just get an empty display i.e no data set was assigned to the adapter,how to rectify that – Tanishq Saluja Jan 19 '18 at 15:34
  • i have edited the question , you can see the new details now – Tanishq Saluja Jan 19 '18 at 15:58
  • ArrayList arrayList=new ArrayList(); check after adding this in adapter class. – Arora Jan 20 '18 at 12:11

2 Answers2

2

The crash is happening because you've initialised a null arrayList in MainActivity.java:

ArrayList<News> arrayList;

then tried to call .size() method on a null object in your NewsAdapter.java:

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

So change the getItemCount() function of your Adapter class to

@Override
public int getItemCount() {
    return arrayList != null ? arrayList.size() : 0;
}
HaroldHibari
  • 422
  • 3
  • 12
1

In your NewsAdapter.java

@Override
public int getItemCount() {
    if(arrayList != null)
       return arrayList.size();
    else
       return 0;
}
Yusuf Çağlar
  • 320
  • 2
  • 13