Question

I need to pass an int value from an activity fragment to another fragment. This data will be then set to be in a switch case, which will decide on which android layout file will attach to the fragment.

This is the code from the base activity and on the fragment that sets the value to be passed:

Fragment fragment = new otherFragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

btw, I also tried to put the above code on the onCreate and onCreateView method of the fragment but still the same output. then after setting the fragment and the bundle, i switch to the other activity and here is the code that will get and use the int value:

Bundle bundle = this.getArguments();
int myInt = bundle.getInt(key, defaultValue);

also tried

savedInstanceState = this.getArguments();
int type = savedInstanceState.getInt(key, defaultValue);

when from the base activity, the error is Null Pointer Exception, and when from the 1st fragment, the error is Resource not found.

05-12 14:50:47.732: E/ERRORSKI(814): java.lang.NullPointerException
05-12 14:41:38.542: E/ERRORSKI(798): android.content.res.Resources$NotFoundException: String resource ID #0x1

Thank you.

Was it helpful?

Solution

Creating a fragment using the default constructor generally isn't the way to go. Here is an example of what you could better be doing for creating a new instance of your fragment and passing an integer with it.

Place this code in your fragment that will be created.

public class ExampleFragment {
    public static ExampleFragment newInstance(int exampleInt) {
        ExampleFragment fragment = new ExampleFragment();

        Bundle args = new Bundle();
        args.putInt("exampleInt", exampleInt);
        fragment.setArguments(args);

        return fragment;
    }
}

Use this in your activity to create a new fragment.

Fragment exampleFragment = ExampleFragment.newInstance(exampleInt);

And later in your fragment, use something like this to get your integer.

getArguments().getInt("exampleInt", -1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top