Emile Emile - 4 months ago 39x
Android Question

Android AlertDialog Builder in a Fragment getActivity() not work

I tried to build an AlertDialog in a Fragment but I couldn't find the proper Context for the AlertDialog Builder.

public class LoginFragment extends Fragment {
public LoginFragment() {
// Required empty public constructor
public void onCreate(Bundle savedInstanceState) {

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);

Button btnEnter = (Button) rootView.findViewById(R.id.btnEnter);

// Listening to register new account link
btnEnter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

// if play name already exists
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setMessage("Player Name Already Exists. Please Find a New Name.")
.setButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

return rootView;

public void onAttach(Activity activity) {

public void onDetach() {


In this line:

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

getActivity() didn't work. It said "require AlertDialog, found AlertDialog.Builder". I've tried things like this.getActivity() and getContext() and getSupportFragmentManager(), all of which didn't work. I am a bit confused about this. Can someone tell me which I should use and why?


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

should be replaced with

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