Emile Emile - 6 months ago 78
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
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
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())
.setCancelable(false)
.setIcon(R.drawable.login_icon)
.setMessage("Player Name Already Exists. Please Find a New Name.")
.setButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
});

return rootView;
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}

@Override
public void onDetach() {
super.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?

Answer

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

should be replaced with

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