Rixwen
Rixwen

Reputation: 275

Android: Error using calling AlertDialog from inside Fragment

Why do i always get error when i try to call AlertDialog from my fragment? At first i try to put it in OnCreate but it also get the same error log...

MainFragment.java

public class MainFragment extends Activity {

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

        if (savedInstanceState == null) {
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            LoginFragment fragment = new LoginFragment();
            ft.add(R.id.simple_fragment, fragment).commit();
        }

    }

}

LoginFragment.java

public class LoginFragment extends Fragment implements OnClickListener {

    Helper application;

    static LoginFragment newInstance() {
        LoginFragment f = new LoginFragment();

        Bundle args = new Bundle();
        f.setArguments(args);

        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        AlertDialog.Builder dlgAlert = new AlertDialog.Builder(getActivity().getApplicationContext());
        dlgAlert.setMessage("TEST");
        dlgAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
            }
        });
        dlgAlert.setCancelable(false);
        dlgAlert.create().show();

    }

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

        Button inner = (Button) v.findViewById(R.id.btnSignUp);
        inner.setOnClickListener(LoginFragment.this);

        return v;
    }

    @Override
    public void onClick(View v) {

    }

}

and this is the error log

12-19 10:14:25.295: E/AndroidRuntime(1083): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.fragment.MainFragment}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

anyone has ever encountered this before?

Upvotes: 0

Views: 918

Answers (2)

Rakeeb Rajbhandari
Rakeeb Rajbhandari

Reputation: 5063

Just try

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

Upvotes: 1

Sound Conception
Sound Conception

Reputation: 5411

If you are dealing with nested fragments. When a fragment has it's own child fragments you need to use getChildFragmentManager().

Upvotes: 0

Related Questions