Passing data beetwen fragments in viewpager - android

I've Viewpager wit 2 fragments: CurrentWeatherFragment and ForecastFragment. I need to pass string from one to another, Iam using interface like below, but I keep getting NullPointerException, the message is not passing propertly...
public class CurrentWeatherFragment extends Fragment {
SendMessage SM
public void onCreateView(...) {
String Message = "Hello"
SM.sendData(Message);
}
interface SendMessage
{
public void sendData(String message);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
SM = (SendMessage) activity;
} catch(ClassCastException e) {
throw new ClassCastException("Musisz zaimplementowac metode sendData");
}
}
}
MainActivity.java
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
public class MainActivity extends FragmentActivity implements CurrentWeatherFragment.SendMessage {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting fragment view pager
viewPager = (ViewPager)findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
public void sendData (String message){
ForecastFragment FF = new ForecastFragment();
FF.getData(message);
}
}
ForecastFragment.java
public class ForecastFragment extends Fragment {
public View onCreateView(){
TextView txt = (TextView)v.findViewById(R.id.txt_forecast);
}
public void getData(String message){
txt.setText(message);
}
}
I've used this method succesfully in other app where I've had 2 fragments in one activity and i could call them by ID
public void sendData(String message) {
SecondFragment f2 = (SecondFragment)getFragmentManager().findFragmentById(R.id.F2);
f2.getData(message);
}
But here Fragments dont have IDs and I think that message is not passed because i dont use FragmentManager(), but how to find fragment in viewpager without ID, any suggestion/ideas?

Although a little hacky what you can do is get the fragment by its tag by using the following code:
String tag = "android:switcher:" + R.id.pager + ":" + index;
Fragment f = getSupportFragmentManager().findFragmentByTag(tag);
Where R.id.pager is the id of the viewpager in your layout and index is the position (as an integer) in the Viewpager Adapter.
I can't say this will work forever but it works for me at the moment.
The Alternative i would suggest is using a LocalBroadcastManager and a BroadcastReciver to send data internally between your fragments as although its a little more work it helps get rid of the spaghetti code situation you may end up finding yourself in trying to reference the fragments directly.

To pass data between fragments you need to pass the data in the object constructor.
Be aware to don't override the default constructor, instead create a static method getInstance(String data).
public static YourClass getInstance(String data)
{
YourClass object = new YourClass();
Bundle bundle = new Bundle();
bundle.putString(key, data);
object.setArguments(bundle);
return object;
}
Then you can get the data in the fragment's onCreate method with getArguments()

For some other users like me who looking for fragment to viewpager data sending
Here is working solution :
Sending data from fragment TO tab layout's view pager's fragments:
In Main fragment :
For tab layout i am using two fragments
1) BillDetailFragment and
2) ClientDepMonFragment
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_detail, container, false);
// adding fragment and passing data to it
BillDetailFragment billDetailFragment=new BillDetailFragment();
Bundle bundle=new Bundle();
bundle.putString("mobile",mobile);
bundle.putInt("c_id",client_id);
bundle.putInt("server_id",server_id);
billDetailFragment.setArguments(bundle);
ClientDepMonFragment clientDepMonFragment=new ClientDepMonFragment();
Bundle bundle1=new Bundle();
bundle1.putString("mobile",mobile);
bundle1.putInt("c_id",client_id);
bundle1.putInt("server_id",server_id);
clientDepMonFragment.setArguments(bundle1);
tabLayout=(TabLayout)view.findViewById(R.id.detail_txn_tab_layout);
viewPager=(ViewPager)view.findViewById(R.id.detail_txn_viewpager);
dtViewPagerAdapter=new DtViewPagerAdapter(getChildFragmentManager(),DetailFragment.this);
dtViewPagerAdapter.addFragments(billDetailFragment,"Lending Money");
dtViewPagerAdapter.addFragments(clientDepMonFragment,"Deposited Money");
viewPager.setAdapter(dtViewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
and here is how to access that data from fragment
BillDetailFragment: override onCreate method
private int client_id,server_id;
private String client_mobile;
#Override
public void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
client_mobile=getArguments().getString("mobile");
client_id=getArguments().getInt("c_id");
server_id=getArguments().getInt("server_id");
}

