-4

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.

Community
  • 1
  • 1
Bishwajyoti Roy
  • 1,091
  • 1
  • 14
  • 19

3 Answers3

1

this is a reference pointing to the current instance, therefore makes no sence in static methods ... and doing something like

MainActivity mc = new MainActivity();

is not the way android wants you to create an activity... you need to get the Activity like calling the getActivity(); method

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

You cannot create activity like that : MainActivity mc = new MainActivity(); . Android is responsible for this. Use Intent instead. See this tutorial https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html about static methods.

Alex Shutov
  • 3,217
  • 2
  • 13
  • 11