-1

I'm new at programming and I've been dealing for a couple of hours with a null pointer exception error.

I have one Activity in the project with a Navigation View menu populated with RSS Feeds Categories obtained from a JSON file. When I click a category, a Fragment ("FragmentRSSFeedContainer") gets loaded. This Fragments loads a ViewPager where each page contains a RecyclerView with news from a RSSFeed.json file.

When I click one item of the Recycler view is where the nullpointer error occurs. This should .replace current "FragmentRSSFeedContainer" and load a "FragmentRSSNewsContainer". This Fragment will load another ViewPager with the info of the selected news, and each page will have a different news of the selected RSSFeed. When I had all the news hardcoded it was working OK. I have issues with a inner class variable, I believe. I detail more about it below.

This is the error:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String ar.com.thomas.mydailynews.model.RSSFeed.getTitle()' on a null object reference
at ar.com.thomas.mydailynews.view.MainActivity.getNotifications(MainActivity.java:47) at ar.com.thomas.mydailynews.view.RSSFeedsActivity.FragmentRSSFeedViewPager$1$1.onClick(FragmentRSSFeedViewPager.java:63) at ar.com.thomas.mydailynews.model.NewsAdapter.onClick(NewsAdapter.java:53)

Here's the MainActivity method that calls the error:

    @Override
public void getNotifications(News selectedNews, Integer newsPosition, List<News>newsList) {

    FragmentNewsContainer fragmentNewsContainer = new FragmentNewsContainer();
    Bundle arguments = new Bundle();
    arguments.putString(FragmentNewsContainer.NEWS_TITLE, selectedNews.getTitle());
    arguments.putString(FragmentNewsContainer.RSS_SOURCE, newsList.get(newsPosition).getRssFeed().getTitle());
    arguments.putInt(FragmentNewsContainer.POSITION, newsPosition);

    fragmentNewsContainer.setArguments(arguments);
    getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.fragment_container, fragmentNewsContainer).commit();
    setTitle(selectedNews.getRssFeed().getTitle());
}

Here's the Fragment where the error is produced. The conflict is in the line "fragmentCalls.getNotifications(itemClicked,itemPosition,newsList". The newsList, for some reason I don't understand, is null. Variable "result" is not null.

public class FragmentRSSFeedViewPager extends Fragment {

public static final String RSS_FEED = "RSSFeed";
public static final String RSS_FEED_LINK = "rssFeedLink";
private RecyclerView recyclerView;
private String rssFeed;
private FragmentCalls fragmentCalls;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.fragment_rssfeed_viewpager,container,false);
    NewsController newsController = new NewsController();

    Bundle bundle = getArguments();
    rssFeed = bundle.getString(RSS_FEED);
    String rssFeedLink = bundle.getString(RSS_FEED_LINK);


    newsController.getNews(new ResultListener<List<News>>() {
        @Override
        public void finish(List<News> result) {

            final List<News> newsList = result;


            NewsAdapter newsAdapter = new NewsAdapter(result);
            newsAdapter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Integer itemPosition = recyclerView.getChildAdapterPosition(v);
                    News itemClicked = newsList.get(itemPosition);
                    fragmentCalls.getNotifications(itemClicked,itemPosition,newsList);
                }
            });

            recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
            recyclerView.setHasFixedSize(true);
            recyclerView.setAdapter(newsAdapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        }
    }, rssFeedLink);

    return view;
}

public static FragmentRSSFeedViewPager generateFragment (RSSFeed rssFeed){

    FragmentRSSFeedViewPager fragmentRSSFeedViewPager = new FragmentRSSFeedViewPager();

    Bundle arguments = new Bundle();
    arguments.putString(RSS_FEED, rssFeed.getTitle());
    arguments.putString(RSS_FEED_LINK, rssFeed.getFeedLink());
    fragmentRSSFeedViewPager.setArguments(arguments);
    fragmentRSSFeedViewPager.setRssFeed(rssFeed.getTitle());
    return fragmentRSSFeedViewPager;
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    fragmentCalls = (FragmentCalls) activity;
}

public String getRssFeed() {
    return rssFeed;
}

public void setRssFeed(String rssFeed) {
    this.rssFeed = rssFeed;
}

public interface FragmentCalls{
    public void getNotifications(News selectedNews, Integer newsPosition, List<News> newsList);
}

And finally the @Override onClick method on the Adapter

    @Override
public void onClick(View v) {
    if(listener !=null){
        listener.onClick(v);
    }
}

Is there anything else I could upload here to see where the error might be? Or any idea where could I be failing?

halfer
  • 19,824
  • 17
  • 99
  • 186
Joey
  • 43
  • 8
  • 7
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Harshad Pansuriya Jun 28 '16 at 05:02
  • fragmentCalls is null when you are trying to onClick – Sathish Kumar J Jun 28 '16 at 05:06
  • why not make `result` as final and use it, instead of creating new `newsList`? – mgcaguioa Jun 28 '16 at 05:24
  • Ironman I appreciate the input but that post didn't help me nor is a duplicate. Thanks anyway. Sathish, indeed, that's where one of the problems was. @mgcaguioa, yes! I had it originally as you said, but started trying different things and made a mess out of everything. Thanks for the input, I'll update my code now to avoid the newsList variable! Thank you!! – Joey Jun 28 '16 at 06:13
  • Can you add some detail (in the comments) as to why this is not a duplicate of the canonical NPE question? I am not a Java dev so am not voting to close, but it may be helpful for the long term if readers can understand _why_ it is not a duplicate. Someone may of course try to close it again. – halfer Nov 02 '16 at 11:05

1 Answers1

1

You need to initialize the list first and then you can use addAll() to add whole other list to your list. So edit your code as below:

      newsController.getNews(new ResultListener<List<News>>() {
    @Override
    public void finish(List<News> result) {

        final List<News> newsList = new ArrayList<News>();
        newsList.addAll(result);

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        NewsAdapter newsAdapter = new NewsAdapter(result);
        recyclerView.setAdapter(newsAdapter);
        newsAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer itemPosition = recyclerView.getChildAdapterPosition(v);
                News itemClicked = newsList.get(itemPosition);
                fragmentCalls.getNotifications(itemClicked,itemPosition,newsList);
            }
        });


    }
}, rssFeedLink);
Dhruvi
  • 1,971
  • 2
  • 10
  • 18
  • Hello Dvr. I did as you said, but I keep having error at same place. Do you think the error could be in another place? The "result" variable was working, I tested it with a toast. edit; thank you for taking the time!! Also, I just tried to doublecheck and result isn't null. tested "String.valueOF(result.size())" and it works. – Joey Jun 28 '16 at 05:24
  • Please check the edited code, even change getContext() to getActivity() while initializing the linearlayoutmanager. – Dhruvi Jun 28 '16 at 05:28
  • Also initialize fragmentCalls on which you are trying to trigger onClick event. – Dhruvi Jun 28 '16 at 05:40
  • Thank you again for taking the time to read and help me out. I copy-pasted and got same error. I partially "fixed" the error by changing some methods, and started following a path of nullpointers all over the place, until I got to another class that also uses the .getNews. I fixed the code there (similarly) just like you told me, and now I'm free of nullpointers. Thanks a lot, again, for helping me out on this. Without your aid I would've lost another day and wouldn't be able to fix this. I'm going to mark this as correct the correct answer. Thank you again!!!!!!!! – Joey Jun 28 '16 at 05:57