user3718908x100
user3718908x100

Reputation: 8519

Passing values between activities properly

Hello I am new to android and I have a problem I do not know how to solve. I have 3 activities, ActivityMain, ActivityA and ActivityB. ActivityMain is the start activity. From ActivityMain the user can move to ActivityA, when they do that a value is passed from ActivityMain to ActivityA like this:

Intent i = new Intent(context, ActivityA.class);
i.putExtra("eventId", eventId);
startActivity(i);

And in my onCreate method of ActivityA I have an init() function that gets that value like this:

public void init() {
  this.eventId = Integer.parseInt(getIntent().getExtras().get("eventId").toString());
}

Now this is my issue, for some reason when I navigate from ActivityA to ActivityB then I click back my app stops working a Null Pointer Exception is thrown at the above line of code.

Upvotes: 1

Views: 74

Answers (3)

PEHLAJ
PEHLAJ

Reputation: 10126

The problem is you are passing data to intent directly and trying to access it from intent bundle but not intent. Use intent.getIntExtra("eventId")

Replace:

Integer.parseInt(getIntent().getExtras().get("eventId").toString());

With

eventId = getIntent().getIntExtra("eventId");

Secondly if you eventId is integer then use intent.getIntExtra, if eventId is string then use intent.getStringExtra

Upvotes: 0

Masum
Masum

Reputation: 4969

if you pass integer try something like this

this.eventId = getIntent().getExtras().getInt("eventId");    

or if you pass string. try this

this.eventId = Integer.parseInt(getIntent().getExtras().getString("eventId"));

Upvotes: 1

takrishna
takrishna

Reputation: 5002

Cache the data from "Extra" to a variable - use onResume() method in your activity to set any configurations.

Upvotes: 2

Related Questions