Android: using getIntent () only inside onCreate?

In Android (targeting API 14-16) I have MainActivity and NextActivity . It's easy to use intentions to start NextActivity from MainActivity if the getIntent() method is called inside the onCreate() NextActivity :

 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int data = 7; ... Intent intent = new Intent(this, NextActivity.class); intent.putExtra("data", data); startActivity(intent); } } public class NextActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final int data = this.getIntent().getIntExtra("data", 7); ... } ... } 

However, since the data field is used inside an anonymous ("internal") class in NextActivity , I have to declare it final .

I would prefer not to declare final fields, and usually I can avoid this by declaring them at the beginning of the class, before starting onCreate() . But for some reason, the application crashes when NextActivity starts if the getIntent() statement appears (without the final keyword) outside of onCreate() .

Any idea why?

+7
source share
2 answers

You cannot getIntent() to onCreate() - there simply is no Intent available at this point. I believe the same is true for everything that Context requires.

Your anonymous inner class can still call getIntent() , so you don't need to declare this as a variable at all.

+9
source

According to your question, I understand that you do not want to declare the data as final in the next step. Then you cannot try it. /

 public class NextActivity extends Activity { int data=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); data = this.getIntent().getIntExtra("data", 7); ... } ... } 

Try it...

+1
source

All Articles