Pyae Phyoe Shein
Pyae Phyoe Shein

Reputation: 13797

call a class from fragment in android

I cannot call outsider class from Fragment, don't why. And show me these message.

Cannot make a static reference to the non-static method selectItem(String, String, String) from the type MainActivity

here is my coding. I want to call "selectItem" class from ContentFragment. That's problem that I cannot call this class.

private void selectItem(String title, String gender, String getStats) {     
    Fragment fragment = new ContentFragment();
    Bundle args = new Bundle();
    args.putString(ContentFragment.JOBTITLE, title);
    args.putString(ContentFragment.JOBGENDER, gender);
    args.putString(ContentFragment.JOBSTATUS, getStats);
    fragment.setArguments(args);        

    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

}

public static class ContentFragment extends Fragment {

    public ContentFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.list_layout, container, false);
        btnPopMsg = (TextView) rootView.findViewById(R.id.btnPopMsg);
        btnPopMsg.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                >>>selectItem("", "", "ALL");<<<
            }
        });            
        return rootView;
    }
}

Upvotes: 1

Views: 2880

Answers (2)

Kingfisher Phuoc
Kingfisher Phuoc

Reputation: 8190

You cant call a static method in an non-static method. If you want to call the function in your onClick, add the block of code:

if(getActivity() instanceof MainActivity){
      ((MainActivity)getActivity()).selectItem("", "", "ALL");
}

Upvotes: 0

Maxim Efimov
Maxim Efimov

Reputation: 2737

You must either set a reference to whatever-wrapper-class-is instance after creating a ContentFragment instance, and then call the method of the reference. Or you may remove static modifier from ContentFragment definition if it fits your design. That happens because nested static class' instance may exist without a wrtapper object of wrapper class, thus in the nested class there is no reference to the wrapper class and it can's call wrapper class' methods.

Upvotes: 1

Related Questions