Related

Android - How to pass data from activity to fragment? [duplicate]

This question already has answers here:
Communicating between a fragment and an activity - best practices
(11 answers)
Closed 4 years ago.
I need to pass data from activity to fragment. I know I can use bundle , but once I passed data,I can't send data without calling and creating fragment again.
In my activity, some thing may be changed and I need to notify my fragment for these changes without recreating fragment.
Create one interface in your Activity and pass your data via the interface to the fragment. Implement that interface in your fragment to get data.
For example
MainActivity.class
public class MainActivity extends AppCompatActivity {
DataFromActivityToFragment dataFromActivityToFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentA fr = new FragmentA();
FragmentManager fm = getFragmentManager();
dataFromActivityToFragment = (DataFromActivityToFragment) fr;
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
final Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
dataFromActivityToFragment.sendData("Hi");
}
};
handler.postDelayed(r, 5000);
}
public interface DataFromActivityToFragment {
void sendData(String data);
}
}
FragmentA.class
public class FragmentA extends Fragment implements MainActivity.DataFromActivityToFragment {
TextView text;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.content_main, null);
text = (TextView) rootView.findViewById(R.id.fragment_text);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void sendData(String data) {
if(data != null)
text.setText(data);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
content_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/fragment_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In above example I have taken Runnable just to send data with delay of 5 seconds after creation of fragment.
Fragment object is just like other objects.Like String , you can invoke methods of string object, str.charAt(0) ,str.toUpperCase() etc. Just create a function in fragment, put your code there and call the function along with values
Inside Activity {
fragDemoObject.doWhatYouWant("this is passed as string object to fragment");
}
Inside FragmentDemo{
void doWhatYouWant(String input){
System.out.println(input);
// do what else you want to do with code
}
}
Actually your question is not related to:
I need to pass data from activity to fragmenet .I know I can use
bundle , but one i've passed data , I cant send anymore data without
calling and creating fragment once more .
The real one is this:
in my activity , some thing may be changed and I need to notify my
fragment from these changes without recreating fragment.
how can I do so ?
In this case I would store the fragment in the activity as reference and I would call a function, an interface implementation inside the fragment.
Something like this:
In Activity:
SomeEventListener myFragment ;
yourFragmentCreationMethod(){
if(myFragment == null){
myFragment = new MyFragment(maybeParamsHere);
}
}
yourNotificationMethod(){
myFragment .onEventHappent(param);
}
// declare an interface: - separate file
public interface SomeEventListener
{
void onEventHappent(param);
}
// implement the interface in Fragment - separate file
public class MyFragment extends Fragment implements SomeEventListener{
// add a constructor what you like
public void onEventHappent(param){
/// ... your update
}
}
The interface it will help you at testing only.
The host activity can deliver messages to a fragment by capturing the
Fragment instance with findFragmentById(), then directly call the
fragment's public methods.
In your fragment - MyFragment, create a public method
public void myFragmentDataFromActivity(int passedDataFromActivity) {
// do your stuff
}
In your activity to pass an integer value say, 100 :
get MyFragment instance using getSupportFragmentManager or getFragmentManager by providing id/tag/position. Then call the public method in MyFragment instance.
MyFragment myFragment = (MyFragment) getSupportFragmentManager.getFragmentById(id);
myFragment.myFragmentDataFromActivity(100);
You can also use getFragmentByTag(tag), getFragments().get(position) instead of getFragmentById(id) to get fragment instance.
read more about this
For notify fragment with some data after it's created, can be done using some Communicator, or you can always pass the data with bundle in creation time...
For example:
public interface FragmentCommunicator {
void updateDataToFragment(List<Parcelable> data);
}
then in your fragment implement this interface and calling it from the activity for example as:`
Fragment fragment = mSectionsPagerAdapter.getRegisteredFragment(i);
if (fragment instanceof FragmentCommunicator) {
FragmentCommunicator fragmentCommunicator = (FragmentCommunicator) fragment;
fragmentCommunicator.updateDataToFragment(data);
}`
This should works for your case...
try this one in Activity
fragment=new PdfFragment();
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
Bundle bundle = new Bundle();
bundle.putString("pdf", Pdf);
bundle.putString("flag", "0");
fragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.container, fragment).addToBackStack(null).commit();
}
and in fragment
Pdf = getArguments().getString("pdf");
You should declare your method as public in the fragment to update new data. Then you will call that method via fragment instance. For example, write this in your activity when getting new data:
fragmentInstance.publicMethod(newData);
Happy coding!
I have also come across the same issue, I have used singleton class to
transfer data from activity to fragment (without making fragment
transaction or using inteface)
class DataPersistance {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
private String name;
private String place;
private String type;
private static final DataPersistance ourInstance = new DataPersistance();
static DataPersistance getInstance() {
return ourInstance;
}
private DataPersistance() {
}
}
to set and get data
DataPersistance.getInstance().setName(mEditText.getText().toString());
String name = DataPersistance.getInstance().getName();

