【问题标题】:Why does my app crash on single choice?为什么我的应用程序在单选时崩溃?
【发布时间】:2024-06-19 01:25:02
【问题描述】:

我正在从所有有界蓝牙设备中制作一个选择列表。一旦做出选择,我就会尝试只祝酒“成功”。 我的项目中有 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);
                   }
               });
} 
}

当我做出选择时,应用程序崩溃了。为什么?我在哪里可以学到这些小东西?

【问题讨论】:

    标签: java android dialog fragment


    【解决方案1】:

    您发布的 sn-p 抛出了 ClassCastException 因为是实现接口的MainActivity。您应该转换活动的对象而不是对话框的构建器。

    ((listenForDeviceChoose) getActivity()).clickDevice(which);
    

    【讨论】:

    • 感谢您解决了我的问题。 +1 并接受。我在哪里可以学到这些小东西?我什至无法正确设置谷歌的示例。我用谷歌搜索每一个细节。有时间和经验吗?
    • 我无法真正回答。这需要时间和耐心。您可以阅读 java vol 1 中的思想和有效的 java
    最近更新 更多