Bishwajyoti Roy Bishwajyoti Roy - 1 year ago 63
Android Question

call static method of a activity with "this" from a fragment

This is my first android app so maybe this is a stupid question. So, please consider if I am doing any mistake.

I am building a app related to bluetooth.

I have a method in my

public void showDeviceListDialog() {
BluetoothDeviceListDialog dialog = new BluetoothDeviceListDialog(this);
dialog.setTitle("Paired Devices");

I need to call this method from another fragment. So, when I call this method like this:
it is asking for making the method Static. But when I am making it Static I am getting errors on "this" [
] on my method.

I have already read some posts like this and this but I didn't got help about my problem.

I have tried this from my fragment:

MainActivity mc = new MainActivity();

but this is showing NullPointerException.

So, Please tell me how to call it from my fragment without this errors.
Thank you.

Answer Source

A Fragment has a getActivity() method which returns the Activity associated with the Fragment.

Therefore, you can call this method from a Fragment without making it static :

getActivity ().showDeviceListDialog ();

EDIT (thanks to user1506104's comment) :

Actually, you'll have to cast the Activity returned by getActivity() to MainActivity in order to call that method :

((MainActivity) getActivity ()).showDeviceListDialog ();

This is assuming the Fragment is associated with an Activity of that type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download