Trouble Passing object Fragment to Fragment - android

I am trying to pass an object Fragment -> Activity -> Fragment.
My 2nd Fragment says my object is null when getting arguments:
Fragment A: (Sending Object, communicator is interface to Main Activity)
meetsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Meet meet = new Meet();
meet = meetList.get(position); // meet is not null here
communicator.changeToolbarTitle(meet.getName());
****** Sends Meet object to main activity ********
communicator.sendMeetToMeetProfile(meet);
}
});
Main Activity:
#Override
public void sendMeetToMeetProfile(Meet meet) {
MeetAthletesListContainer meetAthletesListContainer = new MeetAthletesListContainer();
***** Fragment is not replaced just called *******
MeetAthletesMales meetAthletesMales = new MeetAthletesMales();
MeetAthletesFemales meetAthletesFemales = new MeetAthletesFemales();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Bundle bundleMales = new Bundle();
bundleMales.putParcelable("meetAthletesMales", meet);
meetAthletesMales.setArguments(bundleMales);
Bundle bundleFemales = new Bundle();
bundleFemales.putParcelable("meetAthletesFemales", meet);
meetAthletesFemales.setArguments(bundleFemales);
******* Replaces current fragment with container that contains above (2) fragments *******
transaction.replace(R.id.frameLayout, meetAthletesListContainer, "meetAthletesListContainer");
transaction.addToBackStack(null);
transaction.commit();
}
Fragment B: (Fragment is contained inside another fragment)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_meet_athletes_males, container, false);
Log.e("", "Fragment onCreateView Called!");
initializeVar();
*****Says this meet object is null*****
meet = getArguments().getParcelable("meetAthletesMales");
}
I am replacing a fragment with another but passing the object to a fragment which is inside another fragment(meet_container_fragment). So my object is being sent directly to the fragment. I got this working in another instance where I actually replace the fragment but I want to replace the FRAGMENT CONTAINER, not the actual fragment B

Try this
MeetAthletesListContainer meetAthletesListContainer = new MeetAthletesListContainer();
***** Fragment is not replaced just called *******
MeetAthletesMales meetAthletesMales = new MeetAthletesMales();
MeetAthletesFemales meetAthletesFemales = new MeetAthletesFemales();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
bundle.putParcelable("meetAthletesMales", meet);
bundle.putParcelable("meetAthletesFemales", meet);
meetAthletesFemales.setArguments(bundle);
******* Replaces current fragment with container that contains above (2) fragments *******
transaction.replace(R.id.frameLayout, meetAthletesListContainer, "meetAthletesListContainer");
transaction.addToBackStack(null);
transaction.commit();

Try this,
main activity
FragmentB fragmentb = FragmentB.newInstance(appContext,meet);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.contentContainer, fragmentb , tag);
Fragment B
public static FragmentB newInstance(AppContext appContext, Meet meet) {
FragmentB fragment = new FragmentB();
Bundle args = new Bundle();
args.putSerializable(ARG_APP_CONTEXT, appContext);
args.putString(ARG_MEET_NAME, meet.name);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
appContext = (AppContext) getArguments().get(ARG_APP_CONTEXT);
name= getArguments().getString(ARG_MEET_NAME);
}
}
also make Meet implements Serializable

Related

Transfer data from one fragment to another fragment

I am developing an app in which I have used bottom navigation bar so for that I had to use fragments. In my fragments, I implemented Recycler view. So My question is when I click on an item of recycler view, how can I navigate to another fragment (which is in a different item of the bottom navigation bar) and how can I transfer the data between two fragments. Please Help.
during onClick() pass data through bundle
like that
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
Bundle bundleobj = new Bundle();
bundleobj.putCharSequence("key", data);
Fragment2 fragobj = new Fragment2();
fragobj.setArguments(bundleobj);
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.replace(R.id.containerView, fragobj).commit();
In Fragment2 class:
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle =getArguments();
if(null!=bundle) {
myData=bundle.getCharSequence("key");
}
}
In first Fragment..
Fragment fragment = new EditExamFragment();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
Bundle bundle = new Bundle();
bundle.putString("branch_id", mDataset.get(position).getiBranchId());
bundle.putString("exam_id",mDataset.get(position).getiExamId());
fragment.setArguments(bundle);
In Second Fragment for fetching values try below code;
String branch_id, exam_id ;
final Bundle bundle = this.getArguments();
if (bundle != null) {
branch_id = bundle.getString("branch_id");
exam_id = bundle.getString("exam_id");
}
Add below code after event listener in fragment1
SecondFragmentName secondFragmentName = new SecondFragmentName();
Bundle args = new Bundle();
args.putString("key", "value");
secondFragmentName.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.content_frame, secondFragmentName).addToBackStack("Some string").commit();
To get value in Fragment2
String message = getArguments().getString("key");

