简体   繁体   中英

App crashing while trying to display a Toast on AlertDialog button click (in a Fragment)

I am trying to make a DialogFragment contaning an alert dialog. It contains an interface holding a method that should be called upon the pressing of dialog's Cancel/OK button.

Now the problem is that I want to display a Toast.makeText when user clicks OK/Cancel, but I don't know what Context I should pass to the toast, in order not to crash it. My app crashes when user clicks the dialog buttons and I guess the Context is causing the exception:

Fragment class:

public class AlertDFragment extends DialogFragment {

dialogListener ds;
Context con;

public interface dialogListener {
    public void onOK(Context c);
    public void onCancel(Context c);
}

@Override
public Dialog onCreateDialog(Bundle savedInstances) {
    Builder b = new AlertDialog.Builder(getActivity());

    b.setIcon(R.drawable.abc_ic_search);
    b.setTitle("DialogFragment instance");
    b.setMessage("Choose an option");
    b.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            ds.onOK(con);
        }
    });

    b.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface arg0, int arg1) {
            ds.onCancel(con);
        }
    });

    return b.create();
}

public AlertDFragment() {

}

protected void OnAttach(Activity activity) {
    super.onAttach(activity);
    con = activity;
    try {
        ds = (dialogListener) activity;
    } catch(ClassCastException e) {
        throw new ClassCastException(activity.toString()+" must implement the dialogListener interface");
    }
}

}

Main Activity (parent of the fragment):

public class MainActivity extends FragmentActivity implements AlertDFragment.dialogListener {

Button dialog2;
FragmentManager fm = getSupportFragmentManager();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dialog2 = (Button) findViewById(R.id.btn2);
    dialog2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            AlertDFragment adf = new AlertDFragment();
            adf.show(fm, "MY TAG");
        }
    });

}

//interface methods
public void onOK(Context c) {
    Toast.makeText(MainActivity.this, "OK pressed", Toast.LENGTH_SHORT).show();     
}

public void onCancel(Context c) {
    Toast.makeText(MainActivity.this, "Cancel pressed", Toast.LENGTH_SHORT).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

And the LogCat:

11-04 10:23:30.959: E/AndroidRuntime(2014): FATAL EXCEPTION: main
11-04 10:23:30.959: E/AndroidRuntime(2014): Process: com.apex.dialogtest, PID: 2014
11-04 10:23:30.959: E/AndroidRuntime(2014): java.lang.NullPointerException
11-04 10:23:30.959: E/AndroidRuntime(2014):     at com.apex.dialogtest.AlertDFragment$1.onClick(AlertDFragment.java:33)
11-04 10:23:30.959: E/AndroidRuntime(2014):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
11-04 10:23:30.959: E/AndroidRuntime(2014):     at android.os.Handler.dispatchMessage(Handler.java:102)
11-04 10:23:30.959: E/AndroidRuntime(2014):     at android.os.Looper.loop(Looper.java:136)
11-04 10:23:30.959: E/AndroidRuntime(2014):     at android.app.ActivityThread.main(ActivityThread.java:5017)
11-04 10:23:30.959: E/AndroidRuntime(2014):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 10:23:30.959: E/AndroidRuntime(2014):     at java.lang.reflect.Method.invoke(Method.java:515)
11-04 10:23:30.959: E/AndroidRuntime(2014):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-04 10:23:30.959: E/AndroidRuntime(2014):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-04 10:23:30.959: E/AndroidRuntime(2014):     at dalvik.system.NativeStart.main(Native Method)

Thanks in advance!

ds does not get initialized because protected void OnAttach(Activity activity) needs a lowercase o. Be sure to always use @Override annotations and you would have gotten an error.

You have the following in code

dialogListener ds;

but you never instantiate it. Then you call ds.onOK(con); method on a reference ds . This causes null pointer exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM