# Helper class for Fragments management

A Helper class for Fragment Management.
The FragmentsManager class has methods to add and replace fragments.
The replace method checks if the given fragment is present in backstack or not and if the fragment is present it brings back the old fragment. Need review for the following:

• Code optimized.
• Memory Efficiency
• Overall code review
• Can the replace method be improved in any way so as to avoid creation of additional fragments?
• I've tried to use popbackstack() but couldn't how to use it. Can you help with that?

Thanks

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

class FragmentsManager {

private static final String TAG = "FragmentsManager";
private static FragmentTransaction transaction;
//    Return Fragment Transaction
private static FragmentTransaction getTransaction(Activity activity){
//        if (transaction == null) {
//            return transaction;
//        }
return getFragmentManager(activity).beginTransaction();
}
//    Return Fragment Manager
private static FragmentManager getFragmentManager(Activity activity){
return ((AppCompatActivity)activity).getSupportFragmentManager();
}

/**
* Add Fragment to the given ID
* @param activity
* @param fragment
* @param id
*/
transaction = getTransaction(activity);
transaction.commit();
}

static void replaceFragment(Activity activity, Fragment fragment, int id, boolean add_to_backstack) {
Fragment check_Fragment = getFragmentManager(activity).findFragmentByTag(fragment.getClass().getName());
if (check_Fragment == null) {
transaction = getTransaction(activity)
.replace(id,fragment,fragment.getClass().getName());
transaction.commit();
}
else{
transaction = getTransaction(activity);
transaction.replace(id,check_Fragment,check_Fragment.getClass().getName())
.commit();
}
}
}


your code looks very good, there are only minor issues:

# 1) naming

since you don't create any instances of FragmentsManager you should consider to rename it to FragmentsUtility. An Utility class provides methods to help you with your code while a Manager is an instance that does the work for you.

boolean should beginn with prefix is (or rarely as an alternative has/can/should) (in Java it's convention to use camelCase) so rename your boolean add_to_backstack into boolean isAddedToBackstack rather (btw. in java it's convention to use camelCase)

remove commented code!

you provide some javadoc on the addFragment methode which is very crude - get things done and finish it!

the same applies to replaceFragment.

• Thank you for your review. I thought JavaDocs should be provided for all the methods defined for description purposes. So I added them. Guess I was wrong. Thanks again. – sdb1995 Nov 24 '18 at 6:07