treesa
treesa

Reputation: 13

Call a method of an Activity from another Activity

I have two Activities A and B. B has a method searchDevices. I want to access that method from A 's onCreate method. How can I do it with Intent?
I tried this :

public void onCreate(Bundle savedInstanceState)
{
    try{


    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MY_UUID= UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");    


    //Function enbling Bluetooth
    enableBluetooth();

    ///Function to initialize components
    init();


    //Calling AvailableDevices class's method searchDevice to get                AvailableDevices
    Intent intent=new Intent(this,AvailableDevices.class);
    int x=10;
    intent.putExtra("A", x);

    }catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(),   Toast.LENGTH_LONG).show();}
}

Upvotes: 0

Views: 1344

Answers (3)

Cam Connor
Cam Connor

Reputation: 1231

if ActivityA is in a class called class1 make a method in class1 like this

public static void method1(){
}

then in activity 2 call the method by doing this ActivityA.method1()

Upvotes: 2

Aduait Pokhriyal
Aduait Pokhriyal

Reputation: 1559

Why don't use StartActivityForResult.

As per my understanding You can start AvailableDevices Activity for result with Intent having extra data and call searchDevice to get AvailableDevices and return the result to calling Activity.

[Edit]

In Class A

//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
startActivityForResult(intent , searchDevicesRequestCode); //searchDevicesRequestCode = 100

Also override onActivityResult()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == searchDevicesRequestCode) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // Manipulate searchDevicesResult from Intent data
        }
    }
}

In Class B

@override    
onCreate()
{
    //call searchDevices()
    String result = searchDevices(); // save result to send in any form
    // Create intent to deliver some kind of result data
    Intent intentResult = new Intent("RESULT_ACTION");
    intentResult.putExtra("key",result);
    setResult(Activity.RESULT_OK, intentResult);
    finish();
}

Upvotes: 1

vipul mittal
vipul mittal

Reputation: 17401

You can also create a base activity that both ActivityA and ActivityB extends and put searchDevices() method in it.

For ex:

public class BaseActivity extends Activity{

public void searchDevices(){

}

}


public class ActivityB extends BaseActivity{
onCreate..
{
  ...
  searchDevices();
}
}


public class ActivityA extends BaseActivity{
onCreate..
{
  ...
  searchDevices();
}
}

Upvotes: 4

Related Questions