Since the Android system uses the default no-arg constructor when recreating a fragment, we should not pass values over an overloaded constructor with arguments when we instantiate it. Otherwise we get a warning that says “Avoid non-default constructors in fragments: use a default constructor plus Fragment setArguments(Bundle) instead” or we even get an InstantiationException. The correct way to instantiate a new fragment and passing values to it, is by creating a bundle, setting arguments on this bundle and then passing it to our fragment. Inside the fragment we then retrieve this bundle and get the values out of it. A clean way to do this is by creating a so called “factory method”. In MainActivity.java class add these lines of codes:- import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { ...
Become a coding expert