Robert Dzieza
Robert Dzieza

Reputation: 104

Android invoking activity method from fragment

Im testing some ideas and might need a little help. The situation is: I have an activity with preference fragment. When one of options is clicked I want my activity to show or hide another fragment below the preference one. All I am getting is NullPointerException, I guess like I can't get reference to MainActivity from my GroupSettingFragment. Here are the codes:

public class GroupsSettingFragment extends PreferenceFragment{


    MainActivity activity = (MainActivity)getActivity();
        @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.groups_settings);
            Preference pref = findPreference("pref3");
            pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

                @Override
                public boolean onPreferenceClick(Preference preference) {
                    activity.performChange();
                    return false;
                }
            });
        }
    }

In MainActivity

public void showContacts(){
        fr = new ContactsListFragment();
        FragmentTransaction tr = getFragmentManager().beginTransaction();
        tr.add(R.id.contact_list, fr);
        tr.commit();

    }

    public void hideContacts(){
        FragmentTransaction tr = getFragmentManager().beginTransaction();
        tr.remove(fr);
        tr.commit();
    }

    public void performChange(){
        if(isShown){
            //hideContacts();
            isShown = false;
        }else{
            //showContacts();
            isShown = true;
        }
    }

I would appreciate any help. Regards

Upvotes: 0

Views: 238

Answers (1)

bogdan
bogdan

Reputation: 782

The fragment is not automatically assigned to an activity when it is created, that is why getActivity(); returns null globally. You should use the method onAttach(Activity activity) if you want to access the activity.

Upvotes: 1

Related Questions