Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Attempt to invoke virtual method '...' on a null object reference error

Hi. When i start the app while my network is off, i get an app crash when i click on the 7 day forecast button. i get the above error on the logs. please advise where i am am getting it wrong.

Seth Kroger
Seth Kroger
56,409 Points

We need to see your code and the line that was causing the null reference to help.

this is where the roor link is pointing me to

@OnClick(R.id.eventsButton) public void startEventsActivity(View view){ Intent intent = new Intent(this, EventsActivity.class); intent.putExtra(EVENT_UNIFIER, mUnifier.getEventUnified()); startActivity(intent); }

1 Answer

Seth Kroger
Seth Kroger
56,409 Points

The most likely issue is mUnifier isn't initialized. Since you say this happens when your network is off, I'm guessing you are getting data from the net and initializing it when the response comes in. I'd recommend wrapping the code for starting the new activity in a if(mUnifier != null) statement. You can handle the else part however you like.

thanks a lot its worked, i also did the following on the new activity:

Intent intent = getIntent(); if(intent.getParcelableArrayExtra(MainActivity.EVENT_UNIFIER) != null){ Parcelable[] parcelables = intent.getParcelableArrayExtra(MainActivity.EVENT_UNIFIER); int count = parcelables.length; if(count != 0){ mEvents = Arrays.copyOf(parcelables, count, Event[].class); EventAdapter adapter = new EventAdapter(this, mEvents); setListAdapter(adapter); }else{ EventAdapter adapter = new EventAdapter(this, mEvents); setListAdapter(adapter); } }

just to make sure that if a null is passed to the new activity it does not cause an error on the adapter