Assign data to activity variable from fragment, an

2019-05-25 21:03发布

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条回答
干净又极端
2楼-- · 2019-05-25 21:35

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.

查看更多
登录 后发表回答