Right, I know there's alot of similar questions. I've researched on stackoverflow as well as on the internet about this but still stumped.
This code is in a fragment.
...
private Context context = getActivity();
public void Dialog(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View mView = inflater.inflate(R.layout.dialog, null);
alertDialogBuilder.setView(mView);
EditText a = (EditText) mView.findViewById(R.id.a);
EditText b = (EditText) mView.findViewById(R.id.b);
EditText c = (EditText) mView.findViewById(R.id.c);
//a.setText("abc");
//b.setText("xyz");
//c.setText("123");
strA = a.getText().toString();
strB = b.getText().toString();
final String strC = c.getText().toString();
}
This should be a typical approach to getting the view of the inflated layout and using it to access the elements inside the view, but it's not working no matter what I tried, I just could not get strA, strB and strC values using getText().toString().
//a.setText("abc");
//b.setText("xyz");
//c.setText("123");
But, if I uncomment the above 3 lines, the values get sent across. And I can receive them inside strA, strB, strC. Why is this so? I don't get it at all.
Any help greatly appreciated, thank you!
You are trying to get values at the time you initialize the dialog. you need to get values after an action, like a button click
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
strA = a.getText().toString();
strB = b.getText().toString();
}
});
Have a look at this display textview in alert dialog
Looks to me like you're checking the values of the EditTexts as soon as they're created. Which of course the value is going to be null every time since your user hasn't had time to type anything. I think you need a SubmitButton or something similar that checks the EditTexts in its onClickListener. Though I'll admit I've never inflated a view into an alert dialog.
Try like this.
MyDialogue is your Activity name.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MyDialogue.this);
// Get the layout inflater
LayoutInflater inflater = MyDialogue.this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View mView = inflater.inflate(R.layout.dialog, null);
alertDialogBuilder.setView(mView);
final EditText a = (EditText) mView.findViewById(R.id.a);
final EditText b = (EditText) mView.findViewById(R.id.b);
final EditText c = (EditText) mView.findViewById(R.id.c);
a.setText("abc");
b.setText("xyz");
c.setText("123");
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String strA = a.getText().toString();
final String strB = b.getText().toString();
final String strC = c.getText().toString();
Log.e("tag", strA + " " + strB + " " + strC );
}
});
alertDialogBuilder.show();
The layout is not yet initiated when you are trying to set the values, you need to call AlertDialog alertDialog = alertDialogBuilder.create(); and then alertDialog.show(); or just alertDialogBuilder.show() before you can edit the textView content.
Related
I'm attempting to null check an EditText (which should be simple enough) however each time I enter text into my two ET's - they always return as empty: "" and they should not (if they have text in them).
I've looked over several other SO articles related to this and none of the fixes seem to resolve the issue.
Can anyone spot what I might be doing wrong in this instance?
Source Snippet:
Java class:
...
public void doneClicked(View v) throws JSONException {
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v1 = li.inflate(R.layout.profile_notification_settings_list_edit, null);
final EditText label = (EditText) v1.findViewById(R.id.emaillabel);
final EditText value = (EditText) v1.findViewById(R.id.emailvalue);
String sValue = value.getText().toString();
if (sValue.matches("")) {
Toast.makeText(this, "You did not enter a value", Toast.LENGTH_SHORT).show();
return;
}
String sLabel = label.getText().toString();
if (sLabel.matches("")) {
Toast.makeText(this, "You did not enter a label", Toast.LENGTH_SHORT).show();
return;
}
...
Adapter:
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflater.inflate(R.layout.profile_notification_settings_list_edit, null);
EditText value = (EditText) view.findViewById(R.id.emailvalue);
value.setHint("Value");
value.setText(valueList[i]);
EditText label = (EditText) view.findViewById(R.id.emaillabel);
if (labelList != null)
label.setHint("Label");
label.setText(labelList[i]);
Full source:
Java Class:
https://pastebin.com/y1e9J1yE
Adapter:
https://pastebin.com/Zqh3eCAk
Because everytime you click you are creating a new view which has nothing to do with the views currently being displayed on the screen
public void doneClicked(View v) throws JSONException {
// don't inflate new views
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v1 = li.inflate(R.layout.profile_notification_settings_list_edit, null);
final EditText label = (EditText) v1.findViewById(R.id.emaillabel);
final EditText value = (EditText) v1.findViewById(R.id.emailvalue);
// ... code
Note : you cannot directly fetch the data from rowItemVies from ListView , so you need to add method in your adapter class to get the selected position through which you can fetch the rowView using yourListView.getChildAt(position) and further fetch data from children in rowView
use
sValue.trim().equals("") instead of sValue.matches("")
I have implemented form in my dialog, and when positive button is clicked I create new object to ma database. I've created global variable for EditText's but still not work. Where I want get text value from them I always get empty string.
here is code:
EditText name, desc;
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
view = inflater.inflate(R.layout.new_dialog, null);
name = (EditText) view.findViewById(R.id.workout_name);
desc = (EditText) view.findViewById(R.id.workout_description);
builder.setView(inflater.inflate(R.layout.new_dialog, null)).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MyDbHelper helper = new MyDbHelper (getActivity());
MyObj w = new MyObj ();
w.setName(name.getText().toString(););
w.setDescription(desc.getText().toString());
w.setLevel(1);
long id = helper.createWorkout(w);
Toast.makeText(getActivity(), id+"", Toast.LENGTH_LONG).show();
callback.onPositiveButtonClick();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
callback.onNegativeButtonClick();
}
});
return builder.create();
}
Any ideas please?
I stumbled upon the same issue. You can get the views inflated in the dialog using getDialog() provided by the onClick.
((EditText) getDialog().findViewById(R.id.your_editText_ID)).getText().toString()
In below code, you are inflating new_dialog layout and your name and desc EditTexts belong to this layout.
view = inflater.inflate(R.layout.new_dialog, null);
name = (EditText) view.findViewById(R.id.workout_name);
desc = (EditText) view.findViewById(R.id.workout_description);
But when you are setting the layout of the dialog you are setting new_workout_dialog. your name and desc do not belong to this layout.
builder.setView(inflater.inflate(R.layout.new_workout_dialog, null))
Furthermore, even if you used new_dialog while setting the builders view, name and desc would still be irrelevant. Because you are completely creating a new view inside setView method.
Use the view variable as following:
builder.setView(view, null))
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.
i've got a alertdialog which shows rating bar.
LayoutInflater rating = LayoutInflater.from(RatingActivity.this);
final View v = rating.inflate(R.layout.rating_layout, null);
AlertDialog.Builder adb = new AlertDialog.Builder(RatingActivity.this);
adb.setTitle("Rate us!);
adb.setView(v);
AlertDialog ratingbar = adb.create();
final RatingBar cleanbar = (RatingBar) ratingbar.findViewById(R.id.clealiness);
when I triggered onclick listener, it shows NULL POINTER EXCEPTION. and 2nd line error says error in getNumStars() line.. Force close after that.
adb.setPositiveButton("Rate", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//this line error. means they cant get the rating value?
final String cleaninput = Integer.toString(cleanbar.getNumStars());
may i know any other ways to get the value of ratingbar? i've seen few like ratingBar.getRating(); ratingBar.getNumStars();
all of them could not work... even i put the value direct into int.
final int cleaninput = (int) cleanbar.getRating(); //fails
EDITTED (SOLVE)::
final RatingBar cleanbar = (RatingBar)v.findViewById(R.id.clealiness);
i replace the ratingbar to v instead and it works! i do not know the reason >.<
I think your problem is this:
final RatingBar cleanbar = (RatingBar) ratingbar.findViewById(R.id.clealiness);
It won't initialise correctly RatingBar because you are not initialising RatingBar from layout of Activity(that contains RatingBar) and this is reason why you get NPE at
cleanbar.getNumStars() // cleanbar is assigned as null
Change it to
final RatingBar cleanbar = (RatingBar) findViewById(R.id.clealiness);
Now it should work.
Update:
LayoutInflater rating = LayoutInflater.from(RatingActivity.this);
final View ratingView = rating.inflate(R.layout.rating_layout, null);
AlertDialog.Builder adb = new AlertDialog.Builder(RatingActivity.this);
adb.setTitle("Rate us!);
adb.setView(ratingView);
AlertDialog ratingbar = adb.create();
Now for getting value correctly:
RatingBar cleanbar = (RatingBar) ratingView.findViewById(R.id.clealiness);
You need to assign RatingBar with View you inflated.
Now it should works:
final int cleaninput = (int) cleanbar.getRating();
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);