views:

52

answers:

5

I have a menu and would like to open a new Activity when the user clicks on the menu item:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.add_symbol:
           System.out.println("ADD SYMBOL CLICKED!");
           Intent myIntent = new Intent(this.getContext(), AddStocksActivity.class);
           startActivityForResult(myIntent, 0);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

I'm not sure how to create my Intent properly

Compiler Error:

The method getContext() is undefined for the type Main
A: 

Change this.getContext() to this.getApplicationContext()

You are trying to call a method that doesn't exist.

smith324
A: 

In your activity class do

Context mContext;

In your onCreate() do

mContext = this

then in your Options thing, do

Intent myIntent = new Intent(this.getContext(), AddStocksActivity.class);
Falmarri
+1  A: 

Since Main extends Activity (which extends Context), you can do:

Intent myIntent = new Intent(this, AddStocksActivity.class)
Erich Douglass
Oh, yeah, if you have to do this in an anonymous inner class you can follow my answer. Or you can do `MyActivity.this`
Falmarri
this is a good spot!
Jorgesys
A: 
 Intent myIntent = new Intent(getApplicationContext(), AddStocksActivity.class);

or

Intent myIntent = new Intent(this, AddStocksActivity.class)
Jorgesys
A: 

this is what I do

public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options_menu, menu);

    MenuItem item1 = menu.findItem(R.id.menu_item_a);
    Intent intent1 = new Intent(this, A.class);
    item1.setIntent(intent1);

    MenuItem item2 = menu.findItem(R.id.menu_item_b);
    Intent intent2 = new Intent(this, B.class);
    item2.setIntent(intent2);

}

hope it helps

achie
you can use YourClassName.this instead of just this
achie