Bundle is null in Fragment - android

I create the bundle in my Activity with
ListFragment fragment = new ListFragment();
Bundle bundle = new Bundle();
bundle.putInt("i", 0);
Log.i("Bundle", String.valueOf(bundle.getInt("i")));
fragment.setArguments(bundle);
And I get the arguments in my Fragment with
Bundle bundle = this.getArguments();
if (bundle != null) {
myInt = bundle.getInt("i", -1);
}
But it says that my bundle is null. Any idea why?

Are you sure that the fragment you want to read the arguments was created from the provided code block #1? Your code is correct, there is nothing wrong so it must work. (as long as the arguments are accessed after onCreate, which they are)

I had the same issue, I initially had my bundle variable declared outside the onCreateView function. Once I moved it inside, it worked for me

Related

Bundle returning Null when called in fragment

I am trying to pass string from Adapter to fragment in Bundle bu ti'm getting null in my Fragment
Here is my code to add string to Bundle
Bundle bundle=new Bundle();
bundle.putString("id",expense_id);
AddExpenseFragment fragment=new AddExpenseFragment();
fragment.setArguments(bundle);
UiActivity.startAddExpense(context);
this is my code to retrieve to Bundle value in Fragment
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view=inflater.inflate(R.layout.activity_fragment_add_expense,container,false);
String id=this.getArguments().getString("id");
return view;
}
and i'm passing bundle value from My recyclerView Adapter class
The problem is simple here. You are creating a fragment and setting data to it which is fine,
AddExpenseFragment fragment=new AddExpenseFragment();
fragment.setArguments(bundle);
But the problem is in your
UiActivity.startAddExpense(context);
you must be replacing with a new instance of the AddExpenseFragment as you are no where passing the newly created fragment instance (with the arguments set to it) to the startAddExpense() method.
The solution is simple, just pass the newly created fragment object to the startAddExpense() like this,
UiActivity.startAddExpense(context, fragment);
and then inside the method replace or add this new fragment and do not instantiate any new fragment object.
Try this:
Bundle bundle = this.getArguments();
String id=bundle.getString("id");
From your code, it's hard to find problems.just give your some suggestions.
Firstly, check whether your variable expense_id is null or not.
Secondly, check whether the AddExpenseFragment you created and really showed are the same.

How to get element back on popBackStack( )

I have two fragments: in the first fragment I do it:
ritorno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
manager.beginTransaction().replace(R.id.content_frame,new SearchFlight()).addToBackStack(null).commit();
}
});
and this works well. In the second I need to return to the first fragment, so I decide to do this:
String s = element.getText().toString(); //I need to return it
FragmentManager manager = getActivity().getSupportFragmentManager();
SearchFragment fragment = new SearchFragment();
manager.popBackStack();
I need to return to the first fragment this String. How could I do it?
Thanks
There are 3 ways
Static Variable : Define public static variable in first fragment, update its value in second fragment.
BroadcastReceiver
EventBus you can even find EventBus tutorial here
pass string to BR or EventBus and you can fetch it in first fragment by defining appropriate method or listener.
Try doing it with a bundle object.
String s = element.getText().toString(); //item to be returned
FragmentManager manager = getActivity().getSupportFragmentManager();
SearchFragment fragment = new SearchFragment();
Bundle bundle = new Bundle();
bundle.putString("key", "value");
fragment.setArguments(bundle);
manager.popBackStack();
And then, in your SearchFragment resolve the bundle like:
Bundle bundle = this.getArguments();
bundle.getString("key");
Do the resolution part of the bundle in your onCreateView of the SearchFragment. Do place a null check on the resolution part of the bundle. If the bundle is not resolved, then the getString("key") method will give a null pointer exception.

Sending data from an activity to its fragment using bundle

I'm trying to send a Parcelable array from MainActivity to one of its fragment using bundle. My code is
Bundle bundle = new Bundle();
MyFragment fragment = new MyFragment();
bundle.putParcelableArray(key, MyParcelableArray);
fragment.setArguments(bundle);
When debugged, I found that MyParcelableArray is not null but bundle mParcelledData is null. Thus, it is throwing a null pointer error.
Why is this happening?
I'm retrieving code in the fragments onCreateView as below.
Bundle bundle = getArguments();
Parcelable[] parcelables = bundle.getParcelableArray(MainActivity.key);
getting null pointer in the above line.
While opening a fragment use below code
Bundle bundle= new Bundle();
bundle.putSerializable("data", MyParcelableArray);
ListFrag newFragment = new ListFrag ();
newFragment.setArguments(bundle);
While obtaining that bundle data in fragment use below code
Bundle b = getArguments();
ArrayList<collection> yourArrayList = (ArrayList<collection>) b.getSerializable("data");

The correct way and place to restore bundle information on a fragment?

I have seen Bundles restored in several of the Android callback methods, but in many cases there is manual creation and setting of Bundles as on the developers website, in this case from an external message on Fragment creation:
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
In this other question, for example, bundle data is restored in the onCreateView() method.
public class Frag2 extends Fragment {
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle=getArguments();
//here is your list array
String[] myStrings=bundle.getStringArray("elist");
}
}
I am a bit confused about the Bundle data supplied with each callback method VS "other bundles":
Bundle bundle=getArguments();
and the correct way and place to retrieve these different types of bundled data.
Thanks in advance!
The two ways described above are exactly the correct way to
initialize a new instance of the Fragment and pass the initial parameters.
retrieve the initial parameters in the Fragment.
In other words, you're on the right track! It should work, and you should be pleased with yourself :)
EDIT:
The Bundle can be retrieved in either onCreateView() or
onCreate(). I'd prefer onCreate(), as it represents the creation
of the Fragment instance and is the right place for initialization.
There is always one and only one Bundle instance retrieved by the call to getArguments(), and this Bundle instance contains all of your ints, Strings, whatever.

Fragments onCreateView() bundle. Where does it come from?

I'm starting an Activity through the usual means:
Intent startIntent = new Intent(this, DualPaneActivity.class);
startIntent.putExtras(((SearchPageFragment) currentFragment).getPageState());
startActivity(startIntent);
When this activity loads, it places a Fragment in a frame like so:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment currentFragment = fragment;
currentFragment.setArguments(getIntent().getExtras());
transaction.replace(R.id.singlePane, currentFragment);
transaction.commit();
Seems simple, right?
However, you can inside of onCreateView() method access three separate bundles (four, if you include the one included in the Fragment's onCreate(Bundle savedInstanceState)):
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Fill state information
Bundle bundle;
if(savedInstanceState != null) bundle = savedInstanceState; // 1
else if(getArguments() != null) bundle = getArguments(); // 2
else bundle = getActivity().getIntent().getExtras(); // 3
setPageState(bundle);
}
In the above instance, I've worked out from trial and error that the bundle I want is the second one, the one retrieved from getArguments().
From my understanding the third one from getActivity().getIntent().getExtras(); is actually calling the Bundle from the intent used to start containing activity. I also know from experimentation that savedInstanceState seems to always be null. But where is it coming from and why is it null?
The documentation says this:
savedInstanceState If non-null, this fragment is being re-constructed
from a previous saved state as given here.
That doesn't help me - It's bugging me more than stopping me from moving on. Can someone help me out with this annoyance?
To the best of my knowledge, onCreateView and onCreate() are both passed the bundle from onSaveInstanceState().
So if you override onSaveInstanceState() and put data in the bundle, you should be able to retrieve it in onCreateView(). That is why the documentation says that the bundle will be non-null when the fragment is re-constructed from a previous saved state.

Categories

Resources