Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Casey Bell
2,604 PointsPassing Data from Activity to Fragment
My app has a main activity with a navigation drawer that has several fragments. In one fragment, I want the user in input some information and press a button which navigates them to an activity. The user will enter information within the activity and press a button to return back to the fragment with their information saved. Essentially, I want to pass data from the activity to the fragment. I have created a bundle to pass the data, but I am getting a null pointer exception when I click on the fragment in the navigation drawer. It won't even open Any thoughts?
Java
//The button in the activity to pass data
@Override
public void onClick(View view) {
Bundle objectId = new Bundle();
objectId.putString(Worker.KEY_WORKER_OBJECTID, mPayload);
StartWorkFragment passId = new StartWorkFragment();
passId.setArguments(objectId);
finish();
}
});
Java
//Fragment where I am trying to receive the passed data from the Activity
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_start_work_tag, container, false);
mIdTestView = (TextView) rootView.findViewById(R.id.testing_worker_id_pass);
mTagObjectId = this.getArguments().getString(Worker.KEY_WORKER_OBJECTID);
mIdTestView.setText(mTagObjectId);
return rootView;
}
}