How can pass array list object from an activity to fragment in android

I am storing some values in array list now i want to pass the same array list object to fragment from an activity. So how can i send the array list object from an activity and receive the same object in fragment.
Try this code in your activity, It is a code snippet from my working application.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourArrayList.add("test");
yourArrayList.add("test2")
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayList", yourArrayList);
yourFragment yourFragment = new yourFragment();
yourFragment.setArguments(bundle);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container, yourFragment);
fragmentTransaction.commit();
}
In your fragment you can access the value like this
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<String> values = getArguments().getStringArrayList("arrayList");
}
pass activity should follow this lines
Bundle bundle = new Bundle();
bundle.putStringArrayList("valuesArray", namesArray);
namesFragment myFragment = new namesFragment();
myFragment.setArguments(bundle);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container, myFragment);
fragmentTransaction.commit();
get Fragment inside follow this lines
ArrayList<ObjectName> arraylist = extras.getParcelableArrayList("valuesArray");
You can do this by following the usual way of Fragment-Activity communication. That is:
1) Declare a public interface within your Fragment class.
2) Inside this interface declare a getter method for your list.
3) Make your respective Activity implement this interface.
4) Inside your Fragment, do this:
#Override
public void onAttach(Context context) {
super.onAttach(context);
YourInterfaceType activity = (YourInterfaceType) context;
List<> yourList = activity.getMyList();
}
To make it more clear:
Your activity will be as follows:
public class MyActivity extends Activity implements YourInterfaceType{
#Override
public void getMyList(){
return yourList;
}
}
just put your array with setargument in Actiivty and get Array
getArgument in fragment.
Activity
Bundle bundle = new Bundle();
bundle.putStringArrayList("valuesArray", namesArray);
namesFragment myFragment = new namesFragment();
myFragment.setArguments(bundle);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container, myFragment);
fragmentTransaction.commit();
fragment
ArrayList<Model> values = getArguments().getStringArrayList("valuesArray");

How to add fragment on activity in android? [duplicate]

This question already has answers here:
Start a fragment via Intent within a Fragment
(5 answers)
Closed 6 years ago.
i want to replace activity to a fragment, this code is not working.
Intent intent = new Intent(Activity.this, Fragment.class);
startActivity(intent);
finish();
You cannot switch from an Activity to Fragment, because a Fragment does not have its own existence without an Activity. i.e. a Fragment works inside an Activity.
Basically, Fragments are mainly used to create multi-pane screens.
Inside an Activity if you can replace Fragments (associated with the Activity) as mentioned in the above code examples to change the UI.
Try like this in your activity
#Override
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
} else {
getSupportFragmentManager().popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
transaction.replace(R.id.flContent, fragment);
transaction.commitAllowingStateLoss();
getSupportFragmentManager().executePendingTransactions();
}
and use like this
YourFragment mYourFrag = new YourFragment ();
replaceFragment(mYourFrag , false);
Create a Fragmen class like
public class FragmentName extends android.support.v4.app.Fragment {}
And then you are able to cast a activity to view like:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View returner = null;
Intent intent = new Intent([CONTEXT],[CLASSNAME.class]);
Bundle args = this.getArguments();
final Window w = [LocalActivityManager].startActivity("Title", intent);
final View wd = w != null ? w.getDecorView() : null;
if (wd != null) {
ViewParent parent = wd.getParent();
if(parent != null) {
ViewGroup v = (ViewGroup)parent;
v.removeView(wd);
}
wd.setVisibility(View.VISIBLE);
wd.setFocusableInTouchMode(true);
if(wd instanceof ViewGroup) {
((ViewGroup) wd).setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
}
}
returner = wd;
return returner;
}

Cant understand fragment replace

I have trouble understanding in FragmentTransaction.replace(id, fragment, 'string') what does .replace actually
I read somewhere that it will replace the content of view id with fragment but in my
public class MainActivity extends
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_container) !=null) {
if(savedInstanceState!=null){
return ;
}
ArticleFragment first_fragment = new ArticleFragment();
HeadlineFragment second_fragment = new HeadlineFragment();
first_fragment.setArguments(getIntent().getExtras());
second_fragment.setArguments(getIntent().getExtras());
FragmentTransaction manager=getSupportFragmentManager().beginTransaction();
manager.add(R.id.fragment_container, first_fragment,"first");
manager.add(R.id.fragment_container, second_fragment,"second");
manager.commit();
}
abc newFragment = new abc();
Bundle args = new Bundle();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment,"second");
transaction.addToBackStack(null);
transaction.commit();
}
}
it only replaces the first fragment that i added to Transaction, i.e. first_fragment.
And how do i replace a specific fragment?
The issue seems to be with R.id.fragment_container. You should have a different first argument on the line below in order to replace a fragment that is not your "first" fragment:
manager.add(R.id.fragment_container, second_fragment,"second");

