Bishwajyoti Roy Bishwajyoti Roy - 14 days ago 6
Android Question

Use "this" in static method in android

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

MainActivity.java
:

public void showDeviceListDialog() {
BluetoothDeviceListDialog dialog = new BluetoothDeviceListDialog(this);
dialog.setOnDeviceSelectedListener(this);
dialog.setTitle("Paired Devices");
dialog.setDevices(bluetoothSerial.getPairedDevices());
dialog.showAddress(true);
dialog.show();
}


I need to call this method from another fragment. So, when I call this method like this:
MainActivity.showDeviceListDialog();
it is asking for making the method Static. But when I am making it Static I am getting errors on "this" [
dialog.setOnDeviceSelectedListener(
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();
mc.showDeviceListDialog();


but this is showing NullPointerException.

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

Answer

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.

Comments