Skip to content
Advertisement

Android intent returning null when moving back and forth of activities

I have an app where a user can create/login an account, when the user logs in, I pass their valid email as an intent to the main/landing activity .

I also have another activity for the user profile, from which I pass the intent from the landing activity (the user email).

With the user email I created queries to get all the user projects (it’s a PM tool kind of thing) – in my landing activity i have a fragment also where I use these queries based on the user email.

In my user profile activity i also created queries to get the users details (name, email etc) to show in their profile where they can change it etc.

========

The issue is, initially when I log in with valid details and I’m brought to the landing activity, I get the users projects which is great, I can also navigate to the users profile activity and I get the users details which is what I want.

Then when I move back to the landing activity my intent (users emaill) which was passed from the Login activity is no longer valid, so I do not get any results from my DB queries and when I move back to the profile activity the intent is null so i can’t get the current user anymore.

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.ppmtoolmobile.model.User.getFirstName()' on a null object reference

I wanted some advice on how to handle this to avoid getting NPE when moving back and forth.


I removed the variables for components to make it more readable, but I have initialized them all etc..

Landing Activity / ProjectActivity.java

JavaScript

ProfileActivity.java

JavaScript

DaoHelper.java methods

JavaScript

Initial state after logging in State when moving to profile activity then back to Project activity

Advertisement

Answer

The problem here is, your are starting another ProjectActivity instance in your ProfileActivity’s onNavigationItemSelected listener of bottomNavView, which has no arguments (startActivity(new Intent(getApplicationContext(), ProjectActivity.class));)
That’s why in your second instance of ProjectActivity, it has no value for parameter authenticatedUser and returning empty string.

You can fix this by modifying code of bottomNavView’s onNavigationItemSelected listener in your ProfileActivity class. Replace your switch case logic for id R.id.nav_home like below in ProfileActivity class

JavaScript

Or, if you want to keep multiple instance of same activity (ProjectActivity and ProfileActivity), then you can add parameter to Intent instance in ProfileActivity’s bottomNavView’s itemSelectedListener. In that case, your code would become something like below

JavaScript
Advertisement