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
OK this is how you send data to your fragments from activity
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.