android - 程序因 .onDialogPositiveClick 崩溃

标签 android crash dialog

所以目前我正在尝试将信息从对话框传递到主机 Activity ,并且我遵循 this guide 。但是它在三个实例上崩溃:

catch (ClassCastException e) {
        // The activity doesn't implement the interface, throw exception
        throw new ClassCastException(context.toString()
                + " must implement NoticeDialogListener");

:

mListener.onDialogPositiveClick(NDPickeris.this);

还有:

mListener.onDialogNegativeClick(NDPickeris.this);

这是 Activity :

public class NDPickeris extends DialogFragment {

public static ArrayList ndpam, allpam;

public static final String MyPREFERENCES = "MyPrefs";
/* public static final ArrayList ndpam = null; */


public static final String Pi1 = "nameKey11", Pi2 = "nameKey12", Pi3 = "nameKey13", Pi4 = "nameKey14",
        Pi5 = "nameKey15", Pi6 = "nameKey16", Pi7 = "nameKey17", Pi8 = "nameKey18",A1 = "nameKey21",
        A2 = "nameKey22", A3 = "nameKey23", A4 = "nameKey24", A5 = "nameKey25", A6 = "nameKey26",
        A7 = "nameKey27", A8 = "nameKey28", T1 = "nameKey31", T2 = "nameKey32", T3 = "nameKey33",
        T4 = "nameKey34", T5 = "nameKey35", T6 = "nameKey36", T7 = "nameKey37", T8 = "nameKey38",
        K1 = "nameKey41", K2 = "nameKey42", K3 = "nameKey43", K4 = "nameKey44", K5 = "nameKey45",
        K6 = "nameKey46", K7 = "nameKey47", K8 = "nameKey48", Pe1 = "nameKey51", Pe2 = "nameKey52",
        Pe3 = "nameKey53", Pe4 = "nameKey54", Pe5 = "nameKey55", Pe6 = "nameKey56", Pe7 = "nameKey57",
        Pe8 = "nameKey58";

SharedPreferences sharedpreferences;

/* The activity that creates an instance of this dialog fragment must
 * implement this interface in order to receive event callbacks.
 * Each method passes the DialogFragment in case the host needs to query it. */
public interface NoticeDialogListener {
    void onDialogPositiveClick(DialogFragment Dialog);
    void onDialogNegativeClick(DialogFragment Dialog);
}

// Use this instance of the interface to deliver action events
NoticeDialogListener mListener;

// Override the Fragment.onAttach() method to instantiate theNoticeDialogListener

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    // Verify that the host activity implements the callback interface
    try {
        // Instantiate the NoticeDialogListener so we can send events to the host
        mListener = (NoticeDialogListener) context;
    } catch (ClassCastException e) {
        // The activity doesn't implement the interface, throw exception
        throw new ClassCastException(context.toString()
                + " must implement NoticeDialogListener");
    }


}

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Get the layout inflater
    LayoutInflater inflater = getActivity().getLayoutInflater();

    final View view = inflater.inflate(R.layout.nd_pickeris, null);
    final Spinner spin;
    spin = (Spinner) view.findViewById(R.id.pamoka_spinner);

    sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

    ndpam = new ArrayList();
    allpam = new ArrayList();

    allpam.add(sharedpreferences.getString(Pi1, ""));
    allpam.add(sharedpreferences.getString(Pi2, ""));
    allpam.add(sharedpreferences.getString(Pi3, ""));
    allpam.add(sharedpreferences.getString(Pi4, ""));
    allpam.add(sharedpreferences.getString(Pi5, ""));
    allpam.add(sharedpreferences.getString(Pi6, ""));
    allpam.add(sharedpreferences.getString(Pi7, ""));
    allpam.add(sharedpreferences.getString(Pi8, ""));
    allpam.add(sharedpreferences.getString(A1, ""));
    allpam.add(sharedpreferences.getString(A2, ""));
    allpam.add(sharedpreferences.getString(A3, ""));
    allpam.add(sharedpreferences.getString(A4, ""));
    allpam.add(sharedpreferences.getString(A5, ""));
    allpam.add(sharedpreferences.getString(A6, ""));
    allpam.add(sharedpreferences.getString(A7, ""));
    allpam.add(sharedpreferences.getString(A8, ""));
    allpam.add(sharedpreferences.getString(T1, ""));
    allpam.add(sharedpreferences.getString(T2, ""));
    allpam.add(sharedpreferences.getString(T3, ""));
    allpam.add(sharedpreferences.getString(T4, ""));
    allpam.add(sharedpreferences.getString(T5, ""));
    allpam.add(sharedpreferences.getString(T6, ""));
    allpam.add(sharedpreferences.getString(T7, ""));
    allpam.add(sharedpreferences.getString(T8, ""));
    allpam.add(sharedpreferences.getString(K1, ""));
    allpam.add(sharedpreferences.getString(K2, ""));
    allpam.add(sharedpreferences.getString(K3, ""));
    allpam.add(sharedpreferences.getString(K4, ""));
    allpam.add(sharedpreferences.getString(K5, ""));
    allpam.add(sharedpreferences.getString(K6, ""));
    allpam.add(sharedpreferences.getString(K7, ""));
    allpam.add(sharedpreferences.getString(K8, ""));
    allpam.add(sharedpreferences.getString(Pe1, ""));
    allpam.add(sharedpreferences.getString(Pe2, ""));
    allpam.add(sharedpreferences.getString(Pe3, ""));
    allpam.add(sharedpreferences.getString(Pe4, ""));
    allpam.add(sharedpreferences.getString(Pe5, ""));
    allpam.add(sharedpreferences.getString(Pe6, ""));
    allpam.add(sharedpreferences.getString(Pe7, ""));
    allpam.add(sharedpreferences.getString(Pe8, ""));

    for (int i = 0; i < allpam.size(); i++) {
        Object aPerson = allpam.get(i);
        if (ndpam.contains(aPerson)) {
            Log.i("yra", "kay");
        } else {
            if (aPerson == "") {
                Log.i("tuscia", "yep");
            } else {
                String ndpamString = aPerson.toString();
                ndpam.add(ndpamString);
            }
        }
    }

    //Log.i("man", ndpam.toString());

    Collections.sort(ndpam);


    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_spinner_item, ndpam);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);

    spin.setAdapter(adapter);

    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog layout

    AlertDialog.Builder(getActivity());
    builder.setView(view)
            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // Send the positive button event back to the host activity
                    Spinner spin = (Spinner) view.findViewById(R.id.pamoka_spinner);
                    String PamokosName = spin.getSelectedItem().toString();
                    Toast.makeText(getActivity().getApplicationContext(), PamokosName, Toast.LENGTH_SHORT).show();
                    mListener.onDialogPositiveClick(NDPickeris.this);
                }
            })
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // Send the negative button event back to the host activity
                    mListener.onDialogNegativeClick(NDPickeris.this);
                }
            });
    return builder.create();


}}

