简体   繁体   中英

NPE : Attempt to invoke interface method

I have a fragment & i have the below code :

NavDrawer listener;
public interface NavDrawer {
     void showNavDrawer(String msg);
}

I've set a navigation icon for my fragment. When the icon is clicked, i just called Interface method.

toolbar.setNavigationIcon(android.R.drawable.ic_menu_directions);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        listener.showNavDrawer("Show Drawer");
    }
});

In the MainActivity.class , I implemented the interface to open the Navigation drawer.

@Override
public void showNavDrawer(String msg) {
    drawer.openDrawer(GravityCompat.START);
}

The error shown was :

java.lang.NullPointerException: Attempt to invoke interface method

Before I post this thread, I shown some effort by viewing and tried the solution in existing question. But, couldn't solve so far.

Override onAttach in your framgent

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try {
        listener= (NavDrawer) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement NavDrawer");
    }
}

And also check if listener is null before listener.showNavDrawer("Show Drawer");

Note : onAttach(activity) is deprecated you will have a context and you can use that. You can check if context is a instance of activity.

Also the above would work as long as MainActivity is implementing the interface.

http://developer.android.com/reference/android/app/Fragment.html#onAttach(android.app.Activity)

More info fragmet communication @ http://developer.android.com/training/basics/fragments/communicating.html

Since your listener is null, initialize it in MainActivity.

public class MainActivity extends AppCompatActivity implements NavDrawer{

    private NavDrawer listener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        .....

        listener= new NavDrawer(this);

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM