DialogFragment / orientation switch - android

I have a fairly simple DialogFragment. It looks something like:
import android.support.v4.app.DialogFragment;
public class MyDialogFragment extends DialogFragment {
private String mData = "empty";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate");
setStyle(DialogFragment.STYLE_NO_TITLE, 0);
// setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mydialog, container);
....
return view;
}
public setData(String _data) {
mData = _data;
}
}
I load this fragment like so from my FragmentActivity:
FragmentManager lFM = getSupportFragmentManager();
MyDialogFragment lDialog = new MyDialogFragment();
lDialog.setData("not empty");
lDialog.show(lFM, "MyDialog");
The code as above works fine. However I would like to retain the fragment on an orientation switch so that the mData field is preserved. If I add setRetainInstance(true); (and after sticking in some debug) I can see that the fragment is indeed retained on an orientation switch - onCreate() is not being called this time. I can see onCreateView() is being called and I return a correct View object, but the dialog is not shown on the screen. What am I missing?

After reading the answer that baboo gave me I implemented the solution as follows .. I hope this is correct (at least it works ok ...)
#Override
public void onCreate(Bundle savedInstanceState) {
// ....
FragmentManager lFM = getSupportFragmentManager();
if(lFM.findFragmentByTag("MyDialog")!=null)
((MyDialogFragment)lFM.findFragmentByTag("MyDialog")).show(lFM, "MyDialog");
// ....
}

Try the following logic in your fragment activity:
Use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
icicle.putBoolean("dialogDisplayed", value); // set value = true when displayin dialog...
}
And restore the values in onCreate():
public void onCreate(Bundle icicle) {
if (icicle != null){
value = icicle.getBoolean("dialogDisplayed");
}
if(value)
//Display Dialog here....
}

The dialog fragment should be preserved automatically as long as you do the following:
If you call an Activity onSaveInstanceState(), make sure you call the super function!!!!. In my case, that was the key. Also make sure you do the same thing in the Fragment.
If you use setRetainInstance, you will need to manually store off the values and re-apply them. Otherwise, you should be able to not worry about it, in most cases. If you're doing something a bit more complicated, you might need to setRetainInstance(true), but otherwise ignore it. In my case, I needed to use it to store a random seed for one of my classes, but otherwise I was okay.
Some people have complained about a bug in the support library, where a dismiss message is sent when it shouldn't be. The latest support library seems to have fixed that, so you shouldn't need to worry about that.
You shouldn't need to do anything fancy like manually store off the fragment, it should be done automatically if you follow these steps.

Related

Prevent Fragment recovery in Android

