[英]Why does my app crash on single choice?
我從所有有界的藍牙設備中做出一個選擇列表。 一旦做出選擇,我就嘗試舉杯消息“成功”。 我的項目中有2個文件。 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");
}
}
和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);
}
});
}
}
當我選擇時,應用程序崩潰了。 為什么? 在哪里可以學到所有這些小知識呢?
您發布的代碼段拋出ClassCastException
因為它是實現接口的MainActivity
。 您應該轉換活動的對象而不是對話框的生成器。
((listenForDeviceChoose) getActivity()).clickDevice(which);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.