How to add RadioGroup and EditText to AlertDialog? - java

Hi I want to get user name and user gender using alert dialog so I add:
AlertDialog.Builder user= new AlertDialog.Builder(this);
user.setTitle("New Student");
user.setMessage("What is your Name?");
final RadioGroup genderRG= new RadioGroup(this);
RadioButton radiomr = new RadioButton(this);
radiomr.setText("Mr");
// radiomr.setId(1);
genderRG.addView(radiomr);
RadioButton radiomiss = new RadioButton(this);
radiomiss.setText("Miss");
// radiomiss.setId(2);
genderRG.addView(radiomiss);
user.setView(genderRG);
final EditText input = new EditText(this);
user.setView(input);
user.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int whichButton)
{
// get data
}
});
user.setNegativeButton("CANCEL", null);
user.create().show();
But when I run it, It just gives me an EditText.
Please! How can I get Gender and Name in same AlertDialog using radio button or spinner.

You should create your own layout and set it via setView().
You are instead inflating just the EditText, this is why you have just that in the dialog.
In any case it is better to use DialogFragment to create your own dialog version.
More here https://developer.android.com/reference/android/app/DialogFragment

Related

Android : EditText and TextView are misaligned in alertdialog

In this code, I am making an AlertDialog with attributes title, EditText, TextView, Cancel Button, and Email me Button.
EditText and TextView not aligned/set properly.
// Alert Dialog
private void showForgotpasswdDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Forgot your password?");
// Set linear layout
LinearLayout linearLayout = new LinearLayout(this);
// View to set an dialog
final EditText Email = new EditText(this);
Email.setHint("Email");
Email.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
// Text view
linearLayout.addView(Email);
builder.setView(linearLayout);
// Text view
final TextView tv = new TextView(this);
tv.setText("Unfortunately, if you have never given us your email, we will not be able to reset your password");
linearLayout.addView(tv);
builder.setView(linearLayout);
// Buttons for EMAIL ME
builder.setPositiveButton("EMAIL ME", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// Input email
String email = Email.getText().toString().trim();
beginforgotpasswd(email);
}
});
// Buttons for CANCEL
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
// Dismiss dialog
dialog.dismiss();
}
});
// Show dialog
builder.create().show();
}
Please see the following screenshot showing the misaligned EditText:
just try it:
linearLayout.setOrientation(LinearLayout.VERTICAL);
to get proper orientation!

Removing TextViews when i clicked backbutton

My problem is I have a button and that button is doing create new textview but that textviews removing when i click back button. How I saved textviews in activity?
My java sourcecodes here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notlar);
Button btnNotEkle = (Button) findViewById(R.id.btnNotEkle);
final EditText etNot = new EditText(NotEkle.this);
final LinearLayout layoutNotlar = (LinearLayout) findViewById(R.id.layoutNotlar);
final TextView tv1 = (TextView) findViewById(R.id.tvnotOrtalama);
etNot.setInputType(InputType.TYPE_CLASS_NUMBER);
AlertDialog.Builder notEkle = new AlertDialog.Builder(NotEkle.this);
notEkle.setTitle("Notunuz");
notEkle.setView(etNot);
//Positive button
notEkle.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tvNot = new TextView(NotEkle.this);//girelen not burdaki textview e yazdırılacak.
girilenNot = etNot.getText().toString();//Girilen notu alıyoruz
tvNot.setText(girilenNot);//girilen notu textviewa veriyoruz
notTopla += Integer.parseInt(girilenNot);//Notları topluyoruz
layoutNotlar.addView(tvNot);
count = layoutNotlar.getChildCount();
dersOrtalamaYazdir=String.valueOf(dersOrtalama());
tv1.setText("Ders Ortalamanız : "+dersOrtalamaYazdir);
dialog.cancel();
}
});
final AlertDialog notEkleCreate = notEkle.create();
btnNotEkle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
notEkleCreate.show();
}
});
}
}
Try giving your TextView objects ids.
You need to know that when you click back button - by default your activity is destroyed so all views are removed.
When you are adding new TextView you should add information about this TextView (like the text itself) to some list declared as field in your activity.
Then you can save this list when activity is recreated see: onSaveInstanceState/nRestoreInstanceState
You can also pass this list back or to new activity so that they can take actions based on this list.
Following my understanding your TextView had been created inside Dialog and after you press back button the dialog dismisses and all views you created inside will be removed and you can't access it from your Activity.
You may try to create TextView in onCreate, pass and in Dialog just call setText. I hope this is the answer you're looking for.
Cheers.

Edittext field outside scope of alert dialog? Nullpointer Exception

