no news no news - 3 months ago 25
Android Question

getIntent().getSerializableExtra is null

I have a

POJO
class implements
Serializable

and I want to transfer an object of this class to another
activity
with a help
Intent
and
Bundle
.
I checked the object before the transfer, it is not null. (Correctly get one of attributes)

put:

private void onFriendClick(FriendHolder holder, int position) {
Intent intent = new Intent(context, ProfileActivity.class);
Bundle extra = new Bundle();
extra.putSerializable(Consts.KEY_USER_JSON, friendList.get(position));
intent.putExtra(Consts.KEY_USER_JSON, extra);
Log.e("onFriendClick", String.valueOf(friendList.get(position).getName()));
context.startActivity(intent);
}


get from another activity:

private void setupProfile() {
Bundle extras = getIntent().getExtras();
if (extras != null) {
profile = (ProfileDTO) getIntent().getSerializableExtra(Consts.KEY_USER_JSON);
Log.e("onFriendClick", String.valueOf(profile.getName()));//NPE this
} else profile = user.getProfile();
}



Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'java.lang.String
ru.techmas.getmeet.api.models.ProfileDTO.getName()' on a null object
reference
at ru.techmas.getmeet.activities.ProfileActivity.setupJsonProfile(ProfileActivity.java:103)

Answer

You don't need to create a Bundle. Try doing:

private void onFriendClick(FriendHolder holder, int position) {
    Intent intent = new Intent(context, ProfileActivity.class);
    intent.putExtra(Consts.KEY_USER_JSON,  friendList.get(position));
    Log.e("onFriendClick", String.valueOf(friendList.get(position).getName()));
    context.startActivity(intent);
}

private void setupProfile() {
    if (getIntent().getSerializableExtra(Consts.KEY_USER_JSON) != null) {
        profile = (ProfileDTO) getIntent().getSerializableExtra(Consts.KEY_USER_JSON); 
        Log.e("onFriendClick", String.valueOf(profile.getName()));//NPE this
    } else {
        profile = user.getProfile();
    }
}

But if still want to use the Bundle, you should replace in the code that you posted:

profile = (ProfileDTO) getIntent().getSerializableExtra(Consts.KEY_USER_JSON);

By:

profile = (ProfileDTO) extras.getSerializableExtra(Consts.KEY_USER_JSON);