buggydroid
buggydroid

Reputation: 1870

Null pointer in putExtras

I have some trouble with putExtras to an intent. Could you please review my code?

 public void onSelectCategory(View v) {
    int category = Integer.parseInt((String) v.getTag());
    Intent intent = new Intent(HomeActivity.this, ListActivity.class);
    intent.putExtra("EXT_CATEGORY", category);
    startActivity(intent);
}

And in the ListActivity, I'm doing the following..

public static final String EXT_CATEGORY = "category";
int category = getIntent().getExtras().getInt(EXT_CATEGORY);

Upvotes: 0

Views: 238

Answers (3)

Simon Schubert
Simon Schubert

Reputation: 2028

You did several mistakes, here is a overworker version of your code.

 public void onSelectCategory(View v) {
    int category = Integer.parseInt((String) v.getTag());
    Intent intent = new Intent(HomeActivity.this, ListActivity.class);
    intent.putExtra(EXT_CATEGORY, category);
    startActivity(intent);
}

int defaultCat = -1;
public static final String EXT_CATEGORY = "category";
int category = getIntent().getIntExtra(EXT_CATEGORY,defaultCat); // Use default int if there is no extra

Upvotes: 1

Evos
Evos

Reputation: 3915

You should use this to get you info, not getExtras() :

int category = getIntent().getIntExtra("EXT_CATEGORY");

getExtras() returns additional Bundle of data. You need only one integer.

Upvotes: 0

Deepanker Chaudhary
Deepanker Chaudhary

Reputation: 1704

From this line

         intent.putExtra("EXT_CATEGORY", category);

in your another activity String name should be same means:--

         public static final String EXT_CATEGORY = "EXT_CATEGORY";

Upvotes: 5

Related Questions