Tamas Koos
Tamas Koos

Reputation: 1063

Android Studio - Fragment button action

I tried to make an application that shows a fragment at start then you can change that fragment to an other one with a button in the first fragment. But when I put the button action in the fragments java, it won't start and I get the nullpointerexception error. Could you tell me why?

public class Fragment_main extends Fragment {

FragmentManager fm = getFragmentManager();

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Button button_inditas = (Button) getView().findViewById(R.id.button_inditas);
    button_inditas.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fm.beginTransaction().replace(R.id.content_frame, new Fragment_1()).commit();
        }
    });
    return inflater.inflate(R.layout.fragment_main,container,false);

}
}

Upvotes: 2

Views: 191

Answers (2)

Skizo-ozᴉʞS ツ
Skizo-ozᴉʞS ツ

Reputation: 20656

But when I put the button action in the fragments java, it won't start and I get the nullpointerexception error. Could you tell me why?

Well I see some errors on your code...

First of all you can't call getView() if you haven't inflated one, it means that you MUST inflate a view as i'll put on my answer and then you can avoid the getView() and use that view itself.

And instead of returning the inflater you have to return your View

This is how your Fragment should look like:

 public class Fragment_main extends Fragment {

    public Fragment_main() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main,container,false);
        Button button_inditas = (Button)rootView.findViewById(R.id.button_inditas);
        button_inditas.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

         FragmentManager fragmentManager = getFragmentManager ();
         FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();

         fragmentTransaction.add (R.id.content_frame, new Fragment_1());
         fragmentTransaction.commit ();


        });
    return rootView;

    }
}

Upvotes: 1

Dave
Dave

Reputation: 321

You have to inflate the view first and use the view returned by that instead of getView ().

View view = inflater.inflate (...);

and then

... = (Button) view.findView(...);

This happens because the view that is returned by getView () hasn't been created yet, so getView() returns null.

Upvotes: 0

Related Questions