ShiftyCodes ShiftyCodes - 7 months ago 12
Java Question

How to call MainActivity method

I'm trying to call method share() from a fragment. share() is in MainActivity.java

Button shareButton = new Button(getActivity());
shareButton.setOnClickListener(new View.onClickListener() {
@Override
public void onClick(View v) {
MainActivity ma = new MainActivity();
ma.share(); //Doesn't work! NullPointerException
}
}


share():

public void share() {
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, shareString);
startActivity(Intent.createChooser(i, "Say Something"));
}

Answer

Change

MainActivity ma = new MainActivity();

To

MainActivity ma = (MainActivity) getActivity();

getActivity() returns an instance of Activity so it must be cast

Comments