Fragment already active - When trying to setArguments

I am using the example give in the below link
http://android-er.blogspot.in/2013/04/handle-onlistitemclick-of-listfragment.html
Here i have two classes one extending List Fragment and other extending Fragment.
Now i am passing object to detailfragment in this way :
*from ListFragment *
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Detailfragment detailFragment = (Detailfragment)getFragmentManager().findFragmentById(detailFragmentID);
Bundle bundle = new Bundle();
bundle.putSerializable(BUNDLE_KEY, obj);// passing this object
detailFragment.setArguments(bundle);
detailFragment.setUpLayout();// update the UI
}
Now in the Fragment class i receive it,basic goal is to update the UI of the fragment based on the item selected in the list fragment, thats the reason i am sending the object
Bundle b = getArguments();
b.getSerializable(BUNDLE_KEY);
Now on item selected it says "Fragment already active".
What is the issue here? what am i doing wrong?
Another solution is to create an empty constructor for your fragment.
public Detailfragment() {
super();
// Just to be an empty Bundle. You can use this later with getArguments().set...
setArguments(new Bundle());
}
and in the onListItemClick method you use that bundle:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Detailfragment detailFragment = (Detailfragment)getFragmentManager().findFragmentById(detailFragmentID);
// Update the keys.
detailFragment.getArguments().putSerializable(BUNDLE_KEY, obj);// passing this object
detailFragment.setUpLayout();// update the UI
}
Now you can call the getArguments() methond in your setUpLayout() method.
From the Official Android development Reference:
public void setArguments (Bundle args) Supply the construction arguments for this fragment. This can only be called before the fragment has been attached to its activity; that is, you should call it immediately after constructing the fragment. The arguments supplied here will be retained across fragment destroy and creation.
Your fragment is already attached to its activity
i suggest you to use your own method, you don't need setArguments!
create your own setUIArguments(Bundle args) inside the fragment class and update the fragment UI inside this method
You will call this method in this way:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Detailfragment detailFragment = (Detailfragment)getFragmentManager().findFragmentById(detailFragmentID);
Bundle bundle = new Bundle();
bundle.putSerializable(BUNDLE_KEY, obj);// passing this object
detailFragment.setUIArguments(bundle); /* your new method */
}
in your fragment class
public void setUIArguments(Bundle args) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
/* do your UI stuffs */
}
}
}
You can check if there are already arguments, and if so just add/update them.
private static void initFrag(Fragment frag, Bundle args) {
if (frag.getArguments() == null) {
frag.setArguments(args);
} else {
//Consider explicitly clearing arguments here
frag.getArguments().putAll(args);
}
}
Optionally, you might want to clear away existing arguments if you can't safely assume that pre-existing arguments are still valid.
This one global variable:
private FragmentManager fragmentmanager;
private FragmentTransaction fragmenttransaction;
These code put in your "List Fragment" onCreate() Activity :
fragmenttransaction = fragmentmanager.beginTransaction();
fragmenttransaction.replace(detailFragmentID, detailFragment, "test");
fragmenttransaction.addToBackStack(null);
fragmenttransaction.commit();
These is Drawerlistitem click event:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Bundle bundle = new Bundle();
fragmenttransaction = fragmentmanager.beginTransaction();
if(fragmentmanager.findFragmentById("test") != null) {
fragmenttransaction.remove(fragmentmanager.findFragmentByTag("test"));
}
Detailfragment detailFragment = (Detailfragment)getFragmentManager().findFragmentById(detailFragmentID);
bundle.putSerializable(BUNDLE_KEY, obj);// passing this object
detailFragment.setArguments(bundle);
fragmenttransaction.replace(detailFragmentID, detailFragment, "test");
fragmenttransaction.addToBackStack(null);
fragmenttransaction.commit();
}
Now Extending Fragment code as it is:
Bundle b = getArguments();
b.getSerializable(BUNDLE_KEY);
Dialogue fragment's public method
public void setBundle(final Bundle bundle) {
final Bundle arguments = getArguments();
arguments.clear();
arguments.putAll(bundle);
}
Show or update dialogue fragment
public void showMessageDialogue(final String tag, final Bundle bundle) {
final Fragment fragment = mFragmentManager.findFragmentByTag(tag);
if (fragment != null && fragment instanceof MessageDialogueFragment) {
((MessageDialogueFragment) fragment).setBundle(bundle);
} else {
final MessageDialogueFragment messageDialogueFragment = new MessageDialogueFragment();
messageDialogueFragment.setArguments(bundle);
messageDialogueFragment.show(mFragmentManager, tag);
}
}

Categories

Resources