0

I am trying to pass value between activity and fragment But I am getting java.lang.NullPointerException. So please tell me how to do it in the right way. Here is my code:-

Activity class :-

String city = "one";
Fragmentone frag  = new Fragmentone(city);  

And in Fragmentone class I am using something like this:-

String mcity ;
public Fragmentone(String city) {
this.mcity = city;

}

Log.e("--", mcity);

So this log is giving me NullPointerException

Thank you in advance

xenteros
  • 15,586
  • 12
  • 56
  • 91

1 Answers1

0

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

mrtpk
  • 1,398
  • 4
  • 18
  • 38