We are using Fragments and we don't need them to be automatically recovered when the Activity is recreated.
But Android every time when Activity::onCreate(Bundle savedInstanceState) -> super.onCreate(savedInstanceState) is called, restores Fragments even if we use setRetainInstance(false) for those Fragments.
Moreover, in those Fragments Fragment.performCreateView() is called directly without going through Fragment::onAttach() and so on. Plus, some of the fields are null inside restored Fragment...
Does anybody know how to prevent Android from restoring fragments?
P.S. We know that in case of recreating Activity for config changes it could be done by adding to manifest android:configChanges="orientation|screenSize|screenLayout. But what about recreating activity in case of automatic memory cleaning?
We finished by adding to activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
}
It suppresses any saved data on create/recreate cycle of an Activity and avoids fragments auto re-creation.
#goRGon 's answer was very useful for me, but such use cause serious problems when there is some more information you needs to forward to your activity after recreate.
Here is improved version that only removes "fragments", but keep every other parameters.
ID that is removed from bundle is part of android.support.v4.app.FragmentActivity class as FRAGMENTS_TAG field. It may of course change over time, but it's not expected.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(createBundleNoFragmentRestore(savedInstanceState));
}
/**
* Improve bundle to prevent restoring of fragments.
* #param bundle bundle container
* #return improved bundle with removed "fragments parcelable"
*/
private static Bundle createBundleNoFragmentRestore(Bundle bundle) {
if (bundle != null) {
bundle.remove("android:support:fragments");
}
return bundle;
}
I was having a problem with TransactionTooLargeException. So thankfully after using tolargetool I founded that the fragments (android:support:fragments) were been in memory, and the transaction became too large. So finally I did this, and it worked great.
#Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("android:support:fragments", null);
}
Edit: I added it to the Activity. In my case I have one single Activity app and Multiple Fragments.
Those who got NPE with ViewPager when use this method described in the accepted answer, please override
ViewPager.onRestoreInstanceState(Parcelable state)
method and call
super.onRestoreInstanceState(null);
instead.
I removed the fragments in Activity's onCreate.
For an app with a ViewPager, I remove the fragments in onCreate(), before their creation.
Based on this thread: Remove all fragments from container, we have:
FragmentManager fm = getSupportFragmentManager();
for (Fragment fragment: fm.getFragments()) {
fm.beginTransaction().remove(fragment).commitNow();
}
Use this one for androidx
override fun onCreate(savedInstanceState: Bundle?) {
preventFragmentRecreation()
super.onCreate(savedInstanceState)
}
private fun preventFragmentRecreation() {
supportFragmentManager.addFragmentOnAttachListener { _, _ ->
savedStateRegistry.unregisterSavedStateProvider("android:support:fragments")
}
}
This worked for me
#Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.remove("androidx.lifecycle.BundlableSavedStateRegistry.key");
}
View hierarchy in not restored automatically. So, in Fragment.onCreateView() or Activity.onCreate(), you have to restore all views (from xml or programmatically). Each ViewGroup that contains a fragment, must have the same ID as when you created it the first time. Once the view hierarchy is created, Android restores all fragments and put theirs views in the right ViewGroup thanks to the ID. Let say that Android remembers the ID of the ViewGroup on which a fragment was. This happens somewhere between onCreateView() and onStart().

Fragment saveInstanceState is coming as null after orientation change

I have an activity with action bar tab. Each tab contain a fragment. Now when I rotate my device, bundle in my corresponding fragment is coming as null. This is taken care when I using device post android 3.2, but it is happening when device is Andoird3.0. I am having a headache after working on this issue. I crossed check various link on SO, but no help. Although I have given enough details, still will provide some code snippet as at various cases user ask for code snippet.
In my fragment class I am storing this value
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean("textboxVisible", true);
}
this is storing one boolean variable which it retrived as below.
/**
* Function called after activity is created. Use this
* method to restore the previous state of the fragment
*/
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null)
{
//restore the state of the text box
boolean textboxVisible = savedInstanceState.getBoolean("textboxVisible");
if (textboxVisible)
{
//do some stuff
}
}
}
but after rotation savedInstanceState is coming as null.
I don't what is going wrong. I have read in some document that below 3.2 the onCreateView() of
fragment is not called with bundle value. But to deal with this. Any help will be appreciated.
if you use setRetainInstance(true) the savedInstance bundle is always gonna be null after orientation changed. SO you cannot really save something with it, but what you can do if you need to save something, is to put it in a data member of the fragment, because setRetainInstance(true) preserves the fragment and doesn't destroy it, so after the device was rotated you gonna have the same values.
Try to get the savedInstanceState in onCreate of the Fragment.
Like
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
if (savedInstanceState != null) {
// IT MUST NOT BE NULL HERE
}
}
Please try... i hope it will work

Send data from activity to fragment in Android

