Assign data to activity variable from fragment, and get variable in another fragment

£可爱£侵袭症+ 提交于 2020-01-13 19:23:07

问题


I have an android application. Which have one activity with two fragments.

When my application starts it assigns data to a variable in his activity. Then on the click of a button second fragment opens and it takes data from his activity which is assigned in activity. But it returns null. What I have tried so far is...

I made variable in my activity class and assign data from my fragment like this.

((MainActivity)getActivity()).resultObj = gson.fromJson(HomeCardString.toString(), HomeCardResult.class);

and it assigned perfectly as i have used this data in same fragment like this

HomeCardListItemAdapter adapter = new HomeCardListItemAdapter(getActivity(),
            R.layout.home_cardlist_item, ((MainActivity)getActivity()).resultObj.HomeData.FriendSummary);

Which works perfect.

But when I opened my second fragment on a click, it just shows my the layout without executing any of its override method. like oncontentview etc, As these all method were executed at the start of activity. But at that time i haven't assigned the data to my activity's variable. So i made my own method and call it right after showing my second fragment like this.

showFragment(FRIENDLIST, true);
FriendListActivity asdss = new FriendListActivity(); // this is my second fragment
asdss.populateFriendList();

And in second fragment I have that method with this code.

public void populateFriendList()
{
    FriendList = ((MainActivity)getActivity()).resultObj.HomeData.Friends;
    String asd = FriendList.toString();
    asd = asd + "asdasda";
}

But after [FriendList = ((MainActivity)getActivity()).resultObj.HomeData.Friends;] this line it shows invocationtargetexception.class file with written source not found in it.

And in logcat this error appears.

07-24 12:06:47.204: E/AndroidRuntime(3926): java.lang.NullPointerException


回答1:


OK this is how you send data to your fragments from activity


(In your Activity)

// You create a bundle

Bundle bundle = new Bundle();

// Add data to your the bundle

bundle.putInt("key", your_data); //e.g. adding integer, you can do similar for other data types


// Pass bundle to the fragment using setArguments()

your_fragment.setArguments(bundle);

(In your Fragment class)

Bundle bundle = getArguments();
Integer your_data = bundle.getInt("key", default_value);

Note: You can even pass objects to fragments. For that you need to make your object class "Parcelable" and call bundle.putParcelable("key", your_object);

Play around with what sort of data types you can pass to fragments. Please do ask if you get stuck on any sort of problem.



来源:https://stackoverflow.com/questions/24927210/assign-data-to-activity-variable-from-fragment-and-get-variable-in-another-frag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!