【问题标题】:Getting null when using the string outside the interface在接口外使用字符串时获取 null
【发布时间】:2014-07-17 12:30:35
【问题描述】:

我创建了一个方法,在该方法中我在按钮单击时显示警报。我还创建了一个接口来获取按钮上的文本及其位置。现在在我的另一个类中,当我使用该方法时,我总是在字符串上获得一个空指针。

警报方法

protected void displayPopup(Context context, String title, final String[] array, final Button button, final boolean setText, final GetNamePosition getNamePosition) {
        builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setItems(array, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                    button.setText(array[i]);


                getNamePosition.getName(button.getText().toString());
                getNamePosition.getPosition(i);

                dialogInterface.dismiss();
            }
        });

        builder.show();
    }

我正在使用弹出窗口的其他类

private String[] chooseDocumentArray;
    private String userSelection;
case R.id.bt_choose_file:

                displayPopup(getActivity(), "Choose File", chooseDocumentArray, btChooseDoc, false, new GetNamePosition() {
                    @Override
                    public void getName(String name) {
                        userSelection = name;
                        if (userSelection.equals("Gallery")) {
                            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(intent, 0);
                        }
                    }

                    @Override
                    public void getPosition(int position) {

                    }
                });

//                if (userSelection.equals("Gallery")) {
//                    intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                    startActivityForResult(intent, 0);
//                }

        }

界面

public interface GetNamePosition {

    public void getName(String name);

    public void getPosition(int position);
}

我在界面内使用字符串用户选择,应用程序工作正常,但是当我在界面外使用它时{我评论过}我强制关闭

【问题讨论】:

    标签: java android interface android-alertdialog


    【解决方案1】:

    userSelection 仅在 getName 方法中初始化,否则其值为 null。

    为了避免得到空指针,试试这个private String userSelection = ""; 或 在接口外使用字符串之前进行空检查,即

    if(userSelection != null){
         if (userSelection.equals("Gallery")) {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, 0);
         }
    }
    

    【讨论】:

    • 是的,现在我没有得到空指针,但现在画廊打开了,但它本身没有用户选择画廊
    • 相同的代码现在我已经从界面中删除了画廊意图并取消了外部代码的注释
    • 画廊可能由于您的代码中的其他部分而打开。确保在每个 case 结束时在 switch case 中使用 break。由于缺乏完整的代码伙伴,无法弄清楚确切的问题。
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多