I have two classes. First is activity, second is a fragment where I have some EditText. In activity I have a subclass with async-task and in method doInBackground I get some result, which I save to variable. How can I send this variable from subclass "my activity" to this fragment?
From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Also You can access activity data from fragment:
Activity:
public class MyActivity extends Activity {
private String myString = "hello";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
...
}
public String getMyData() {
return myString;
}
}
Fragment:
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyActivity activity = (MyActivity) getActivity();
String myDataFromActivity = activity.getMyData();
return view;
}
}
I´ve found a lot of answers here # stackoverflow.com but definitely this is the correct answer of:
"Sending data from activity to fragment in android".
Activity:
Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Fragment:
Reading the value in the fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
String myValue = bundle.getString("message");
...
...
...
}
or just
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String myValue = this.getArguments().getString("message");
...
...
...
}
This answer may be too late. but it will be useful for future readers.
I have some criteria. I have coded for pick the file from intent. and selected file to be passed to particular fragment for further process. i have many fragments having the functionality of File picking. at the time , every time checking the condition and get the fragment and pass the value is quite disgusting. so , i have decided to pass the value using interface.
Step 1: Create the interface on Main Activity.
public interface SelectedBundle {
void onBundleSelect(Bundle bundle);
}
Step 2: Create the SelectedBundle reference on the Same Activity
SelectedBundle selectedBundle;
Step 3: create the Method in the Same Activity
public void setOnBundleSelected(SelectedBundle selectedBundle) {
this.selectedBundle = selectedBundle;
}
Step 4: Need to initialise the SelectedBundle reference which are all fragment need filepicker functionality.You place this code on your fragment onCreateView(..) method
((MainActivity)getActivity()).setOnBundleSelected(new MainActivity.SelectedBundle() {
#Override
public void onBundleSelect(Bundle bundle) {
updateList(bundle);
}
});
Step 5: My case, i need to pass the image Uri from HomeActivity to fragment. So, i used this functionality on onActivityResult method.
onActivityResult from the MainActivity, pass the values to the fragments using interface.
Note: Your case may be different. you can call it from any where from your HomeActivity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
selectedBundle.onBundleSelect(bundle);
}
Thats all. Implement every fragment you needed on the FragmentClass. You are great. you have done. WOW...
The best and convenient approach is calling fragment instance and send data at that time.
every fragment by default have instance method
For example :
if your fragment name is MyFragment
so you will call your fragment from activity like this :
getSupportFragmentManager().beginTransaction().add(R.id.container, MyFragment.newInstance("data1","data2"),"MyFragment").commit();
*R.id.container is a id of my FrameLayout
so in MyFragment.newInstance("data1","data2") you can send data to fragment and in your fragment you get this data in MyFragment newInstance(String param1, String param2)
public static MyFragment newInstance(String param1, String param2) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
and then in onCreate method of fragment you'll get the data:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
so now mParam1 have data1 and mParam2 have data2
now you can use this mParam1 and mParam2 in your fragment.
Basic Idea of using Fragments (F) is to create reusable self sustaining UI components in android applications. These Fragments are contained in activities and there are common(best) way of creating communication path ways from A -> F and F-A, It is a must to Communicate between F-F through a Activity because then only the Fragments become decoupled and self sustaining.
So passing data from A -> F is going to be the same as explained by ρяσѕρєя K. In addition to that answer, After creation of the Fragments inside an Activity, we can also pass data to the fragments calling methods in Fragments.
For example:
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
articleFrag.updateArticleView(position);
I would like to add for the beginners that the difference between the 2 most upvoted answers here is given by the different use of a fragment.
If you use the fragment within the java class where you have the data you want to pass, you can apply the first answer to pass data:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
If however you use for example the default code given by Android Studio for tabbed fragments, this code will not work.
It will not work even if you replace the default PlaceholderFragment with your FragmentClasses, and even if you correct the FragmentPagerAdapter to the new situation adding a switch for getItem() and another switch for getPageTitle() (as shown here)
Warning: the clip mentioned above has code errors, which I explain later here, but is useful to see how you go from default code to editable code for tabbed fragments)! The rest of my answer makes much more sense if you consider the java classes and xml files from that clip (representative for a first use of tabbed fragments by a beginner scenario).
The main reason the most upvoted answer from this page will not work is that in that default code for tabbed fragments, the fragments are used in another java class: FragmentPagerAdapter!
So, in order to send the data, you are tempted to create a bundle in the MotherActivity and pass it in the FragmentPagerAdapter, using answer no.2.
Only that is wrong again. (Probably you could do it like that, but it is just a complication which is not really needed).
The correct/easier way to do it, I think, is to pass the data directly to the fragment in question, using answer no.2.
Yes, there will be tight coupling between the Activity and the Fragment, BUT, for tabbed fragments, that is kind of expected. I would even advice you to create the tabbed fragments inside the MotherActivity java class (as subclasses, as they will never be used outside the MotherActivity) - it is easy, just add inside the MotherActivity java class as many Fragments as you need like this:
public static class Tab1 extends Fragment {
public Tab1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout_name_for_fragment_1, container, false);
return rootView;
}
}.
So, to pass data from the MotherActivity to such a Fragment you will need to create private Strings/Bundles above the onCreate of your Mother activity - which you can fill with the data you want to pass to the fragments, and pass them on via a method created after the onCreate (here called getMyData()).
public class MotherActivity extends Activity {
private String out;
private Bundle results;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mother_activity);
// for example get a value from the previous activity
Intent intent = getIntent();
out = intent.getExtras().getString("Key");
}
public Bundle getMyData() {
Bundle hm = new Bundle();
hm.putString("val1",out);
return hm;
}
}
And then in the fragment class, you use getMyData:
public static class Tab1 extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public Tab1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout_name_for_fragment_1, container, false);
TextView output = (TextView)rootView.findViewById(R.id.your_id_for_a_text_view_within_the_layout);
MotherActivity activity = (MotherActivity)getActivity();
Bundle results = activity.getMyData();
String value1 = results.getString("val1");
output.setText(value1);
return rootView;
}
}
If you have database queries I advice you to do them in the MotherActivity (and pass their results as Strings/Integers attached to keys inside a bundle as shown above), as inside the tabbed fragments, your syntax will become more complex (this becomes getActivity() for example, and getIntent becomes getActivity().getIntent), but you have also the option to do as you wish.
My advice for beginners is to focus on small steps. First, get your intent to open a very simple tabbed activity, without passing ANY data. Does it work? Does it open the tabs you expect? If not, why?
Start from that, and by applying solutions such as those presented in this clip, see what is missing. For that particular clip, the mainactivity.xml is never shown. That will surely confuse you. But if you pay attention, you will see that for example the context (tools:context) is wrong in the xml fragment files. Each fragment XML needs to point to the correct fragment class (or subclass using the separator $).
You will also see that in the main activity java class you need to add tabLayout.setupWithViewPager(mViewPager) - right after the line TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); without this line, your view is actually not linked to the XML files of the fragments, but it shows ONLY the xml file of the main activity.
In addition to the line in the main activity java class, in the main activity XML file you need to change the tabs to fit your situation (e.g. add or remove TabItems). If you do not have tabs in the main activity XML, then possibly you did not choose the correct activity type when you created it in the first place (new activity - tabbed activity).
Please note that in the last 3 paragraphs I talk about the video! So when I say main activity XML, it is the main activity XML in the video, which in your situation is the MotherActivity XML file.
If you pass a reference to the (concrete subclass of) fragment into the async task, you can then access the fragment directly.
Some ways of passing the fragment reference into the async task:
If your async task is a fully fledged class (class FooTask extends AsyncTask), then pass your fragment into the constructor.
If your async task is an inner class, just declare a final Fragment variable in the scope the async task is defined, or as a field of the outer class. You'll be able to access that from the inner class.
From Activity you send data with Bundle as:
Bundle bundle = new Bundle();
bundle.putString("data", "Data you want to send");
// Your fragment
MyFragment obj = new MyFragment();
obj.setArguments(bundle);
And in Fragment onCreateView method get the data:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
String data = getArguments().getString("data");// data which sent from activity
return inflater.inflate(R.layout.myfragment, container, false);
}
Sometimes you can receive Intent in your activity and you need to pass the info to your working fragment.
Given answers are OK if you need to start the fragment but if it's still working, setArguments() is not very useful.
Another problem occurs if the passed information will cause to interact with your UI. In that case you cannot call something like myfragment.passData() because android will quickly tells that only the thread which created the view can interact with.
So my proposal is to use a receiver. That way, you can send data from anywhere, including the activity, but the job will be done within the fragment's context.
In you fragment's onCreate():
protected DataReceiver dataReceiver;
public static final String REC_DATA = "REC_DATA";
#Override
public void onCreate(Bundle savedInstanceState) {
data Receiver = new DataReceiver();
intentFilter = new IntentFilter(REC_DATA);
getActivity().registerReceiver(dataReceiver, intentFilter);
}
private class DataReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int data= intent.getIntExtra("data", -1);
// Do anything including interact with your UI
}
}
In you activity:
// somewhere
Intent retIntent = new Intent(RE_DATA);
retIntent.putExtra("data", myData);
sendBroadcast(retIntent);
Very old post, still I dare to add a little explanation that would had been helpful for me.
Technically you can directly set members of any type in a fragment from activity.
So why Bundle?
The reason is very simple - Bundle provides uniform way to handle:-- creating/opening fragment
-- reconfiguration (screen rotation) - just add initial/updated bundle to outState in onSaveInstanceState()
-- app restoration after being garbage collected in background (as with reconfiguration).
You can (if you like experiments) create a workaround in simple situations but Bundle-approach just doesn't see difference between one fragment and one thousand on a backstack - it stays simple and straightforward. That's why the answer by #Elenasys is the most elegant and universal solution. And that's why the answer given by #Martin has pitfalls
If an activity needs to make a fragment perform an action after initialization, the easiest way is by having the activity invoke a method on the fragment instance. In the fragment, add a method:
public class DemoFragment extends Fragment {
public void doSomething(String param) {
// do something in fragment
}
}
and then in the activity, get access to the fragment using the fragment manager and call the method:
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DemoFragment fragmentDemo = (DemoFragment)
getSupportFragmentManager().findFragmentById(R.id.fragmentDemo);
fragmentDemo.doSomething("some param");
}
}
and then the activity can communicate directly with the fragment by invoking this method.
the better approach for sending data from activity class to fragment is passing via setter methods. Like
FragmentClass fragmentClass = new FragmentClass();
fragmentClass.setMyList(mylist);
fragmentClass.setMyString(myString);
fragmentClass.setMyMap(myMap);
and get these data from the class easily.
Use following interface to communicate between activity and fragment
public interface BundleListener {
void update(Bundle bundle);
Bundle getBundle();
}
Or use following this generic listener for two way communication using interface
/**
* Created by Qamar4P on 10/11/2017.
*/
public interface GenericConnector<T,E> {
T getData();
void updateData(E data);
void connect(GenericConnector<T,E> connector);
}
fragment show method
public static void show(AppCompatActivity activity) {
CustomValueDialogFragment dialog = new CustomValueDialogFragment();
dialog.connector = (GenericConnector) activity;
dialog.show(activity.getSupportFragmentManager(),"CustomValueDialogFragment");
}
you can cast your context to GenericConnector in onAttach(Context) too
in your activity
CustomValueDialogFragment.show(this);
in your fragment
...
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
connector.connect(new GenericConnector() {
#Override
public Object getData() {
return null;
}
#Override
public void updateData(Object data) {
}
#Override
public void connect(GenericConnector connector) {
}
});
}
...
public static void show(AppCompatActivity activity, GenericConnector connector) {
CustomValueDialogFragment dialog = new CustomValueDialogFragment();
dialog.connector = connector;
dialog.show(activity.getSupportFragmentManager(),"CustomValueDialogFragment");
}
Note: Never use it like "".toString().toString().toString(); way.
just stumbled across this question, while most of the methods above will work.
I just want to add that you can use the Event Bus Library, especially in scenarios where the component (Activity or Fragment) has not been created, its good for all sizes of android projects and many use cases. I have personally used it in several projects i have on playstore.
You can create public static method in fragment where you will get static reference of that fragment and then pass data to that function and set that data to argument in same method and get data via getArgument on oncreate method of fragment, and set that data to local variables.
I ran into a similar issue while using the latest Navigation architecture component. Tried out all the above-mentioned code with passing a bundle from my calling activity to Fragment.
The best solution, following the latest development trends in Android, is by using View Model (part of Android Jetpack).
Create and Initialize a ViewModel class in the parent Activity, Please note that this ViewModel has to be shared between the activity and fragment.
Now, Inside the onViewCreated() of the fragment, Initialize the Same ViewModel and setup Observers to listen to the ViewModel fields.
Here is a helpful, in-depth tutorial if you need.
https://medium.com/mindorks/how-to-communicate-between-fragments-and-activity-using-viewmodel-ca733233a51c
Kotlin version:
In Activity:
val bundle = Bundle()
bundle.putBoolean("YourKey1", true)
bundle.putString("YourKey2", "YourString")
val fragment = YourFragment()
fragment.arguments = bundle
val fragmentTransaction = parentFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.your_container, fragment, fragment.toString())
fragmentTransaction.commit()
In the Fragment onCreate():
var value1 = arguments?.getBoolean("YourKey1", default true/false)
var value2 = arguments?.getString("YourKey2", "Default String")
Smartest tried and tested way of passing data between fragments and activity is to create a variables,example:
class StorageUtil {
public static ArrayList<Employee> employees;
}
Then to pass data from fragment to activity, we do so in the onActivityCreated method:
//a field created in the sending fragment
ArrayList<Employee> employees;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
employees=new ArrayList();
//java 7 and above syntax for arraylist else use employees=new ArrayList<Employee>() for java 6 and below
//Adding first employee
Employee employee=new Employee("1","Andrew","Sam","1984-04-10","Male","Ghanaian");
employees.add(employee);
//Adding second employee
Employee employee=new Employee("1","Akuah","Morrison","1984-02-04","Female","Ghanaian");
employees.add(employee);
StorageUtil.employees=employees;
}
Now you can get the value of StorageUtil.employees from everywhere.
Goodluck!
My solution is to write a static method inside the fragment:
public TheFragment setData(TheData data) {
TheFragment tf = new TheFragment();
tf.data = data;
return tf;
}
This way I am sure that all the data I need is inside the Fragment before any other possible operation which could need to work with it.
Also it looks cleaner in my opinion.
You can make a setter method in the fragment. Then in the Activity, when you reference to the fragment, you call the setter method and pass it the data from you Activity
In your activity declare static variable
public static HashMap<String,ContactsModal> contactItems=new HashMap<String, ContactsModal>();
Then in your fragment do like follow
ActivityName.contactItems.put(Number,contactsModal);

