treesa
treesa

Reputation: 13

calling method of one activity from other activity

I have two activities Main nd AvaiableDevices in Main activity i have a button btnAdvc in AvailableDevices

public class MainActivity extends Activity
{
    Button btnAdvc;
    Button btnPdvc;
    Button btnDdvc;
    Button btnMdvc;

    public BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    public static final int REQUEST_ENABLE_BT = 1; 
    public static  UUID MY_UUID=null;
    public  BluetoothServerSocket mmServerSocket;

    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
            btnAdvc.setOnClickListener(new View.OnClickListener() {  
                public void onClick(View v) 
                {
                    call();
                }
            });
        }catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
    }

    public void init()
    {
        btnAdvc=(Button)findViewById(R.id.btnAdvc);
        btnPdvc=(Button)findViewById(R.id.btnPdvc);
        btnDdvc=(Button)findViewById(R.id.btnDdvc);
        btnMdvc=(Button)findViewById(R.id.btnMdvc);
    }
    public void call()
    {
        Intent intent=new Intent(this,AvailableDevices.class);
        startActivity(intent);
    }
}

I have a method searchDevices() in AvailableDevices activity

public class AvailableDevices extends Activity 
{

    public BluetoothAdapter mBluetoothAdapter;
    public BluetoothDevice device;
    public ListView lv;//for Available Devices
    public ArrayList<String> s=new ArrayList<String>();
    public HashSet<String> hs = new HashSet<String>();
    public ArrayAdapter<String> adapter; 

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_available_devices);

        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, s);
        lv=(ListView)findViewById(R.id.listView1);

        Intent intent=getIntent();
    }


    public AvailableDevices(BluetoothAdapter bt)
    {
        mBluetoothAdapter =bt;
    }

    public void searchDevice()
    {
        if(mBluetoothAdapter.isEnabled())
        {
            mBluetoothAdapter.startDiscovery();
            // Create a BroadcastReceiver for ACTION_FOUND

            final BroadcastReceiver mReceiver = new BroadcastReceiver()
            {
                public void onReceive(Context context, Intent intent) 
                {

                    String action = intent.getAction();
                    // When discovery finds a device
                    if (BluetoothDevice.ACTION_FOUND.equals(action)) 
                    {
                        try{
                            // Get the BluetoothDevice object from the Intent
                            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            // Add the name and address to an array adapter to show in a ListView
                            s.add(device.getName()+ "\n" + "#"+ device.getAddress());
                            //To avoid duplicate devices put it in to  hash set which doesn't allow duplicates          
                            hs.addAll(s);
                            //Clear all the devices in String array S
                            s.clear();
                            //Replace with hash set
                            s.addAll(hs);
                            //          
                            lv.setAdapter(adapter);
                        }catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}                                          
                    }

                    lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
                    {
                        //A local bluetooth device to  Hold the selected device to connect
                        BluetoothDevice    devtoconnect;
                        public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long id)
                        {
                            try{
                                mBluetoothAdapter.cancelDiscovery();
                                //A local String array to hold the Name and address of the selected bluetooth device
                                String[] separated = adapter.getItem(position).split("#");

                                if(mBluetoothAdapter.checkBluetoothAddress(separated[1])==true)
                                {
                                   devtoconnect = mBluetoothAdapter.getRemoteDevice(separated[1]);
                                }                                                                       
                                // Create object of Connect Thread Class to get connection                                    
                                // ConnectThread t1=new  ConnectThread(devtoconnect);
                            }catch(Exception e){}

                        }//Closes onItemClick(AdapterView<?> parentAdapter, View view, int position, long id)
                    }); //Closes lv.setOnItemClickListener(new AdapterView.OnItemClickListener()


                }//Coses function onReceive

            };//Closes  BroadcastReceiver 

            // Register the BroadcastReceiver
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

        }//if

    }// function searchDevices
}

when i click in btnAdvc of main the searchDevices() method of AvailableDevices activity should be called how can i do it?

Upvotes: 0

Views: 148

Answers (3)

Prashant Thakkar
Prashant Thakkar

Reputation: 1403

From the code provided, it looks like searchDevices() method is not a kind of independent method and uses variables/properties decalred in AvaiableDevices class. So probably what you can try is some like

    Intent intent=new Intent(this,AvailableDevices.class);
    intent.putExtra("CallSearchDevices", true);
    startActivity(intent);

And in AvailableDevices at the end of the onCreate method,

    Intent intent=getIntent();
    boolean flag = intent.getBooleanExtra("CallSearchDevices", false);
    if (flag){
      searchDevices();
    }

I hope this helps

Upvotes: 1

Freego
Freego

Reputation: 466

You should declare your method static so you can call it like that AvailableDevices.searchDevices() from your other activity

Upvotes: 0

stinepike
stinepike

Reputation: 54682

you can use broadcast messages. after the button click send a broadcast. and in the other activity register a BroadcastReceiver which will handle the brodcast. so whenever you have got the desired message then call the method in second activity.

Upvotes: 2

Related Questions