1

I have declared a global boolean variable in my MainActivity class and set its value to true:

public class MainActivity extends AppCompatActivity {
    public boolean inAppTextIntegration = true;
    //onCreate method and stuff

I have 11 more activities in my application. And, in every activity, I'm overriding the attachBaseContext method as:

@Override
protected void attachBaseContext(Context base) {
    if(inAppTextIntegration) {
        super.attachBaseContext(ZeTarget.attachBaseContext(base, this));
    }
    else {
        super.attachBaseContext(base);
    }
}

I have declared the boolean variable inAppTextIntegration in all my activities. Now the problem part: Since I'm doing the same thing in all the activities, is it possible to reduce the code?

Currently, I'm using SharedPreferences to store the value of inAppTextIntegration in my MainActivity, and then accessing that value in other activities because I don't want to set this value manually in all the activities.

Again, the problem that I face is in all other activities, else part of the overriding method is being executed (I'm initializing inAppTextIntegration variable in onCreate method of all other activities. Doing it outside the onCreate method causes null pointer exception as the context is not set yet).

So, how do I control the override to attachBaseContext at all other activities just by changing one variable in the MainActivity?

Akeshwar Jha
  • 4,516
  • 8
  • 52
  • 91
  • 3
    for the first part, code reduction and factorization, define a superclass that does that and that all your activies extend. For the second part, init the value of your variable directly in `attachBaseContext` since that's where you use it. Use the `base` context to access your prefs – njzk2 Jan 07 '16 at 21:14
  • Thanks for the response. But all my activities already extend AppCompatActivity. Is there a workaround? – Akeshwar Jha Jan 08 '16 at 08:51
  • You can create a custom class that extends AppCompatActivity and have all your Activities extend your custom class – Björn Kechel Jan 08 '16 at 09:49

1 Answers1

3

(i) Create a class which contains all the common methods that all your activities will have.

(ii) Make this class extend Activity, AppCompatActivity or whatever all your activities are extending.

(iii) Make all your activities extend this class instead of what they are already extending.

You're done :)