Question

I am searching for an elegant solution/pattern for this problem ( pseudo-code ):

public class LoggedInActivity extends Activity {
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isUserLoggedIn()) {
         finish();
         startActivity(getLoginActivity());
        }
    }

    ...
}


class MainActivity extends LoggedInActivity {
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       codeThatShouldNotBeExecutedWithoutUser();
    }
}

I am searching for a way to not touch every child-class of LoggedInActivity and do a check there - In an Ideal world I can solve this problem in LoggedInActivity completely - but I do not see a way yet.

Was it helpful?

Solution

A good way to solve this is:

  1. Make LoggedInActivity an abstract class.
  2. Add to it an abstract method:

    abstract void codeThatShouldNotBeExecutedWithoutUser();

  3. Change all subclasses to implement (and override) codeThatShouldNotBeExecutedWithoutUser(). If they already implement that method, you should at least add the @Override annotation to make it clear that the method is being overridden.

  4. Remove the calls to codeThatShouldNotBeExecutedWithoutUser() from all the subclasses.
  5. Change LoggedInActivity.onCreate() to call codeThatShouldNotBeExecutedWithoutUser() if and only if the user is logged in:

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isUserLoggedIn()) {
           finish();
           startActivity(getLoginActivity());
        } else {
           codeThatShouldNotBeExecutedWithoutUser();
        }
    }
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top