The reason you are getting null pointer exception is because of this :
All subclasses of Fragment must include a public no-argument
constructor. The framework will often re-instantiate a fragment class
when needed, in particular during state restore, and needs to be able
to find this constructor to instantiate it. If the no-argument
constructor is not available, a runtime exception will occur in some
cases during state restore.
You cannot pass arguments through a constructor in fragment.
For passing arguments, you should use newInstance
.
In your case to pass mcity
to fragment - Fragmentone
, include this code in Fragmentone
String mCity;
public static newInstance(String mcity) {
Fragmentone fragmentOne = new Fragmentone();
Bundle argumentsBundle = new Bundle();
argumentsBundle.putString("mcityKey", mcity);
fragmentOne.setArguments(argumentsBundle);
return fragmentOne;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String mCity = getArguments().getString("mcityKey");
Log.i("city : ", mcity);
}
Now in activity class you can do this,
String city = "one";
Fragmentone frag = new Fragmentone(city);
see more examples and details