Input element not initializing correctly

时间:2016-12-02 05:12:26

标签: android android-fragments android-viewpager

My Android app contains an activity with multiple tabs implemented with ViewPager and TabLayout elements. In one of these tabs, there is a form which allows a user to fill in some details and then save those details.

In onCreateView, I fetch the TextInputEditText elements and initialize them.

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.my_fragment, container, false);

    usernameInput = (TextInputEditText) view.findViewById(R.id.username_input);
    usernameInput.setText("Test username"); // This works

    // Repeat for other TextInputEditTexts

    return view;
}

However when clicking the Save button (implemented with a FAB), the save() method shows that TextInputEditText elements are null. Why is this happening?

public void save() {
    String username = usernameInput.getText().toString();
    // Crash - usernameInput NullException error
}

Another one of the tabs in this same activity offers a very similar UI and logic (ie. another form and 'save' button), and yet it all works correctly there.

Logcat shows the following error - is this related in any way?

moveToState: Fragment state for MyFragment not updated inline; expected state 3 found 2

0 个答案:

没有答案