Here is the method where I need to get the text from the EditText of AlertDialog
public void checkButton() {
leggspillere = (Button) findViewById(R.id.leggspillere);
final LayoutInflater inflater = this.getLayoutInflater();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(inflater.inflate(R.layout.create_user,null));
builder.setMessage("Lag en spiller");
builder.setCancelable(true);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// trying to get the EditText-string inside alertdialogbox input here.
final String Name = UserName.
Person person = new Person(Name, 0);
dialog.dismiss();
spillere.setText(person.getName() + " " + person.getScore());
}
}
);
//sette andre knappen "cancel"
builder.setNegativeButton("no",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
XML:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="64dp"
android:scaleType="center"
android:background="#FFFFBB33"
android:contentDescription="#string/app_name" />
<EditText
android:id="#+id/UserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:inputType="textEmailAddress" />
</LinearLayout>
Trying to get the input/string from EditText.xml to make a person object.
Always referencing to a null object. I can't find any solution, point me somewhere.
How are you trying to access the editText inside DialogInterface.OnClickListener?
Try getting the inflated view in a View object and do findViewById on that View object variable. This code below should work fine:
LayoutInflater inflater = this.getLayoutInflater();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final View dialogView = inflater.inflate(R.layout.dialog_alert, null);
builder.setView(dialogView);
builder.setMessage("Lag en spiller");
builder.setCancelable(true);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
EditText editText = (EditText) dialogView.findViewById(R.id.d_alert_et);
Log.v("tag", "Edit text value: " + editText.getText());
}
});
builder.setNegativeButton("no",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
Basically get the inflated view in a View Object:
final View dialogView = inflater.inflate(R.layout.dialog_alert, null);
And then do findViewById on that View Object:
EditText editText = (EditText) dialogView.findViewById(R.id.d_alert_et);
editText.getText()
Pls. refer this code : https://www.mkyong.com/android/android-custom-dialog-example/
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Android custom dialog example!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
**EditText edtName = (EditText) dialog.findViewById(R.id.edtName);**
image.setImageResource(R.drawable.ic_launcher);
Button dialogButton = (Button)
dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
**String s = edtName.getText().toString();**
dialog.dismiss();
}
});
dialog.show();
}
i prefer to use Material Dialog library because it's very easy to use.
you can use custom view or use the simple input
1.simple input example from my project:
new MaterialDialog.Builder(this)
.title(R.string.input)
.content(R.string.input_content)
.inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)
.input(R.string.input_hint, R.string.input_prefill, new MaterialDialog.InputCallback() {
#Override
public void onInput(MaterialDialog dialog, CharSequence input) {
// Do something
}
}).show();
2.custom view example :
View view = LayoutInflater.from(context).inflate(R.layout.dialog_new_queue, null, false);
MaterialDialog dialog = new MaterialDialog.Builder(context)
.customView(view, false).build();
AutoCompleteTextView tv = view.findViewById(R.id.dialog_add_q_tv);
Button btn = view.findViewById(R.id.dialog_add_queue_btn);
btn.setOnClickListener(v -> {
String input = tv.getText().toString().trim();
Observable
.create(emitter -> {
if (input.isEmpty()) {
emitter.onError(new IllegalArgumentException("اسم صف خالی است"));
} else if (dao.getQueue(pref.getLastUsername(), input) != null) {
emitter.onError(new IllegalArgumentException("این اسم تکراری است!"));
} else {
QueueModel q = new QueueModel(input, pref.getLastUsername(), System.currentTimeMillis());
dao.insert(q);
emitter.onComplete();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(o -> {},e ->{
tv.setError(e.getMessage());
tv.requestFocus();
},() -> {
Toast.makeText(context, "صف جدید ساخته شد", Toast.LENGTH_SHORT).show();
dialog.dismiss();
loadData();
});
});
dialog.show();
Replace the 2 lines:
final String Name = UserName.
Person person = new Person(Name, 0);
By
EditText editText = (EditText) dialogView.findViewById(R.id.UserName);
Person person = new Person(editText.getText(), 0);
Try this
public void checkButton() {
leggspillere = (Button) findViewById(R.id.leggspillere);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.create_user, null));
builder.setMessage("Lag en spiller");
builder.setCancelable(true);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Change here
Dialog myDialog = (Dialog) dialog;
EditText editText = (EditText) myDialog.findViewById(R.id.UserName);
Person person = new Person(editText.getText(), 0);
}
})
//sette andre knappen "cancel"
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create().show();
}
Related
I created a custom AlertDialog and I want to save the values that the user has set. However I can't access them because Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference.
I am in HomeFragment, I created the AlertDialog and set the layout. I did it like this :
public class HomeFragment extends Fragment implements CustomDialog.CustomDialogListener {
private HomeViewModel homeViewModel;
private View root;
public View onCreateView(#NonNull final LayoutInflater inflater,
final ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
root = inflater.inflate(R.layout.fragment_home, container, false);
final TextView textView = root.findViewById(R.id.text_home);
homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
Button btn_add_apero = (Button) root.findViewById(R.id.btn_add_apero);
btn_add_apero.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(root.getContext());
builder.setTitle("Super un nouvel apéro !");
final EditText name_apero = (EditText)root.findViewById(R.id.edit_apero);
final EditText date_apero = (EditText)root.findViewById(R.id.edit_date);
builder.setView(inflater.inflate(R.layout.layout_dialog, null))
// Add action buttons
.setPositiveButton(R.string.text_add, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
LaperoDatabase db = Room.databaseBuilder(root.getContext(),
LaperoDatabase.class, "lapero_db").allowMainThreadQueries().build();
AperoDao dbApero = db.getAperoDao();
Apero new_apero = new Apero(name_apero.getText().toString(), date_apero.getText().toString());
dbApero.insert(new_apero);
}
})
.setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
});
return root;
}
In my layout_dialog.xml I set the 2 EditText :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<EditText
android:id="#+id/edit_apero"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_apero" />
<EditText
android:id="#+id/edit_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/edit_apero"
android:layout_alignParentStart="true"
android:hint="#string/edit_date"
android:layout_alignParentLeft="true" />
</RelativeLayout>
How can I manage to get the value that are in those 2 fields ?
First thing i noticed is that you're using root to find your dialog views, but root points to your fragment layout. root = inflater.inflate(R.layout.fragment_home, container, false);
First inflate your dialog layout before referencing its resource id.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View inflater = getLayoutInflater().inflate(R.layout.layout_dialog, null);
builder.setView(inflater);
Then change root to inflater so you reference the view from your dialog layout
final EditText name_apero = (EditText)inflater.findViewById(R.id.edit_apero);
final EditText date_apero = (EditText)inflater.findViewById(R.id.edit_date);
Full code
Button btn_add_apero = (Button) root.findViewById(R.id.btn_add_apero);
btn_add_apero.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
View inflater = getLayoutInflater().inflate(R.layout.layout_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(inflater);
builder.setTitle("Super un nouvel apéro !");
final EditText name_apero = (EditText)inflater.findViewById(R.id.edit_apero);
final EditText date_apero = (EditText)inflater.findViewById(R.id.edit_date);
// Add action buttons
builder.setPositiveButton(R.string.text_add, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
LaperoDatabase db = Room.databaseBuilder(root.getContext(),
LaperoDatabase.class, "lapero_db").allowMainThreadQueries().build();
AperoDao dbApero = db.getAperoDao();
Apero new_apero = new Apero(name_apero.getText().toString(), date_apero.getText().toString());
dbApero.insert(new_apero);
}
})
builder.setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
});
I am working on a coding exercise,which is about AlertDialog. In the Dialog, I hope the image or view can be placed on the top of the dialog,like a header,but it goes to the bottom.
The XML code:
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/star"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text=" choose your sex"
android:gravity="center_vertical"/>
Activity code:
private void showSingleDialog() {
LayoutInflater factory = LayoutInflater.from(this);
final View view = factory.inflate(R.layout.activity_solo, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view);
final String[] sex = {
"male",
"felmale",
"unknow",
"guess"
};
builder.setSingleChoiceItems(sex, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
Toast.makeText(MainActivity.this, "your choice is:" + sex[i], Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
builder.show();
}
I tried to place the builder.setView(view) in different place, it still go to the bottom.
Is there any hints for me? Thanks a lot
p.s Sorry for my poor English, I attached the image hereMy Result
I hope the little Star and "choose your sex" go on the top
Alternatively you can achieve the same view with drawable and title methods:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] array = {"male","felmale","unknow","guess"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(R.drawable.ic_star);
builder.setTitle("Choose your sex")
.setSingleChoiceItems(array, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
sex = array[i];
//handle on click
}
});
return builder.create();
}
I achieved the same view like this:
I am very new to Java and I'm trying to keep things simple. Why doesn't this work? I have an XML layout with a EditText field and a Submit Button. I want to press it, an AlertDialog to pop up with the TextView of what I inputted into the EditText. What I tried keeps crashing:
//CustomAlertDialogPopUp
public void submitButton(View v) {
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.alertXML, null);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Alert");
alert.setView(alertLayout);
AlertDialog dialog = alert.create();
dialog.show();
EditText text1 = (EditText)findViewById(R.id.inputText);
TextView text2 = (TextView)findViewById(R.id.alertText);
String result = text1.getText().toString();
text2.setText(result);
}
Sorry if I sound stupid! Like I say, super new.
If you want to keep it simple, this will work:
For custom AlertDialog view you can refer to this question
public void submitButton(View v){
new AlertDialog.Builder(this)
.setTitle("Message")
.setMessage(text1.getText().toString())
.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
This is my GoogleMapAPI, I wish user can type the Marker information first, and then use that to make the marker.
But LogCat always say "String MarkerInfo = markerInfo.getText().toString();" Fail.
Sorry I'm a newbie for coding. Please help me.
public void onMapLongClick(final LatLng point) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle(R.string.funtion);
builder1.setItems(choice, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int selectedItem) {
Toast.makeText(MainActivity.this,"You Select Letter "+choice[selectedItem],Toast.LENGTH_SHORT).show();
dialog.dismiss();
if(selectedItem==1){
AlertDialog.Builder builder2;
Context mContext = MainActivity.this;
LayoutInflater inflater = getLayoutInflater();
builder2 = new AlertDialog.Builder(mContext);
markerInfo = (EditText)findViewById(R.id.markerInfo);
builder2.setView(inflater.inflate(R.layout.markerinfo, null))
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface marker, int id) {
String MarkerInfo = markerInfo.getText().toString();
map.addMarker(new MarkerOptions()
.position(point)
.title(MarkerInfo)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface marker, int id) {
}
});
builder2.setTitle(R.string.typeinfo);
AlertDialog marker = builder2.create();
marker.show();
}
}
});
AlertDialog alert = builder1.create();
alert.show();
}
Looks like R.id.markerInfo is declared insido markerinfo.xml, so you have to use the "inflated" version of markerinfo.xml to retrieve the EditText
View view = inflater.inflate(R.layout.markerinfo, null);
markerInfo = (EditText)view.findViewById(R.id.markerInfo);
builder2.setView(view);
I use this code to build an AlertDialog with an EditText:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setView(LayoutInflater.from(context).inflate(R.layout.dialog_view, null));
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mInput = ((EditText) LayoutInflater.from(context).inflate(R.layout.dialog_view, null).findViewById(R.id.etxtDialog)).getText().toString();
}
});
builder.show();
When I run this code though, the mInput.length() == 0, so the string is empty. The line mInput = ((EditText) LayoutInflater.from(context).inflate(R.layout.dialog_view, null).findViewById(R.id.etxtDialog)).getText().toString(); is executed though and the EditText does contain some characters. Why isn't this code working?
You are doing it wrong... Hold the instance of your inflated view and use it later. For example:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
final View v = LayoutInflater.from(context).inflate(R.layout.dialog_view, null);
builder.setView(v);
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mInput = ((EditText)v.findViewById(R.id.etxtDialog)).getText().toString();
}
});
builder.show();
This is because you are creating a new view each time you click on the positiveButton (inflate is called every time). You should do it like this:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
View v=LayoutInflater.from(context).inflate(R.layout.dialog_view, null);
builder.setView(v);
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mInput = ((EditText) v.findViewById(R.id.etxtDialog)).getText().toString();
}
});
builder.show();
use this way
ContextThemeWrapper cw = new ContextThemeWrapper( this, R.style.AlertDialogTheme );
AlertDialog.Builder builder= new AlertDialog.Builder( cw );
LayoutInflater inflater = (LayoutInflater) cw.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialog_view,null);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setView(layout);
mInput = (EditText)layout.findViewById(R.id.etxtDialog);
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String value = mInput.getText().toString();
}
});
builder.show();
Here: R.style.AlertDialogTheme is your application theme
Try this. Your full and final solution. This is how i did:
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
String currentDateandTime = sdf.format(new Date());
userInput.setText(currentDateandTime);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
if(userInput.getText()+"" != "")
{
Intent i = new Intent(MainActivity.this,AskForTextFile.class);
i.putExtra("userInput",userInput.getText()+"");
startActivity(i);
}
else
{
Toast.makeText(context, "Please enter backup name to go further.", Toast.LENGTH_LONG).show();
}
}
}
);
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
dialog.cancel();
}
}
);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
Try this---
Replace this line---
mInput = ((EditText) LayoutInflater.from(context).inflate(R.layout.dialog_view, null).findViewById(R.id.etxtDialog)).getText().toString();
With--
mInput = ((EditText) builder.findViewById(R.id.etxtDialog));
String input= mInput.getText().toString();