如何显示某些列表项的警报对话框

How to show alert dialog for certain list item

每当我 select 一个特定的列表项时,我试图显示一个警告对话框,而其他人会打开一个新的片段。但是,在插入 alreat 对话框代码后,会返回一个错误。我不明白为什么 'intent' 已经初始化时出现此错误。可以做些什么来解决这个问题?

Variable 'intent' might not have been initialized

FragmentFruitChooser

public class FragmentFruitChooser extends ListFragment {

    public FragmentFruitChooser() {
        // Required empty constructor
    }

    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    public boolean mTwoPane;

    public static FragmentFruitChooser newInstance() {
        return new FragmentFruitChooser();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fruit_chooser, container, false);
        initialize();
        return view;
    }

    List<Fruits> list = new ArrayList<>();
    private void initialize() {
        String[] items = getActivity().getResources().getStringArray(R.array.fruit_names);
        String[] itemDescriptions = getActivity().getResources().getStringArray(R.array.fruit_descriptions);
        for (int n = 0; n < items.length; n++){
            Fruit fruit = new Fruit();
            fruit.setID();
            fruit.setName(items[n]);
            fruit.setDescription(itemDescriptions[n]);
            list.add(fruit);
        }

        FruitListAdapter mAdapter = new FruitListAdapter(list, getActivity());
        setListAdapter(mAdapter);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        View v = getView();

        mTwoPane = getActivity().findViewById(R.id.detail_container) != null;

        assert v != null;
        ListView lv = (ListView)v.findViewById(android.R.id.list);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // get the adapter, then get the name from the adapter at that position
                FruitListAdapter adapter = (FruitListAdapter) parent.getAdapter();

                //reverse the selected state in data model
                for (int i = 0; i < adapter.getCount(); i++) {
                    Fruit fruit = (Fruit)adapter.getItem(i);
                    fruit.setSelected(i == position);
                }
                Fruit fruit = (Fruit)adapter.getItem(position);

                if (!mTwoPane) {

                    Intent intent;
                    if (fruit.getFruit().equals(view.getResources().getString(R.string.apple))) {
                        intent = new Intent(getActivity(), FruitAppleActivity.class);
                    } else if (fruit.getFruit().equals(view.getResources().getString(R.string.orange))) {
                        intent = new Intent(getActivity(), FruitOrangeActivity.class);
                    } else if (fruit.getFruit().equals(view.getResources().getString(R.string.tomato))) {
 AlertDialog ad = new AlertDialog.Builder(getContext())
            .create();
    ad.setCancelable(false);
    ad.setTitle("Seeded Fruit");
    ad.setMessage("This fruit contains seeds.");
    ad.setButton(context.getString(R.string.ok_text), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
ad.show();
                    } else {
                        intent = new Intent(getActivity(), FruitAppleActivity.class);
                    }
                    startActivity(intent);
                }
            }

        });

        super.onActivityCreated(savedInstanceState);
    }
}

试试 Intent intent = null;而不是 Intent 意图;很难说,但我认为这应该可以解决您的问题 –

不太确定你的程序是如何工作的,但在你的第二个 else if 语句中,你的 intent 没有初始化,但 startActivity(intent) 仍然被调用:

} else if (fruit.getFruit().equals(view.getResources().getString(R.string.tomato))) {
                        AlertDialog ad = new AlertDialog.Builder(getContext())
                                .create();
                        ad.setCancelable(false);
                        ad.setTitle("Seeded Fruit");
                        ad.setMessage("This fruit contains seeds.");
                        ad.setButton(context.getString(R.string.ok_text), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        ad.show();
                    } else {
                        intent = new Intent(getActivity(), FruitAppleActivity.class);
                    }

                    startActivity(intent);

您可以按照@seanAshmore 的回答进行操作,但仍可能导致 NPE。我建议在实际调用 startActivity() 之前简单地为意图添加一个空检查器,如下所示:

if (intent != null) {
                        startActivity(intent);
                    } else {
                        Log.d(FragmentFruitChooser.class.getSimpleName(), "Intent is null");
                    }

您可以为每个 if/elif/else 语句单独放置 Intent intent = new Intent(...) 以确保万无一失。但这是您的代码,所以请按照您的意愿去做。