sss
sss

Reputation: 717

Error when starting new activity from menu click

I am new to android development so there is probably something simple that is wrong. If you need any more info I will be glad to give that to you. Thanks in advance.

I am trying to add a button in my navdrawer.class. This is what I have.

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    switch (item.getItemId()) {
        case R.id.new_account:
            Intent intent = new Intent(this, AddAccountActivity.class);
            this.startActivity(intent);
            break;

        }
        return super.onOptionsItemSelected(item);
    }

}

I get an error.

Upvotes: 2

Views: 53

Answers (3)

Jorgesys
Jorgesys

Reputation: 126523

since you´re into a fragment you must use:

Intent intent = new Intent(getActivity(), AddAccountActivity.class);

or

Intent intent = new Intent(getActivity().getApplicationContext(), AddAccountActivity.class);

for example see the context used in your Toast (getActivity())

Toast.makeText(getActivity(), "This Will Create  A New Account.", Toast.LENGTH_SHORT).show();

Upvotes: 2

danijoo
danijoo

Reputation: 2843

Am I right that this is the fragment instance? If this is the case, thats your problem. The intent constructor needs a context and an activity class to work.

Fragment does not inherit from context. You can get the underlying activity with the getActivity() method.

try this:

Intent intent = new Intent(getActivity(), AddAccountActivity.class);

Upvotes: 1

glyvox
glyvox

Reputation: 58099

You should write

Intent intent = new Intent(AddAccountActivity.this, AddAccountActivity.class);

instead of

Intent intent = new Intent(this, AddAccountActivity.class);

Upvotes: 1

Related Questions