Question

So I was trying to make a menu in an application that has a single item. Clicking this menu item takes you to another activity. So basically I'm starting a sub-activity on having that menu item clicked.

The problem is here that I have to specify my intent in the onCreate() method of my main activity, but I need this intent in my onOptionItemSelected() method which is outside the onCreate() method. How do i do this? My onCreate() method:

public void onCreate(Bundle savedInstanceState) { 
   Intent myIntent=new Intent(mainActivity.this,secondActivityt.class);
} 

My onOptionsItemSelected() method:

public boolean onOptionsItemSelected(MenuItem item){
   if(item.getItemId()==R.id.aboutbtn){
      startActivity(myIntent);
}

So here I'm unable to access myIntent. Is there anyway I can declare the intent outside the onCreate method and still make the program work, or anyway I can access the intent outside the onCreate method?

Was it helpful?

Solution

should be pretty easy, just declare a private class variable and store your intent in that like

public class MyActivity extends Activity{
   private Intent myIntent;

   public void onCreate(...){
      ...
      myIntent = new Intent(...);
   }


   public boolean onOptionsItemSelected(MenuItem item){
      ...
      //use the myIntent here
   }

}

I didn't try it out now, but I don't see any reason why this should not work, unless I didn't clearly understand your issue :)

Just as a sidenote. You maybe should also give a look at the Activity lifecycle, basically which event (onCreate, onResume, onStart, onDestroy,...) is fired when. The following figure taken from Android Developers describes it best: enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top