Fragments, DialogFragment, and Screen Rotation

I have an Activity that calls setContentView with this XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
>
<fragment android:name="org.vt.indiatab.GroupFragment"
android:id="#+id/home_groups"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<..some other fragments ...>
</LinearLayout>
The GroupFragment extends Fragment, and all is well there. However, I show a DialogFragment from within GroupFragment. This shows correctly, HOWEVER when the screen rotates, I get a Force Close.
What's the proper way to display a DialogFragment from within another Fragment other than DialogFragment.show(FragmentManager, String)?
There's a bug in the compatibility library that can cause this. Try putting this in you dialogfragment:
#Override
public void onDestroyView() {
if (getDialog() != null && getRetainInstance())
getDialog().setOnDismissListener(null);
super.onDestroyView();
}
I also suggest setting your dialogfragment as retained, so it won't get dismissed after the rotation. Put "setRetainInstance(true);" e.g. in the onCreate() method.
OK, while Zsombor's method works, this is due to me being inexperienced with Fragments and his solution causes issues with the saveInstanceState Bundle.
Apparently (at least for a DialogFragment), it should be a public static class. You also MUST write your own static DialogFragment newInstance() method. This is because the Fragment class calls the newInstance method in its instantiate() method.
So in conclusion, you MUST write your DialogFragments like so:
public static class MyDialogFragment extends DialogFragment {
static MyDialogFragment newInstance() {
MyDialogFragment d = new MyDialogFragment();
return d;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
}
}
And show them with:
private void showMyDialog() {
MyDialogFragment d = MyDialogFragment.newInstance();
d.show(getFragmentManager(), "dialog");
}
This may be unique to the ActionBarSherlock Library, but the official samples in the SDK documentation use this paradigm also.
To overcome the Bundle always being null, I save it to a static field in onSaveInstanceState. It's a code smell, but the only solution I found for both restoring the dialog and saving the state.
The Bundle reference should be nulled in onDestroy.
#Override
public void onCreate(Bundle savedInstanceState)
{
if (savedInstanceState == null)
savedInstanceState = HackishSavedState.savedInstanceState;
setRetainInstance(true);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
if (savedInstanceState == null)
savedInstanceState = HackishSavedState.savedInstanceState;
...
}
#Override
public void onDestroyView() // necessary for restoring the dialog
{
if (getDialog() != null && getRetainInstance())
getDialog().setOnDismissListener(null);
super.onDestroyView();
}
#Override
public void onSaveInstanceState(Bundle outState)
{
...
HackishSavedState.savedInstanceState = outState;
super.onSaveInstanceState(outState);
}
#Override
public void onDestroy()
{
HackishSavedState.savedInstanceState = null;
super.onDestroy();
}
private static class HackishSavedState
{
static Bundle savedInstanceState;
}
I used a mix of the presented solutions and added one more thing.
This is my final solution:
I used setRetainInstance(true) in the onCreateDialog;
I used this:
public void onDestroyView() {
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
And as a workaround of the savedInstanceState not working, I created a private class called StateHolder (the same way a holder is create for a listView):
private class StateHolder {
String name;
String quantity;
}
I save the state this way:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
stateHolder = new StateHolder();
stateHolder.name = actvProductName.getText().toString();
stateHolder.quantity = etProductQuantity.getText().toString();
}
In the onDismiss method I set the stateHolder back to null. When the dialog is created, it verifies if the stateHolder isn't null to recover the state or just initialize everything normally.
I solved this issue with answers of #ZsomborErdődy-Nagy and #AndyDennie . You must subclass this class and in you parent fragment call setRetainInstance(true), and dialogFragment.show(getFragmentManager(), "Dialog");
public class AbstractDialogFragment extends DialogFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onDestroyView() {
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
}
I had a similar issue, however none of the above worked for me. In the end I needed to create the fragment in code instead of in the XML layout.
See: Replacing fragments and orientation change
I ran into this on my project and none of the above solutions helped.
If the exception looks something like
java.lang.RuntimeException: Unable to start activity ComponentInfo{
...
Caused by: java.lang.IllegalStateException: Fragment....
did not create a view.
It's caused by an issue with a fallback container Id that gets used after rotation. See this ticket for more details:
https://code.google.com/p/android/issues/detail?id=18529
Basically you can prevent the crash by making sure all of your xml fragments have a tag defined in the layout. This prevents the fallback condition from occurring if you rotate when a fragment is visible.
In my case I was able to apply this fix without having to override onDestroyView() or setRetainInstance(true), which is the common recommendation for this situation.
I encountered this problem and the onDestroyView() trick wasn't working. It turned out that it was because I was doing some rather intensive dialog creation in onCreate(). This included saving a reference to the AlertDialog, which I would then return in onCreateDialog().
When I moved all of this code to onCreateDialog() and stopped retaining a reference to the dialog, it started working again. I expect I was violating one of the invariants DialogFragment has about managing its dialog.
In onCreate() call setRetainInstance(true) and then include this:
#Override
public void onDestroyView() {
if (getDialog() != null && getRetainInstance()) {
getDialog().setOnDismissMessage(null);
}
super.onDestroyView();
}
When you call setRetainInstance(true) in onCreate(), onCreate() will no longer be called across orientation changes, but onCreateView() will still be called.
So you can still save the state to your bundle in onSaveInstanceState() and then retrieve it in onCreateView():
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("myInt", myInt);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_layout, container);
if (savedInstanceState != null) {
myInt = savedInstanceState.getInt("myInt");
}
...
return view;
}

