Search code examples
androidandroid-activityabstractradix

What is the correct way to define a BaseActivity


This Question i specific to Android and the use of a Base Activity that can be extended by all other Activities. In general w.r.t Java i understand the use and functioning of abstract classes. I my case i have a Base Activity with some common constants ,functions and implements some Interfaces. My Question is should it be abstract or can i leave it as a normal Activity. Is there a specific reason for it to be abstract.

//Standard BaseActivity 
public abstract class BaseActivity extends Activity {
   //common code
}

//Usage 
public class MyActivity extends BaseActivity {
}

This also seems to work if i defined BaseActivity as follows

//Non Abstract Class
public class BaseActivity extends Activity {
}

Hence the question is there a specific reason to use abstract. In both cases i dont define the BaseActivity in Manifest.


Solution

  • You can refer the following way for defining a BaseActivity.

    It’s always been a good idea to make a baseActivity in android project.

    What, I am suggesting is to create an activity from android.app.Activity called baseActivity and make the 3 custom activity to extend from baseActivity.

    For example,

    public abstract class MyAppBaseActivity extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
    }
    

    And your custom activity

    public class MyCustomActivity extends MyAppBaseActivity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    }
    

    Notice that, MyAppBaseActivity is an abstract class. The reason is, we are not going to instantiate it. That’s why you don’t need to add the MyAppBaseActivity class in AndroidManifest.xml file.

    Now the question is, why would you do that? Means, why you need to make an baseActivity class and then make your other activities as a subclass of it?

    Well, here are few very generic reasons

    1. You can avoid code duplication of you application wise common ui tasks. Suppose you want to show progressDialog in different activities. Just write code to show a progressDialog in your baseActivity and call that method from other activity.

    2. Your application menu should be consistent across different application. For example, you have a settings screen. Option menu is containing the navigation to settings screen. You should display the settings throughout the application, means regardless of activity. User want to access the settings screen from anywhere in application. This feature can be easily achieved, but you have to override onCreateOptionsMenu in each of your activity or, you can override it once in your baseActivity.