سؤال

I'm making a single choice list out of all bounded bluetoothdevices. And I try just toast a message "SUCCESS" once choice is made. I have 2 files in my projekt. MainActivity.java:

import package_name.DeviceChooser.listenForDeviceChoose;

public class MainActivity extends ActionBarActivity implements listenForDeviceChoose{

public void chooseDevice (View view) {
        deviceArray.clear();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        // If there are paired devices
        if (pairedDevices.size() > 0) {
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                // Add the name and address to an array adapter to show in a ListView
                deviceArray.add(device.getName());
            }
        }
        DeviceChooser deviceChooser = new DeviceChooser();
        deviceChooser.show(getSupportFragmentManager(), "DeviceChooser");
    }
}

and DeviceChooser.java:

public class DeviceChooser extends DialogFragment {

    public interface listenForDeviceChoose {
        public void clickDevice(int i);
    }

        public Dialog onCreateDialog(Bundle savedInstanceState) {
               builder.setSingleChoiceItems(cs, 1,
                          new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                      ((listenForDeviceChoose) builder).clickDevice(which);
                   }
               });
} 
}

App gets crashed when I do my choice. Why? And where can I learn all those small things ?

هل كانت مفيدة؟

المحلول

The snippet you posted throws a ClassCastException because is MainActivity that implements the interface. You should cast the activity's object not the Dialog's builder.

((listenForDeviceChoose) getActivity()).clickDevice(which);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top