Alert dialog in Fragment, app get crashed - java

I want to display the alert dialog when onClick of the button in fragment layout. I have tried but the app is crashing when it runs.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentWalletBinding.inflate(inflater, container, false);
Button button = (Button)getView().findViewById(R.id.add_money);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertdialog = new AlertDialog.Builder(view.getContext());
alertdialog.setMessage("this is message");
alertdialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(),"toast message",Toast.LENGTH_SHORT).show();
}
}).show();
}
});
return binding.getRoot();
}

onCreateView returns View which can be further obtained by getView() method. and you are calling it before onCreateView had a chance to return own View for framework (its still inside method, didn't return binding.getRoot(); yet)
if you are using view binding then obtain your Button from there
Button button = (Button) binding.addMoney;
or even just use strictly (without additional local Button)
binding.addMoney.setOnClickListener(...
and if you REALLY WANT to use findViewById (but why...), then you can look inside binding.getRoot() even when it isn't returned/drawn yet
Button button = (Button) binding.getRoot().findViewById(R.id.add_money);

there is a problem in
(Button)getView().findViewById(R.id.add_money);
please make sure id is same as in XML.

Related

Dialog for fragments

Why is my showPopup grey when I already have an OnClick method on that fragment's xml?
I'm trying to make the popup_about_app XML popup when I click on the button with the OnClick.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myDialog = new Dialog(getContext());
return inflater.inflate(R.layout.fragment_settings, container, false);
}
public void showPopup(View view) {
TextView txtclose;
myDialog.setContentView(R.layout.popup_about_app);
txtclose =(TextView) myDialog.findViewById(R.id.txtClose);
txtclose.setText("X");
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
In Android Studio, gray means its not being used yet. Either nothing is calling showPopup, or possibly that Android Studio isn't smart enough to find the thing calling showPopup (which can happen in various scenarios). I wouldn't worry about it unless you hit the button that's supposed to call showPopup and nothing happens (and then it means you forgot to call it). If the popup shows like you expect, its a non-issue.

How do I connect a button to a Dialog that will edit a TextView, within a FrameLayout, with a users input?

I don't understand DialogFragment at all. How to create one, how to get the user input out of it, and set it into a TextView.
I would like for the TITLE button, when clicked, to bring up a DialogFragment asking the user to enter the title of their Mood Board. The user enters a title. When they click the PostiveButton "Done", the user's title is set into the top left frame of the mood board, which has a TextView with a hint.
Please! Ask questions, because I don't really understand the dialog setup.
Here is a picture of my main_layout, in my MainActivity. Every element has an "#+id/".
The solution you are looking for is a callback:
Create an interface with a method to use as a callback
Implements the interface on the activity
Create the dialog fragment and in onAttach get the interface
Show the dialog fragment on the activity
On dismiss the dialog fragment pass the text using the instance of the interface
interface Callback {
updateText(String text)
}
class CoolActivity... implements Callback
onCreate {
//find your views
showDialogBtn.setOnClickListener(...
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("yourTag");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DialogFragment dialogFragment = ExampleDialogFragment.newInstance();
dialogFragment.show(ft, "yourTag");
)
}
#Override
updateText(String text) {
youtView.setText(text)
}
class CoolDialogFragment extend DialogFragment {
private Callback callback;
#Override
void onAttach(Context context) {
callback = (Callback) context
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.dialog_fragment_example, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//find the views in the dialog fragment
closeBtn.clickListener(...
callback.updateText(edittext.getText().toString())
dismiss()
)
}
}
Here is a gist of a dialog fragment
https://gist.github.com/cutiko/7e307efcf7492ea52ef05cd90f9e3203
The problem is you want to connect a dialog fragment with a another component, and you want to do it straigth forward. This is not considered a good practice because yiu create 2 componentes higly attached, so the best would be to use data persistence and some form of react programming
You can make your mood board title textview static then call it to the alertdialog with edittext to set it text (setText)
like this.
final EditText edittext = new EditText(MainActivity.this);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Input Title")
.setView(edittext)
.setCancelable(false)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
YourCustomDialog.your_title_textviewMoodboard.setText(edittext.getText().toString());
}
})
.setNegativeButton("Back", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
in your custom dialog. declare your textview static globally
public static TextView your_title_textviewMoodboard;

When you open a new activity in a fragment the app stops

The problem that Teno I want to use an intro slide in my app through fragments and the third fragment I want to put a button that leads to another activity and in Android studio the code does not make any error but when I run the app and click the app button It stops what is it?
public ThirdFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_third, container, false);
viewPager = getActivity().findViewById(R.id.viewPager);
back1 = view.findViewById(R.id.slideThereback);
back1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(1);
}
});
//The TextView "Done " is the one I want to click on the Take me to another activity and that up to now gives me an error to run in the emulator
done = view.findViewById(R.id.Done);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(getActivity(), MenuP.class);
startActivity(myIntent);
}
});
return view;
}
I hope I can provide the code or say my error to open a new activity in a fragment and not close the app to Ejecutarce on a mobile device
Use the below code in your onClick() method.
Intent myIntent = new Intent(getActivity(), MenuP.class);
getActivity().startActivity(myIntent);
Check that R.id.Done does exists in R.layout.fragment_third. if it doesn't exist then done View might be null.