How do I prevent viewpager from making network request, if the network request has already been made for all the pages

I have a viewpager with three pages that uses FragmentStatePagerAdapter.
The fragment for each page is same but the data changes depending on the position of the page. The inflation logic for each item on the page is defined in fragment's OnCreateView, and thats why each time new instance of fragment is inflated the network calls are repeated even though they have been already made on previous visit to that page.
My question is how do I prevent this. I am new to android and I know I am missing something here, IF my approach is wrong please point out about how should I prevent this behavior.
Some Code :
inside activity's oncreate
ViewPager mViewPager = (ViewPager) findViewById(R.id.vpBooks);
PagerAdapter mPagerAdapter = new BooksPageAdapter(getSupportFragmentManager(), MainActivity.this, extras);
mViewPager.setAdapter(mPagerAdapter);
inside viewpageradapter
public BooksPageAdapter(FragmentManager fm, Context context, Bundle extras) {
super(fm);
this.extras = extras;
this.cls = extras.getStringArray("cls");
this.context = context;
}
#Override
public Fragment getItem(int position) {
return BooksPageFrag.newInstance(extras, cls[position]);
}
#Override
public int getCount() {
return cls.length;
}
inside fragment :
#Override
public void onCreateView(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
url = getArguments().getString("url");
urlFare = getArguments().getString("Fare");
Log.d("url sapf", url);
queue = Volley.newRequestQueue(this.getActivity());
getBooks();// HERE network calls are made
}
so what I want is if the fragement for a particular cls[position] is instantiated and data is fetched then on revisiting same position it should not make new network calls
You need to use parcelable . I think you are using a list array of a class object
.Follow the following steps
1.) Implement parcelable in the class object
2.)In the OnSavedInstanceState use the following code
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("key", mListParcel);
}`
3.) In the onCreate method use this code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
/*Set Your RecyclerView Stuff here*/
if(savedInstanceState!=null)
{
//Fragment has been loaded earlier\
mArrayList=savedInstanceState.getParcelableArrayList("key");
//Use list here
}
else
{
//Fragment New
// Make Request Here
}
}

update object in swipe view

I'm trying to update an object from a fragment contained within a swipe view. The code I have is taken directly from the Android documentation. What I want to do is pass an object from the main CollectionDemoActivity down into the DemoObjectFragment fragment, update it using a button in that fragment and then pass it back up to the main activity. What's the best way to accomplish this?
I've tried passing the object in a bundle as a serialisable through the DemoCollectionPagerAdapter and then again down to the fragment but this seems really cumbersome. I've also tried declaring the object in the main activity and just referencing it in the fragment class but I get complaints that it can't have a non-static reference in a static context.
public class CollectionDemoActivity extends FragmentActivity {
// When requested, this adapter returns a DemoObjectFragment,
// representing an object in the collection.
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
mDemoCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
}
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
So after a lot of searching and reading I found a nice solution that works for me. For those interested I created an interface in the fragment class that is implemented in the Main activity. The methods were kicked off through a button press in the fragment class. This way I was able to pass variables up to the main class without ever needing to pass the entire object down to the fragment.
So my classes were mostly the same with these bits added:
And the fragment class which contains the interface. The onAttach() method needs to be called which gets a reference to the activity that the fragment will be attached to. This activity reference is binded to an instance of the interface in the fragment.
public class DemoObjectFragment extends Fragment {
....
//Creating the interface
public interface ButtonListener {
//This method will be called in the main activity. Whatever is passed in as the parameter can be used by the main activity
public void ButtonPressed(int myInt);
}
//Getting an instance of the interface
ButtonListener updateListener;
//Getting a reference to the main activity when the fragment is attached to it.
//The activity reference is bound to the instance of the interface.
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Ensures the activity implements the callback interface
try {
updateListener = (DayUpdateButtonListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
....
//On the button click call the method through the activity reference from the onAttach() method
//Creating an int object to pass into the method.
int myNewInt = 5;
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
updateListener.ButtonPressed(myNewInt);
}
});
}
Finally in the main activity simply implement the interface and add the method from it.
public class CollectionDemoActivity extends FragmentActivity implements DemoObjectFragment.ButtonListener {
....
#Override
public void ButtonPressed(int myInt) {
//Update the object with myInt
}
}

FragmentAdapter doesn't hold the good reference of the fragment

I'm currently trying to work with fragment, but I'm stuck with an issue I can't solve.
I have one activity, which holds 4 different fragment. From this activity, I launch an ASyncTask which goes to the web and get different data I need, and then will send it to the fragments.
But, when my app gets killed and opened again, or when I change the orientation, my fragments are apparently recreated and my custom FragmentAdapter doesn't hold the good reference to the fragment.
Here is the code of my main activity.
public class MainActivity extends FragmentActivity {
MyPagerAdapter fgsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
FragmentManager fm = super.getSupportFragmentManager();
fgsAdapter = new MyPagerAdapter(fm,this);
ViewPager myPager = (ViewPager) findViewById(R.id.home_pannels_pager);
myPager.setAdapter(fgsAdapter);
myPager.setCurrentItem(0);
}
#Override
protected void onResume() {
super.onResume();
ATaskGetUser task = new ATaskGetUser(callback, (ProgressBar) findViewById(R.id.PB_AsyncTask));
task.execute();
}
//What's called by the ASyncTask onPostExecute()
private void notifyDataChanged() {
fgsAdapter.notifyFragments(user.getItems());
}
private class MyPagerAdapter extends FragmentPagerAdapter {
private List<CardFragment> fragments = new ArrayList<CardFragment>();
private Context c;
public MyPagerAdapter(FragmentManager fm, Context c) {
super(fm);
CardFragment h = new HabitFragment();
CardFragment d = new DailyFragment();
CardFragment t = new ToDoFragment();
CardFragment r = new RewardFragment();
fragments.add(h);
fragments.add(d);
fragments.add(t);
fragments.add(r);
}
public int getCount() {
return fragments.size();
}
#Override
public CardFragment getItem(int position) {
Log.v("MainActivity_fgsmanager", "getItem()");
CardFragment f = (CardFragment) this.fragments.get(position);
return f;
}
public void notifyFragments(List<HabitItem> items) {
for(OnTasksChanged f : fragments) {
f.onChange(items);
}
}
}
}
So, what I want to be able to do, is to be able to call the onChange (an interface implemented by my four fragments), in my notifyDataChanged function. Is this possible, are am I thinking the wrong way?
I got the same problems once with Fragments, I was losing the current fragment after every screen rotation.
I simply solved it by adding one line in the Fragment class (not in the parent FragmentActivity class):
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.rate_fragment, container,false);
setRetainInstance(true);//Added not to lose the fragment instance during screen rotations
(...)
For your case where your app gets killed and opened again, I am not sure it will work though.

ViewPager and Activity recreation / persisting data in fragments after activity onDestroy-onCreate

I wrote an activity with ViewPager, which gets populated after an AsyncTask is executed. Each TestDataObject is tied to the relevant TestFragment. When the screen is rotated the application crushes due to a NullPointerException inside onCreateView method. I believe this is because of ViewPager/Adapter onSaveInstanceState methods, onCreateView tries to restore data prior to the AsyncTask data load when data isn't available yet.
I could just if onCreateView code but it doesn't feel to me like a right solution, because amount of fragments inside ViewPager might vary so it might end up doing unnecessary job: restore altered viewpager content and then replace with initial. In this case onSaveInstanceState seems to be excessively harmful. Presumably, I could extend ViewPager or Adapter to cancel save procedure - I find it weird as well.
Do you have any better suggestions to offer?
public class MainActivity extends LoggerActivity {
private ArrayList<TestDataObject> mDataObjects = new ArrayList<MainActivity.TestDataObject>();
private ViewPager mViewPager;
private TestFragmentAdapter mViewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPagerAdapter = new TestFragmentAdapter(
getSupportFragmentManager(), mDataObjects);
mViewPager.setAdapter(mViewPagerAdapter);
new TestAsyncTask().execute();
}
private class TestAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mDataObjects.add(new TestDataObject());
mDataObjects.add(new TestDataObject());
mDataObjects.add(new TestDataObject());
mViewPagerAdapter.notifyDataSetChanged();
}
}
public static class TestFragment extends Fragment {
private TestDataObject mDataObject;
public static TestFragment getInstance(TestDataObject obj) {
TestFragment f = new TestFragment();
f.mDataObject = obj;
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// layout.find...
mDataObject.toString();
return inflater.inflate(R.layout.fragment_test, null, false);
}
}
public static class TestFragmentAdapter extends FragmentStatePagerAdapter {
private List<TestDataObject> mDataObjects;
public TestFragmentAdapter(FragmentManager fm, List<TestDataObject> objs) {
super(fm);
mDataObjects = objs;
}
#Override
public Fragment getItem(int position) {
return TestFragment.getInstance(mDataObjects.get(position));
}
#Override
public int getCount() {
return mDataObjects == null ? 0 : mDataObjects.size();
}
}
public static class TestDataObject {
}
}
I believe this is because of ViewPager/Adapter onSaveInstanceState
methods. onCreateView tries to restore data prior to the asynctask
dataload when data isn't available yet.
That is not what is happening(I'm assuming you get the exception at mDataObject.toString();), even if the AsyncTask would finish its job instantaneously the exception will still be thrown. After the first run of the app the ViewPager will have three fragments in it. When you'll turn the phone the Activity will be destroyed an recreated again. The ViewPager will try to recreate the fragments in it, but this time it will do it by using the default empty constructor(that is why you shouldn't use a non empty constructor to pass data). As you can see, the first time the Fragment is created by the adapter it will be created by the getInstance method(that is also the only point where you initialize mDataObject) to which you pass a TestDataObject object. When the ViewPager reinitializes its fragments that field will not be initialized as well.
If TestDataObject can be put in a Bundle then you could simply adapt your getInstance method to pass some arguments to your fragments(so the data field will be initialized when the ViewPager will recreate them). I'm sure you've seen:
public static TestFragment getInstance(TestDataObject obj) {
TestFragment f = new TestFragment();
// f.mDataObject = obj; <- don't do this
// if possible
Bundle args = new Bundle();
args.put("data", obj); // only if obj can be put in a Bundle
f.setArguments(args);
return f;
}
private TestDataObject mDataObject;
#Override
public void onCreate(Bundle savedInstance) {
mDataObject = getArguments().get("data"); // again, depends on your TestDataObject
}
Another approach would be to pass the smallest amount of data to the Fragment(like above) so it has enough information to recreate it's data whenever it's recreated.

Categories

Resources