Understanding Base of Activities and Fragments
Posted By : Karan Jeet Singh | 04-Sep-2019
If you are a beginner to Android Development, then I am sure you must have tried something new on your own and stumbled upon a few mistakes in the way. And having said that, this blog assumes that you are familiar with Android App Development UI building blocks such as activities, fragments, and views.
Most of the newbies in Android App Development face the problem of accessing the resources, common objects and methods etc, especially in fragments. The code to just display a toast in your app requires a long line to written manually which can be taken care off just by a method. And keeping a consistent state of Shared Preferences is also a pain in the back since accessing it on and off in every file not only increases the line size but increases the boilerplate code. The sound goal is to reduce the number of lines and make our code look cleaner in every way possible so that we don’t get ambiguous just by looking at our own boilerplate code in numerous files.
All the mentioned problems can be mitigated really swiftly with a rather simple solution of placing objects and methods a custom abstract base class that inherits or extends an AppCompatActivity. The same can be done for a Fragment. This small code snippet will provide you an overview as to how we can common resources and then use them by extending the base activity class to our own class.
Here is another code excerpt to perform the same for Fragment. Except here we can rely on the BaseActivity instance to call its methods.
As an added measure we can also make our app log out in case of session expiration if the Base of Activities and Fragments can receive the error response after the API is done receiving.
Placing common methods and objects in the base is a good practice to build the core of the application. It should be exercised more and more.