最后是主机 Activity :

public class HomeworkMain extends Fragment implements NDPickeris.NoticeDialogListener{

ArrayList<String> listItems=new ArrayList<String>();

int clickCounter=0;

SharedPreferences sharedpreferences, prefs;
private ImageButton back;
public static final String MyPREFERENCES = "MyPrefs";
public static final String date = "date";
private View v;
private Button btn;
private EditText editTxt;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;

public void showNoticeDialog() {
    // Create an instance of the dialog fragment and show it
    DialogFragment dialog = new NDPickeris();
    dialog.show(getFragmentManager(), "NoticeDialogFragment");
}

public void onDialogPositiveClick(DialogFragment dialog) {
}

public void onDialogNegativeClick(DialogFragment dialog) {
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    v = inflater.inflate(R.layout.homework_main, container, false);

    prefs = getActivity().getSharedPreferences(date, Context.MODE_PRIVATE);
    sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

    editTxt = (EditText) v.findViewById(R.id.editTxt);
    btn = (Button) v.findViewById(R.id.add_button);
    list = (ListView) v.findViewById(R.id.list);
    arrayList = new ArrayList<String>();

    adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);
    list.setAdapter(adapter);

    /*btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // this line adds the data of your EditText and puts in your array
            arrayList.add(editTxt.getText().toString());
            // next thing you have to do is check if your adapter has changed
            adapter.notifyDataSetChanged();
        }
    });*/

    btn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            DialogFragment fr = new NDPickeris();
            fr.show(getFragmentManager(), "");
        }
    });

    back = (ImageButton) v.findViewById(R.id.back_btn1);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            HomeworkMain fr = new HomeworkMain();
            tvarkarastis fr2 = new tvarkarastis();
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.activity_frag, fr2);
            fragmentTransaction.remove(fr);
            fragmentTransaction.commit();
        }
    });
    return v;
}}

还有崩溃报告:

27519-27519/com.sajev.slush E/AndroidRuntime: FATAL EXCEPTION: main Process: com.sajev.slush, PID: 27519 java.lang.NullPointerException: Attempt to invoke interface method 'void com.sajev.slush.NDPickeris$NoticeDialogListener.onDialogPositiveClick(android.app.DialogFragment)' on a null object reference at com.sajev.slush.NDPickeris$2.onClick(NDPickeris.java:189) at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:156) at android.app.ActivityThread.main(ActivityThread.java:6523) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)

最佳答案

您没有将一个类的引用值传递给另一个类。所以你需要像下面这样做:-

btn.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v) {
        NDPickeris fr = new NDPickeris();
        // reference of your interface NoticeDialogListener
        fr.setListener(this);
        fr.show(getFragmentManager(), "");
    }
});

现在您需要在 NDPickeris.class 上创建 setter 方法,如下所示:-

 // setter method on your dialog fragment
 public void setListener(NoticeDialogListener mListener) {
      // now u set value on your listener
      this.mListener = mListener;
 }

删除您的 onAttach 代码:-

// Verify that the host activity implements the callback interface
    try {
        // Instantiate the NoticeDialogListener so we can send events to the host
        mListener = (NoticeDialogListener) context;
    } catch (ClassCastException e) {
        // The activity doesn't implement the interface, throw exception
        throw new ClassCastException(context.toString()
                + " must implement NoticeDialogListener");
    }

现在希望你的代码工作正常。

关于android - 程序因 .onDialogPositiveClick 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48951059/

相关文章:

android - 如何创建弹出菜单作为另一个弹出菜单菜单项的子菜单

java - AlarmManager 无法调用我的 BroadcastReceiver

android - 在 ViewPager 中加载具有不同数据的相同 fragment

android - 显示不褪色背景的对话框

php - 我的 Facebook 登录对话框在 IE 中没有关闭

android - 在 Dialog 中使用 Scrollview 时出现问题

android - 列表 fragment 简单示例

ios - UIDocumentMenuViewController initWithDocumentTypes :inMode: can only be called with mode Import or Open

c - 编译后偶尔会死机

C# - DisplayDialog() 不适用于 FileSave 和拖/放