Fragment类中的AlertDialog.Builder(getActivity())上的NullPointerException

时间:2014-03-22 12:49:52

标签: android android-fragments

我有一些通过drawer打开的Fragment类。在某些课程中,按钮不起作用,而其他课程则起作用。我在所有这些代码上都有相同的代码。我在error行上获得了AlertDialog.builder

public class NumbersActivity extends Fragment {

    private Spinner editAlarmSpinner;
    private Button deleteSelected, updateSelected, add;
    String prevAlarmName;
    DBAdapter db;
    ArrayList<String> alarmsList, allList;
    ArrayAdapter<String> dataAdapter;
    final Context contextUpdate = getActivity();

    public static Fragment newInstance(Context context) {
        NumbersActivity f = new NumbersActivity();

        return f;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.activity_numbers, container, false);

        editAlarmSpinner = (Spinner) v.findViewById(R.id.editAlarmSpinner);
        deleteSelected = (Button) v.findViewById(R.id.deleteButton);
        updateSelected = (Button) v.findViewById(R.id.updateNumberButton);
        add = (Button) v.findViewById(R.id.addNumberButton);

        db = new DBAdapter(getActivity());
        updateSpinner();

        add.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                LayoutInflater layoutInflater = getActivity().getLayoutInflater();   

                View promptView =  layoutInflater.inflate(R.layout.updatenumberdialog, null, false);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(contextUpdate);
                alertDialogBuilder.setTitle(R.string.newAlarmDetails);

我做错了什么?为什么这个适用于其他课程,而另一些课程却没有?

2 个答案:

答案 0 :(得分:0)

contextUpdatenull,因为您在初始化之前正在调用Fragment.getActivity。您应该完全删除contextUpdate变量并改为拨打Fragment.getActivity

答案 1 :(得分:0)

改变
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(contextUpdate);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());

或初始化

contextUpdate = getActivity();  

在onCreateView中。