Show a Fragment over everything else currently in view, and then remove it on button click

I'm currently trying to make a fragment come into view over everything else in the activity. Then, on a button press, the fragment should disappear and reveal everything that was there previously.
Here is my current attempt:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
.replace(currentFragment.getId(), fragment);
transaction.addToBackStack(null);
transaction.commit();
and on the button press, I do:
getFragmentManager().popBackStack();
But the issue I'm having it the fragment doesn't totally inflate overtop all the other views, and the button press is not having the desired affect. Any suggestions?
EDIT: It's a bottomNavigationView that's still showing, I'd like to inflate overtop of that.
You can use Dialog fragment like:
public class PopUpDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Context context = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Your title")
.setMessage("Your message")
.setPositiveButton("Button name", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Do your stuff here
dismiss();
}
});
return builder.create();
}
}
Then you call it from your activity like:
PopUpDialogFragment fragment = new PopUpDialogFragment();
fragment.show(getFragmentManager(), "popUp");
If you want a Fragment with your own custom view then you create one with onCreateView method.
public class PopUpDialogFragment extends DialogFragment {
private Button button;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.your_layout,
container, false);
button = view.findViewById(R.id.your_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Do your stuff here
getDialog().dismiss();
}
});
return view;
}
}

must call removeView() on the child's parent first

I'm creating a chat application and facing a problem while creating a group (Recycler View's List item) and to inflate it over the fragment container.
Actually, two kind of views are being inflated. One is the root View that will be inflated in a fragment container and second is inflated as another custom layout for Dialog ask for input group name.
FAB is implemented as a click event to launch Dialog to input channel name. First time when i click a FAB, dialog appears ask for channel name to create group. After passing, an input group is created and Channel/Group (Recycler View's List item) is created and inflated over the container. But second time when I click on FAB, to repeat the process, to create another group/channel, the app crashes and error is encountered on logcat.
"The specified child already has a parent. You must call removeView() on the child's parent first".
I don't have too much knowledge about fragments and don't know what does that error means. Please help to resolve this error.
Thanks
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_open_channel_list, container, false);
CFAlertDialogue_footerView = inflater.inflate(R.layout.cfalertdialog_footer_view_open_channel, null);
editText_ChannelName = CFAlertDialogue_footerView.findViewById(R.id.textInputEditText_channelName);
setRetainInstance(true);
mRecyclerView = rootView.findViewById(R.id.recyclerView_openChannelList);
channelListAdapter = new openChannelListAdapter(getContext());
refreshLayout = rootView.findViewById(R.id.swipe_refresh_open_channel_list);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshLayout.setRefreshing(true);
refreshChannelList(CHANNEL_LIST_LIMIT);
}
});
actionButton = rootView.findViewById(R.id.fab_addOpenChannel);
actionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CFAlertDialog.Builder dialog = new CFAlertDialog.Builder(getContext())
.setDialogStyle(CFAlertDialog.CFAlertStyle.ALERT)
.setTitle("Create Open Channel")
.setTextGravity(Gravity.CENTER_HORIZONTAL)
.setCornerRadius(5)
.setCancelable(true)
.setFooterView(CFAlertDialogue_footerView)
.addButton("Cancel", Color.parseColor("#000000"), Color.parseColor("#f8f8ff"),
CFAlertDialog.CFAlertActionStyle.NEGATIVE, CFAlertDialog.CFAlertActionAlignment.JUSTIFIED,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.addButton("Create", Color.parseColor("#000000"), Color.parseColor("#8b3a3a"),
CFAlertDialog.CFAlertActionStyle.POSITIVE, CFAlertDialog.CFAlertActionAlignment.JUSTIFIED,
new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, int which) {
OpenChannel.createChannelWithOperatorUserIds(editText_ChannelName.getText().toString(),
null, null, null, null, new OpenChannel.OpenChannelCreateHandler() {
#Override
public void onResult(OpenChannel openChannel, SendBirdException e) {
if ( e != null){
Toast.makeText(getContext(), "Error Creating Channel: "+e.getCode()+" "
+e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
dialog.dismiss();
refreshChannelList(CHANNEL_LIST_LIMIT);
}
});
}
});
dialog.show();
}
});
setUpRecyclerViewAndAdapter();
return rootView;
}
Change to
final AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
b.setView(layout);
b.show();
to
final AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
b.setView(layout);
final AlertDialog alertDialog = b.show();
Try to change something like this

Categories