I created an AlertDialog such that when you press a Button, the Dialog pops up and a layout appears with EditTexts. However, I created the layout in the actual code rather than in the xmlfile. For some reason, when the AlertDialog pops up, it's not able to find the EditText field and gives me a NullPointerException.
//private Lecture lecture;
private LectureManager lectureManager;
public void addWork(View view) {
LinearLayout layout = new LinearLayout(this);
EditText weight = new EditText(this);
EditText mark = new EditText(this);
mark.setInputType(InputType.TYPE_CLASS_NUMBER);
weight.setInputType(InputType.TYPE_CLASS_NUMBER);
weight.setId(99);
mark.setId(100);
layout.addView(mark);
layout.addView(weight);
AlertDialog.Builder addwork = new AlertDialog.Builder(this);
addwork.setView(layout);
addwork.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText eweight = (EditText) findViewById(99);
EditText emark = (EditText) findViewById(100);
String coursename = ecoursename.getText().toString();
And for some reason, I'm getting a NullPointerException at the "EditText weight" line. I believe that maybe it's not finding anything with ID 99 and that the EditText might be out of scope? Thanks in advance!
Actually, when you make these calls:
EditText eweight = (EditText) findViewById(99);
EditText emark = (EditText) findViewById(100);
you're calling the findViewById() method of your Activity, not the AlertDialog. In order to retrieve the views from the Dialog, you can use something like this, inside onClick():
EditText eweight = (EditText) ((AlertDialog)dialog).findViewById(99);
EditText emark = (EditText) ((AlertDialog)dialog).findViewById(100);
Hope this helps.
Try this..
Use final for both EditText while initilization like below
final EditText weight = new EditText(this);
final EditText mark = new EditText(this);
Then you can get the text from EditText in PositiveButton
String weight_txt = weight.getText().toString().trim();
String mark_txt = mark.getText().toString().trim();
No need to set id for EditText also no need findViewById.
i think you need to do this
EditText eweight = (EditText) view.findViewById(99);
and view is , what you have passed in your addWork() method parameter.

AlertDialog Closing Automatically

I have an AlertDialog for showing a small form to the user.
On the ALertDialog are 2 buttons; namely "Submit" & "Cancel".
Now the fields (EditTexts) have setKeyListeners attached to them individually.
The problem which I face is suppose the user doesn't fills in any field and directly clicks on Submit button then the dialog box closes automatically.
Here's my Method which is called for creating/showing the Dialog Box:
Context ctx = this.getApplicationContext();
LinearLayout layoutCreateMerch = new LinearLayout(ctx);
layoutCreateMerch.setOrientation(LinearLayout.VERTICAL);
layoutCreateMerch.setVerticalScrollBarEnabled(true);
final AlertDialog.Builder alert = new AlertDialog.Builder(Store.this);
alert.setTitle("New Store");
final EditText stoName = new EditText(Store.this);
final EditText stoDesc = new EditText(Store.this);
InputFilter[] FilterMaxLen = new InputFilter[1];
FilterMaxLen[0] = new InputFilter.LengthFilter(25);
stoName.setFilters(FilterMaxLen);
stoName.setHint("Store's Name");
stoName.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,'1234567890 "));
stoName.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
layoutCreateMerch.addView(stoName);
stoDesc.setFilters(FilterMaxLen);
stoDesc.setHint("Store's Description");
stoDesc.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,'1234567890 "));
stoDesc.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
layoutCreateMerch.addView(stoDesc);
ScrollView scroll = new ScrollView(ctx);
scroll.setBackgroundColor(Color.TRANSPARENT);
scroll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
scroll.addView(layoutCreateMerch);
alert.setView(scroll);
alert.setNeutralButton("Submit",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (Name.getText().toString().equals("")
|| Desc.getText().toString().equals(""))
{
if(stoName.getText().toString().equals("")){
stoName.setHint("fill Store's Name");
stoName.setHintTextColor(Color.RED);
}
else{}
if( stoDesc.getText().toString().equals("")){
stoDesc.setHint("fill Store's Description");
stoDesc.setHintTextColor(Color.RED);
}
else{}
if..
..
..
}
else {
System.out.println("should not exit :| ");
}
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.cancel();
}
});
alert.show();
Any advice is appreciated..
Thanks
Add addTextChangedListener for your EditText and then always check user have entered any text or not as if not disable the submit button else enable the submit button dynamically.

Null Validation on EditText box in Alert Dialog - Android

