Understanding Base of Activities and Fragments

Posted By : Karan Jeet Singh | 04-Sep-2019

Introduction
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.


Problem
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.


Solution
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.

public abstract class BaseActivity extends AppCompatActivity {
public SessionPreference preference;
private Dialog dialog;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    preference = new SessionPreference(this);
}

public void showProgressBar() {
hideProgressBar();
progressDialog = UiUtils.showProgressBar(this);
progressDialog.show();
}

public void hideProgressBar() {
    if (progressDialog != null && progressDialog.isShowing()) {
        progressDialog.cancel();
    }
}

public void showToast(String message, int length){
   if (message != null) {
   Toast.makeText(this, message, length).show();
   }
}

}

Here is another code excerpt to perform the same for Fragment. Except here we can rely on the BaseActivity instance to call its methods.

public abstract class BaseFragment extends Fragment
{
private BaseActivity mActivity;
private Unbinder mUnBinder;
private Dialog progressDialog;
public SessionPreference preference;
private Dialog dialog;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
preference=new SessionPreference(mActivity);
}
@Override

public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

super.onViewCreated(view, savedInstanceState);
setUp(view);
}

protected abstract void setUp(View view);

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof BaseActivity) {
BaseActivity activity = (BaseActivity) context;
this.mActivity =activity;
activity.onFragmentAttached();
}
}

@Override
public void onDetach() {
mActivity = null;
super.onDetach();
}

public void setUnBinder(Unbinder unBinder) {
mUnBinder = unBinder;
}

@Override
public void onDestroy() {
if (mUnBinder != null) {
mUnBinder.unbind();
}
super.onDestroy();
}

public void showProgressBar() {
if(mActivity!=null) mActivity.showProgressBar();
}

public void hideProgressBar() {
if
(mActivity!=null) mActivity.hideProgressBar();
}

public void showToast(String message,int length)
{
if (mActivity != null) {
mActivity.showToast(message,length);
}
}
}

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.

public void handleErrorMessage(Response<ResponseBody> responseBody) throws IOException,JSONException{
String resultString = responseBody.errorBody().string();
JSONObject jsonObject = new JSONObject(resultString);
String message = jsonObject.getString(AppConstants.MESSAGE);
showToast(message,0);
if(jsonObject.getInt(AppConstants.STATUS_KEY) == AppConstants.UNAUTHORIZED){
showToast(message, 0);
performLogout();
}
}

public void performLogout() {
preference.clearSession();
preference.setLoginToken("");
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
this.finish();
}

Conclusion


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.


References

• https://medium.com/@sandeeptengale/writing-good-baseactivity-class-for-android-activity-
100636c81011

• https://stackoverflow.com/questions/8821240/android-how-to-create-my-own-activity-and-
extend-it

 

 

 

 

Request for Proposal

Recaptcha is required.

Sending message..