This question already has answers here:
Problem inflating custom view for AlertDialog in DialogFragment
(9 answers)
Closed 7 years ago.
I am trying to build an AlertDialog and want to show it when the main activity starts. But when the activity starts, an error comes up:
android.util.AndroidRuntimeException: Window feature must be requested before adding content
What I do first is creating an AlertFragment:
public class AlertFragment extends DialogFragment{
public static AlertFragment newInstance(){
return new AlertFragment();
}
public AlertFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle SavedInstanceState){
super.onCreateView(inflater, container, SavedInstanceState);
return inflater.inflate(R.layout.alert_dialog, container, false);
}
#Override
public Dialog onCreateDialog(Bundle SaveInstanceState){
return new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Dialog)).setMessage("Alert Dialog").setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Positive", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Negative", Toast.LENGTH_SHORT).show();
}
}).create();
}
}
The following is the main activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertFragment AF = AlertFragment.newInstance();
AF.show(getSupportFragmentManager(), "Dialog");
}
}
Can someone tell me where the problem lies?
In your AlertFragment remove oncreateview and run
public class AlertFragment extends DialogFragment{
public static AlertFragment newInstance(){
return new AlertFragment(); }
public AlertFragment(){}
#Override
public Dialog onCreateDialog(Bundle SaveInstanceState){
return new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Dialog)).setMessage("Alert Dialog").setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Positive", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Negative", Toast.LENGTH_SHORT).show();
}
}).create();
}
}
just use show in place of create in your code like following:
public Dialog onCreateDialog(Bundle SaveInstanceState){
return new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Dialog)).setMessage("Alert Dialog").setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Positive", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Negative", Toast.LENGTH_SHORT).show();
}
}).show();
Related
I have a bottom navigation fragment and i want to show a single choice dialog in a fragment when a button clicked but i have this logcat:
2020-06-24 18:47:27.954 18946-18946/app E/AndroidRuntime: FATAL EXCEPTION: main
Process: app, PID: 18946
java.lang.NullPointerException: Attempt to invoke interface method 'void app.MapChoiceFragment$SingleChoiceListener.OnNegativeButtonClickedMap()' on a null object reference
at app.baharestanschool.ir.MapChoiceFragment$1.onClick(MapChoiceFragment.java:55)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:174)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
here is my error's code:
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final String[] item = getActivity().getResources().getStringArray(R.array.addresses);
builder.setTitle("choose")
.setSingleChoiceItems(item, position, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
position=i;
}
})
.setPositiveButton("O", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mlistener.OnPosetiveButtonClickedMap(item,position);
}
})
.setNegativeButton("c", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mlistener.OnNegativeButtonClickedMap();
}
});
return builder.create();
}
You should create a dialog as below:-
public class CustomDialogFragment extends DialogFragment {
private OnButtonClickListener mlistener;
public interface OnButtonClickListener {
void OnPositiveButtonClickedMap(String[] item, int position);
void OnNegativeButtonClickedMap();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
mlistener = (OnButtonClickListener) getActvity();
} catch (Exception e) {
}
}
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final String[] item = getActivity().getResources().getStringArray(R.array.addresses);
builder.setTitle("choose")
.setSingleChoiceItems(item, position, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
position=i;
}
})
.setPositiveButton("O", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mlistener.OnPositiveButtonClickedMap(item,position);
}
})
.setNegativeButton("c", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mlistener.OnNegativeButtonClickedMap();
}
});
return builder.create();
}
}
In your Activity, implements OnButtonClickListener as below:-
class MyActivity extends Activity implements OnButtonClickListener {
}
For more info click here
You can build your own Dialog. I build my own custom Dialog With the following example enter link description here
I'm trying get item selected from user to fragment formulary on my Android app, following the google documentation this is possible using this methods from the library, i tried implement this methods and your Interface in my DialogFragment and get it on my fragment formulary, but, the error is returned when i click on the button necessary to open Dialog Fragment.
This is my Dialog Fragment class:
public class FiltroOpcao extends DialogFragment {
OnFiltroEscolhido listener;
private final String[] filtroAnuncio = getResources().getStringArray(R.array.filtro_array);
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
listener = (OnFiltroEscolhido) getTargetFragment();
}catch(ClassCastException e){
throw new ClassCastException(context.toString()+"Deve ser implementado");
}
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Filtrar por:")
.setItems(R.array.filtro_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.pegarFiltro(filtroAnuncio[which]);
}
});
return builder.create();
}
public interface OnFiltroEscolhido{
void pegarFiltro (String escolha);
}
}
And it is where i called the DialogFragment and the crash happens on my VendaFragment fragment class
public void onClick(View v) {
FiltroOpcao filtroOpcao = new FiltroOpcao();
filtroOpcao.setTargetFragment(VendaFragment.this, 1);
filtroOpcao.show(VendaFragment.this.getChildFragmentManager(), "FiltroOpcao");
}
private final String[] filtroAnuncio = getResources().getStringArray(R.array.filtro_array);
Probably, getResources() is the problem because you are using it before the fragment was attached.
Try to move the initialization of filtroAnuncio to onCreateDialog()
private String[] filtroAnuncio;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
filtroAnuncio = getResources().getStringArray(R.array.filtro_array);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Filtrar por:")
.setItems(R.array.filtro_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.pegarFiltro(filtroAnuncio[which]);
}
});
return builder.create();
}
I am trying to display two RecyclerViews inside alert dialog contents. Please Help what am I doing wrong?
The onCreateViewHolder function is not being called
Please note that the RecyclerViews are inside the ConstraintLayout in the xml. If that is causing them not to display what should be the correct procedure?
public class MainActivity extends AppCompatActivity {
private View inflatedView;
private RecyclerView fontList,sizeList;
private String[] fonts = {"normal","sans","serif","monospace"};
private String[] sizes = {"14","16","18","20","22","24"};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
inflatedView = getLayoutInflater().inflate(R.layout.design_style,null);
builder.setView(inflatedView).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"OK Pressed",Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"Cancel",Toast.LENGTH_SHORT).show();
}
});
AlertDialog dialog = builder.create();
dialog.show();
fontList = inflatedView.findViewById(R.id.fontlist);
sizeList = inflatedView.findViewById(R.id.sizelist);
fontList.setLayoutManager(new LinearLayoutManager(this));
fontList.setAdapter(new MyAdapter(Arrays.asList(fonts)));
sizeList.setLayoutManager(new LinearLayoutManager(this));
sizeList.setAdapter(new MyAdapter(Arrays.asList(sizes)));
}
private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
private List<String> itemList;
public MyAdapter(List<String> itemList) {
this.itemList = itemList;
Log.d("lol","MyAdapter");
}
#NonNull
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.design_fontcell,viewGroup);
Log.d("lol","onCreateViewHolder");
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder myViewHolder, int i) {
myViewHolder.mtextView.setText(itemList.get(i));
Log.d("lol",itemList.get(i));
}
#Override
public int getItemCount() {
Log.d("lol","getItemCount: "+itemList.size());
return itemList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView mtextView;
MyViewHolder(View cellView){
super(cellView);
mtextView = cellView.findViewById(R.id.textView_font);
}
}
}
}
Change your code like this
AlertDialog.Builder builder = new AlertDialog.Builder(this);
inflatedView = getLayoutInflater().inflate(R.layout.design_style,null);
//No need of setView() for buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"OK Pressed",Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"Cancel",Toast.LENGTH_SHORT).show();
}
});
fontList = inflatedView.findViewById(R.id.fontlist);
sizeList = inflatedView.findViewById(R.id.sizelist);
fontList.setLayoutManager(new LinearLayoutManager(this));
fontList.setAdapter(new MyAdapter(Arrays.asList(fonts)));
sizeList.setLayoutManager(new LinearLayoutManager(this));
sizeList.setAdapter(new MyAdapter(Arrays.asList(sizes)));
builder.setView(inflatedView); //Set the view at the end
AlertDialog dialog = builder.create();
dialog.show();
i have this code in java:
public class AboutFragment extends Fragment {
public AboutFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about, container, false);
new AlertDialog.Builder(this)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(R.drawable.ic_dialog_alert)
.show();
return rootView;
}
and error is:
The constructor AlertDialog.Builder(AboutFragment) is undefined,
ic_dialog_alert cannot be resolved or is not a field
That's because the AlertDialog.Builder requires a Context and a Fragment is not a Context. Try getActivity() instead of this.
So this is my Dialog class:
public class SecondActivity extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.second, null))
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dismiss();
}
});
return builder.create();
}
}
In my dialog there are 2 edit texts which get 2 strings. I want to use those 2 strings in my MainActivity if the user presses on the save button. How do I do that?
The inflate method returns a view where you can execute a findViewById, like the following:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.second, null);
EditView editView = (EditView)v.findById(R.id.your_edit_view);
builder.setView(v)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dismiss();
}
});
return builder.create();
}