Android - Bundle

> Android

1 - About

Key value pair structure

3 - Snippet

Bundle args = new Bundle();
args.putInt("key",value);

4 - Usage

4.1 - Fragment Arguments

fragment.setArguments(Bundle bundle)
// Once the argument are set, you can only read from them
getArguments().getInt(key",0);
Advertising

4.2 - savedInstanceState Bundle

Thee savedInstanceState Bundle is restoring information once the fragment has been running. The bundle can save information:

  • across orientation changes
  • or if the application gets killed by the system (that's why you get it on the onCreateView methods)
@Override
public void onSaveInstanceState(Bundle outState) {
	// When tablets rotate, the currently selected list item needs to be saved.
	// When no item is selected, mPosition will be set to Listview.INVALID_POSITION,
	// so check for that before storing.
	if (mPosition != ListView.INVALID_POSITION) {
		outState.putInt(SELECTED_KEY, mPosition);
	}
	super.onSaveInstanceState(outState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
	// Code
	// ...........
 
 
	// If there's instance state, mine it for useful information.
	// The end-goal here is that the user never knows that turning their device sideways
	// does crazy lifecycle related things. 
	if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY)) {
		// The listview probably hasn't even been populated yet.  The poisition is then stored in a member variable
                // Actually perform the swapout in onLoadFinished.
		mPosition = savedInstanceState.getInt(SELECTED_KEY);
	}
 
	return myView;
}
  • Use it
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
	myAdapter.swapCursor(data);
	if (mPosition != ListView.INVALID_POSITION) {
		// If we don't need to restart the loader, and there's a desired position to restore,   
		mListView.smoothScrollToPosition(mPosition);
	}
}