1

I am creating an abstract base class to keep my navigation drawer code in one place and want to implement an onClickListener on my app title (defined in the toolbar) to start my launch activity

I am using the following code :

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.toolbar_title:
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);
            return;
    }
}

The app works properly, but I read somewhere that one must not use the Application context to start new activities. However, android studio doesn't let me use any other context apart from getApplicationContext and getBaseContext, maybe because this class is abstract.

Which context should I use then?

sudshekhar
  • 1,576
  • 3
  • 18
  • 31

2 Answers2

2

Well, one of the ways can be: You can define an abstract method in your BaseActivity class:

abstract void launchMainActivity();

And call this method in your click listener:

@Override 
public void onClick(View view) {
    switch (view.getId()){
        case R.id.toolbar_title:
            launchMainActivity();
            return; 
    } 
} 

The sub-classes can then implement this method as:

@Override
void launchMainActivity() {
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
}
Shaishav
  • 5,282
  • 2
  • 22
  • 41
  • Thanks I like your approach too but I chose the other answer because this approach still requires an implementation in all the derived classes (thus kind of violates DRY). – sudshekhar Aug 08 '16 at 03:17
  • @sudshekhar alright man, but isn't it what you started with in the first place? – Shaishav Aug 08 '16 at 03:44
2

Have a look at Context.getApplicationContext() and ContextWrapper.getBaseContext(). Both have in common to be defined on a context instance. In your case it's even an Activity.

So you could even use this as a context to start your MainActivity. This is even better, because with any other context type you' have to include the flag FLAG_ACTIVITY_NEW_TASK to start a new activity.

If you get errors by using this for a context, it's because you define your OnClickListener as anonymous inner class which of course isn't a context. For that you'd have to write MyBaseActivity.this instead. This references the outer class instance.

tynn
  • 38,113
  • 8
  • 108
  • 143
  • Hey, one question : `this` in the base class will refer to the context of the currently running activity? As in the output of `this` or `MyBaseActivity.this` will be same as calling getContext in that (derived) activity? – sudshekhar Aug 07 '16 at 20:36
  • @sudshekhar There's nothing like `getContext()`. But `this` always refers to the instance of an object. This would just be your running activity. – tynn Aug 07 '16 at 20:56