View was clear data when screen rotation in Android

I have a View that was created on runtime then I draw some canvas on that View(runtime) after that I rotated my screen.All data was gone(reset).So I put the some code in AndroidManifest.xml like this
android:configChanges="keyboardHidden|orientation"
in my <activity> then I put a #Override function
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout) findViewById(R.id.myPaint);
layout.addView(mView);
}
but everything couldn't solved my problem.I want to keep my data from View(runtime) on every single rotation.
That's my onCreate function.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mView = new MyView(this);
setContentView(mView);
mView.requestFocus();
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout) findViewById(R.id.myPaint);
layout.addView(mView);
}
You need to save and load the data you want to retain. Even though you're handling the screen rotation yourself when you modified the Manifest the way you did, you're still reloading the view yourself. Reread the reference document on Handling Runtime Changes. You need to store your data and reload it accordingly. Otherwise it will be lost when the application restarts or when you reload your ContentView.
http://developer.android.com/guide/topics/resources/runtime-changes.html
You could approach this a few ways.
I assume MyView is your own class which extends View. If so there are two methods which you may care to know, onSaveInstanceState() and onRestoreInstanceState(). When saving you create a parcelable that will contain enough data for you to re-render your view if it were to be destroyed and recreated.
class MyView extends View {
private String mString;
onDraw(Canvas v) { ... }
Parcelable onSaveInstanceState() {
Bundle b = new Bundle();
bundle.putString("STRING", mString);
return b;
void onRestoreInstanceState(Parcelable c) {
Bundle b = (Bundle) c;
mString = bundle.getString("STRING", null);
}
}
Activity has similar state saving mechanics allowed in onCreate and onSaveInstanceState() (inside Activity, not View in this case) which will allow the activity to reset the state of it's view to the state it desires.
This should solve most of your worries. If you are wanting to use the onConfigurationChanged method, then you should reclarify your question as it is not clear what the current behavior is that you aren't expecting in each situation (only using onConfigurationChanged, or only using onCreate, or using both, etc).
I've just used my data-class as singleton (java-pattern).
And it works fine.
--> Application is a Stop-Timer for Racing, where i can stop time from different opponents on the track, so i need the data for longer time, also if the view is repainted.
regz
public class Drivers {
// this is my singleton data-class for timing
private static Drivers instance = null;
public static Drivers getInstance() {
if (instance == null) {
instance = new Drivers();
}
return instance;
}
// some Timer-Definitions.......
}
Then in MainActivity:
// now the class is static, and will alive during application is running
private Drivers drivers = Drivers.getInstance();
#Override
public void onClick(View v) {
if (v == runButton1) {
drivers.startTimer1();
// do some other crazy stuff ...
}
}
// here i put out the current timing every second
private myUpdateFunction(){
time01.setText(drivers.getTimer1());
// update other timers etc ...
}

Categories

Resources