I have 2 fragments, which are being replaced in a container inside the main activity layout. One fragment passes the data through an interface whenever clicking on the button. When I click the button, I want my first fragment to be replaced with the second fragment, in the same container. However, I have an issue...
In the second fragment, I need to get the data and use it on a view. Now, in the second fragment, I have a method for getting the data. In the activity, I know that I need to find the ID of the second fragment in order to use its method. However, this fragment doesn't have any ID (because I'm going through fragments by code). Since I can't find the ID of the fragment, I'm getting an error and I can't pass the data to the second fragment.
How to solve this? Can it be solved?
Thank you very much!
You can get the fragment by ID if you have it in XML layout.
If you are handling your fragment in code, you can use a TAG and find it by that.
Starting a fragment
String FRAGMENT_TAG = "myFragment";
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().add(R.id.container, new MyFragment(), FRAGMENT_TAG).commit();
Getting the fragment by TAG
MyFragment fragment = (MyFragment) manager.findFragmentByTag(FRAGMENT_TAG);
if (fragment != null) {
fragment.passData(data);
}
You should define a static constant for fragment argument and then call newInstance from second fragment to initialize first fragment and passing data from 1 to 2
Below code is example of above description:
private static final String ARG_DATE = "date";
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(ARG_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
to retrieve/resolve DatePickerFragment argument data:
Date date = (Date) getArguments().getSerializable(ARG_DATE);
to initialize Fragment in another xxxFragment(that's mean pass the crime's date data from xxFragment to DatePickerFragment):
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
you can check out my github repository to understand %100
[https://github.com/Zfr21/CriminalIntent/commit/2ed69c056988818f6f6423762c97a6bf1a82b547][1]
Related
I have a typo regarding getting value from bundle and show it in the Fragment.
My song class has two values title and its detail.
private String songTitle;
private String details;
After sending value from bundle in Adapter part, I get it from Detail Part by doing vice versa process. I show it via getSupportFragmentManager feature.
Although the detail page open without any problem, there is no value in Detail part.
Here is my Detail part and Fragment part.
How can I fix it?
Detail Part
if (savedInstanceState == null) {
// Get the selected song position from the intent extra.
int selectedSong =
getIntent().getIntExtra(SongUtil.SONG_ID_KEY, 0);
Log.i(LOG,"selectedSong : " + selectedSong);
// Create instance of the detail fragment and add it to the activity
// using a fragment transaction.
SongDetailFragment fragment =
SongDetailFragment.newInstance(selectedSong);
getSupportFragmentManager().beginTransaction()
.add(R.id.song_detail_container, fragment)
.commit();
}
Detail Fragment
public static SongDetailFragment newInstance (int selectedSong) {
SongDetailFragment fragment = new SongDetailFragment();
// Set the bundle arguments for the fragment.
Bundle arguments = new Bundle();
arguments.putInt(SongUtil.SONG_ID_KEY, selectedSong);
fragment.setArguments(arguments);
return fragment;
}
Link : Project Link
I solve it by defined static methods for list process in which items are inserted
I am trying to send a data from MainActivity (on MenuItem click) to a Fragment of its Child Fragment.
I have shown an image to understand better.
I want an event to be fired in DayFragment from the MainActivity when MainActivity menuclicked.
I cannot send when the fragment is being created as you know.
Any ideas (or) code to understand the idea would be helpful.
Guys, Negative vote would neither help you nor me.
I will explain in little detail.
I am going to show a datepicker dialog fragment on menu item click on MainActivity. I need to pass the date from MainActivity -> calendarfragment - > dayfragment.
I want the date in dayfragment to other process. Thats it.
Create a public method inside Fragment which the Activity will call upon item selection.
From that public method, using the instance of ChildFragment, call another public method inside ChildFragment to make the magic happen!
You can use Fragment.setTarget(Fragment fragment, int requestCode); , just in case
Use a Bundle. Here's an example:
Fragment fragment = new Fragment(); // replace your custom fragment class
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager(). beginTransaction();
bundle.putString("key","value"); // use as per your need
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(viewID,fragment);
fragmentTransaction.commit();
Bundle has put methods for lots of data types.
Then in your Fragment, retrieve the data (e.g. in onCreate() method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);
}
Hey I was wondering how I could transfer data from one activity to a fragment using fire base. I have edit text in the activity class and a list view in the Fragment.
I would like to display the information throughout the app database so that other users can see and edit the information too.
I dont know if the IDE matters but passing information to a fragment is usually done with fragment arguments. You need to create a static "newInstance" method in your fragment that you can call from the activity and pass whatever info to the fragment through it. Something like this:
public static mListFragment newInstance(String fromActivity) {
mListFragment fragment = new mListFragment ();
Bundle args = new Bundle();
args.putString("STIRNG_FROM_ACTIVITY", fromActivity);
fragment.setArguments(args);
return fragment;
}
You can then call the method from the activity like this:
FragmentManager fm = getFragmentManager().beginTransaction();
mListFragment fragment = new mListFragment();
fragment = mListFragment.newInstance("info_to_send");
fragmentTransaction.add(R.id.fragments_frame, fragment);
From here you can even persist the info across device screen orientation changes..
Just use firebaseRef to setValue() and set the value from the edittext.
Add ValueListener on the fragment to get the same value from dataSnapshot.
:D
https://github.com/firebase/quickstart-java/tree/master/database/src/main/java/com/google/firebase/quickstart
I have an activity that calls to a web service and I want to pass these result to a fragment. Obviously the web service is invoked by an AsyncTask, so the fragment is loaded before getting result.
How can I pass this paramteter from activity's AsyncTask to fragment when is received?
You can implement a method inside your Fragment and call it when needed. For bidirectional communication between an Activity and a Fragment see http://developer.android.com/training/basics/fragments/communicating.html
Set bundle in your fragment.
Bundle args = new Bundle();
args.putInt("id",value);
Fragment newFragment = new Fragment();
newFragment.setArguments(args);
In your fragment get the bundle as
Bundle b = getArguments();
String s = b.getInt("id");
You could move the AsyncTask into the fragment.
But if you wish to keep your current set up, you should save the Fragment reference when you initialize it, and create a public function in the fragment that takes the new data as a parameter.
So the activity code could look like this:
MyFragment fragment = new MyFragment();
getFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit();
and then you could call:
fragment.updateData(myNewData);
Just make sure to do the appropriate null-checks, just to be safe.
i have a internal discussion about what way is better to share info between fragments contents inside a controller activity. In a first classical way, you can set arguments when you are going to replace fragments as follows:
//Just now i'm inside Fragment 1 and i'll navigate to Fragment 2
Fragment newFragment = getFragmentManager().findFragmentByTag(Fragment2.TAG);
Bundle b = new Bundle();
b.putBoolean("test1", true);
// Create new fragment and transaction
if(newFragment==null)
newFragment = Fragment2.newInstance(b);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)//.setCustomAnimations(R.anim.enter_anim, R.anim.exit_anim)
.replace(R.id.fragment_place, newFragment, Fragment2.class.getName())
.addToBackStack(newFragment.getClass().getName())
.commit();
The newInstace method does as i meant above, so, with setArguments:
public static Fragment2 newInstance(Bundle arguments){
Fragment2 f = new Fragment2();
if(arguments != null){
f.setArguments(arguments);
}
return f;
}
But Fragment1 and Fragment2 they are both inside a ControllerActivity, so i can also think about a second way to share information obtained in Fragment1 towards Fragment2, through declaring attributes in the ControllerActivity, so i could do (declaring previously an object in the activity) as follows inside any fragment:
EDIT
public class ControllerActivity extends FragmentActivity{
int value = 5;
...
And then, inside my fragment:
((SplashActivity)getActivity()).value = 10; //i can assign or recover value when i desire
My question is what inconveniences would have doing as the second way.
Writing code using 2nd way is fast. But the problem is you have to cast the general Activity to the more specific SplashActivity in which the value variable exists. If you want to use the Fragment with another Activity, or you want a Fragment to be a general purpose UI component you have to use interface for passing the data.
As mentioned in comments, bellow links provide more details about interface/callback method:
android docs
video from slidenerd
Hope this answers your question.