Search code examples
androidobjectobject-initializationobject-state

How to Make Everything (Counters, Variables) to null of an Object?


I want to know that how can I make a an Object again go back to its initial stage. In my case I make a fragment and initialize it. I want that when it goes back to another fragment, and then back to first one, all values and variables of the first objects again initializes.

MyFragment frag = new MyFragment();

How can it again go back to this stage without initialization it again with new Keyword.


Solution

  • You can use below setter technique

    public class MyFragment extends Fragment{
    
    private String name;
    private String address;
    
    public void resetAll(){
        myFragment = null;
      }
    }
    

    Here myFragment is reference variable of fragment. After call of resetALL method, every String variable available in fragment will be null