Skip to content Skip to sidebar Skip to footer

How To Call Object From One Class Other

In my Android project there is a MainActivity.java MainActivity extends FragmentActivity{ onCreate(Bundle savedInstanceState){ BluetoothManager bluetoothManager =

Solution 1:

Declare the BluetoothManager bluetoothManager at class level ( before onCreate() method ) and other class should be inner class

Solution 2:

There are two ways known to me-

UsingStaticvariable:

MainActivityextendsFragmentActivity{
publicstaticBluetoothAdapter mBluetoothAdapter;
    onCreate(Bundle savedInstanceState){

       BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

    }
  }

publicclassAvailableDevicesextendsListFragment {

     // How to call mBluetoothAdapter here
    use inthisclassasMainActivity.mBluetoothAdapter

  }


2.Passing mBluetoothAdapter to the constructor of the second class.

MainActivityextendsFragmentActivity{

    onCreate(Bundle savedInstanceState){

       BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

    }
  }

publicclassAvailableDevicesextendsListFragment {
    BluetoothAdapter mBluetoothAdapter=null;
AvailableDevices(BluetoothAdapter mBluetoothAdapter){
     this.mBluetoothAdapter=mBluetoothAdapter;


  }

Solution 3:

pass it as a parameter to the constructor of the class

publicclassAvailableDevicesextendsListFragment {
   private BluetoothAdapter bluetoothAdapter;
   publicAvailableDevices(BluetoothAdapter bluetoothAdapter) {
       this.bluetoothAdapter = bluetoothAdapter;
   }
}

or declare it as a static public data member

publicclassMainActivityextendsFragmentActivity{

    publicstatic BluetoothAdapter mBluetoothAdapter;

    ..
 }

and then in the other class use MainActivity.mBluetoothAdapter

or make the AvailableDevices an inner class and declare the adapter as a data member:

publicclassMainActivityextendsFragmentActivity{

    private BluetoothAdapter mBluetoothAdapter;
    ..
    classAvailableDevicesextendsListFragment {
         //can use mBluetoothAdapter
    }
}

Post a Comment for "How To Call Object From One Class Other"