I am trying to add some text validation to an edit text field located within an alert dialog box. It prompts a user to enter in a name.
I want to add some validation so that if what they have entered is blank or null, it does not do anything apart from creating a Toast saying error.
So far I have:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Record New Track");
alert.setMessage("Please Name Your Track:");
// Set an EditText view to get user input
final EditText trackName = new EditText(this);
alert.setView(trackName);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String textString = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
}
else
{
SQLiteDatabase db = waypoints.getWritableDatabase();
ContentValues trackvalues = new ContentValues();
trackvalues.put(TRACK_NAME, textString);
trackvalues.put(TRACK_START_TIME,tracktimeidentifier );
insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues);
}
But this just closes the Alert Dialog and then displays the Toast. I want the Alert Dialog to still be on the screen.
Thanks
I think you should recreate the Dialog, as it seems the DialogInterface given as a parameter in onClick() doesn't give you an option to stop the closure of the Dialog.
I also have a couple of tips for you:
Try using Activity.onCreateDialog(), Activity.onPrepareDialog() and of course Activity.showDialog(). They make dialog usage much easier (atleast for me), also dialog usage looks more like menu usage. Using these methods, you will also be able to more easilty show the dialog again.
I want to give you a tip. It's not an answer to your question, but doing this in an answer is much more readable.
Instead of holding a reference to an AlertDialog.Builder() object, you can simply do:
new AlertDialog.Builder(this)
.setTitle("Record New Track")
.setMessage("Please Name Your Track:")
//and some more method calls
.create();
//or .show();
Saves you a reference and a lot of typing ;). (almost?) All methods of AlertDialog.Builder return an AlertDialog.Builder object, which you can directly call a method on.
The same goes for Toasts:
Toast.makeText(this, "Please enter...", Toast.LENGTH_LONG).show();
I make a new method inside my class that shows the alert and put all the code for creating the alert in that one method. then after calling the Toast I call that method. Say I named that method createAlert(), then I have,
createAlert(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Record New Track");
alert.setMessage("Please Name Your Track:");
// Set an EditText view to get user input
final EditText trackName = new EditText(this);
alert.setView(trackName);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String textString = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
createAlert();
}
else
{
SQLiteDatabase db = waypoints.getWritableDatabase();
ContentValues trackvalues = new ContentValues();
trackvalues.put(TRACK_NAME, textString);
trackvalues.put(TRACK_START_TIME,tracktimeidentifier );
insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues);
}
}
What you should do is to create a custom xml layout including a textbox and an Ok button instead of using .setPositiveButton.
Then you can add a click listener to your button in order to validate the data and dismiss the dialog.
It should be used in CreateDialog:
protected Dialog onCreateDialog(int id)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (id==EDIT_DIALOG)
{
final View layout = inflater.inflate(R.layout.edit_dialog, (ViewGroup) findViewById(R.id.Layout_Edit));
final Button okButton=(Button) layout.findViewById(R.id.Button_OkTrack);
final EditText name=(EditText) layout.findViewById(R.id.EditText_Name);
okButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
String textString = trackName.getText().toString();
if (textString != null && textString.trim().length() ==0)
{
Toast.makeText(getApplicationContext(), "Please enter...", Toast.LENGTH_LONG).show();
} else
removeDialog(DIALOG_EDITTRACK);
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Edit text");
AlertDialog submitDialog = builder.create();
return submitDialog;
}
Even though it's an old post, the code below will help somebody. I used a customized layout and extended DialogFragment class.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the layout inflater
LayoutInflater inflater = requireActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.Name_of_the_customized_layout, null);
final EditText etxtChamp = view.findViewById(R.id.editText);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Enter a Name")
.setTitle("Mandatory field ex.");
builder.setView(view);
final Button btnOk = view.findViewById(R.id.ok);
final Button btnCancel = view.findViewById(R.id.cancel);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(etxtChamp.getText().toString().isEmpty()){
etxtChamp.setError("Oups! ce champ est obligatoire!");
}else{
//Get the editText content and do whatever you want
String messageEditText = etxtChamp.getText().toString();
dismiss();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
return builder.create();
}
Use This code for displaying Dialog.
public void onClick(DialogInterface dialog, int whichButton) {
String textSt`enter code here`ring = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
new AlertDialog.Builder(this)
.setTitle("Message")
.setMessage("please enter valid field")
.setPositiveButton("OK", null).show();
}
This will create a Dialog for you, editText is empty or what are conditions you wants.
//if view is not instantiated,it always returns null for edittext values.
View v = inflater.inflate(R.layout.new_location_dialog, null);
builder.setView(v);
final EditText titleBox = (EditText)v.findViewById(R.id.title);
final EditText descriptionBox = (EditText)v.findViewById(R.id.description);

Categories

Resources