Getting EditText Value from a Fragment in main Activity

后端 未结 3 1070
攒了一身酷
攒了一身酷 2021-01-26 02:55

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

相关标签:
3条回答
  • 2021-01-26 03:11
    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);
    
    0 讨论(0)
  • 2021-01-26 03:11

    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:)

    0 讨论(0)
  • 2021-01-26 03:12

    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;
    }
    
    0 讨论(0)
提交回复
热议问题