I have placed three edit text in a fragment and want to get the values of the edit text in the fragment from the main activity. I tried the following code but its throwing
f1 = new Fragment()
This is not how you add fragments. You are just creating a new fragment instance here. The fragment's onCreateView never gets called because the fragment has not been added. Due to this, the editText variable is null and you get the exception. Please study fragments a little bit.
http://www.vogella.com/tutorials/AndroidFragments/article.html
This is how you add a fragment :
getSupportFragmentManager().beginTransaction().add(R.id.frag_layout_id, f1, "fragment_identifier").commit();
EDIT
Since the question has been edited with the xml, although you have declared the fragment in XML, the f1 instance in your java does not refer to that. To get a handle for the instance added through xml, use this
Fragment_Example f1 = (Fragment_Example)getSupportFragmentManager().findFragmentById(R.id.fragment);
The thing is f1 = new Fragment1();
you have just created a object for fragment
class, but this is not the exact way to call the fragment
. You are supposed to set transition
using the fragmentManager
. If you didn't set in this way, then the frgament Lifecycle
method's won't be called. So, in your scenario onCreateView()
won't be called and the views are not initialized(As your stackTrace clearly states the view is not initialized). Try the below code
f1 = new MainFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, f1,
f1 .getClass().getSimpleName()).addToBackStack(null).commit();
I hope you are aware of the other fragment container.i.e., having a FrameLayout
in MainActivity
and adding the Fragment
to that container.
Hope this is helpful:)
I think you name, age, and gender views are not initialized: try changing your onCreateView() like this
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag1, container);
name = (EditText) view.findViewById(R.id.your_id);
age = (EditText) view.findViewById(R.id.your_id);
gender = (EditText) view.findViewById(R.id.your_id);
return view;
}