I am writing an application with tabs on the main screen. When I click on the main button, I need to get data from several EditText inside fragments that the user entered.
To initialize EditText use this code:

 private EditText editText; @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_1, container, false); editText = (EditText) view.findViewById(R.id.editText); return view; } public MyValues getValues() { final MyValues val = new MyValues(); //doWork val.someTxt = editText.getText() return val; } 

When the getValues method getValues called from another class, I get - NullPointerException on the line:

val.someTxt = editText.getText() .

From the android documentation :

[onCreateView] ( https://developer.android.com/reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater , android.view.ViewGroup, android.os.Bundle))
The system calls this method when the fragment user interface is first displayed on the display. To draw a fragment user interface, return the View object from this method, which is the root in the fragment layout. If the fragment does not have a user interface, you can return null.

If I understand correctly, the onCreateView method onCreateView not executed, if the user has not opened this tab and then the editText variable editText not initialized!

  • one
    Yes, you understood correctly. And you just can not get this edittext because it simply does not exist. And if it does not exist, then the text in it is null. You can think of it as null, or as an empty string if it has not yet been initialized. - Vladyslav Matviienko
  • @metalurgus, the question is how to find the View from the undisclosed fragment. - Real KEK

1 answer 1

In MainActivity I wrote:

 private static Context cntxt; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cntxt = this; //my logic } 

In the fragment code:

 private EditText editText; private boolean flag = false; private View v; @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!flag) { flag = true; v = inflater.inflate(R.layout.fragment_1, container, false); editText = (EditText) v.findViewById(R.id.editText); } return v; } public MyValues getValues() { final MyValues val = new MyValues(); if (!flag) { flag = true; LayoutInflater inflater = LayoutInflater.from(MainActivity.cntxt); View v = inflater.inflate(R.layout.my_fragment, null, false); edtText = (EditText) v.findViewById(R.id.editText); } val.someTxt = editText.getText() return val; }