getting null pointer exception inside custom dialogBox [duplicate] - android

This question already has answers here:
EditText inside AlertDialog always null
(3 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Hey I am creating a custom dialog box containing 2 editText. I don't know what is wrong with this code but whenever the user click on submit it say null values inside the editText.
Can anyone help on this ?
Below is the code for custom dialogBox
private void showPriceDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
final View dialogView = LayoutInflater.from(this).inflate(R.layout.content_price_filter,null);
//Button submitBtn = (Button)findViewById(R.id.submitBtn);
builder.setView(dialogView);
final android.support.design.widget.TextInputEditText minPrice = (android.support.design.widget.TextInputEditText)findViewById(R.id.minPrice);
final android.support.design.widget.TextInputEditText maxPrice = (android.support.design.widget.TextInputEditText)findViewById(R.id.maxPrice);
builder.setTitle("Set Price");
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String max = maxPrice.getText().toString();
String min = minPrice.getText().toString();
if (max.equals("") || min.equals("")){
Toast.makeText(getApplicationContext(),"empty fields",Toast.LENGTH_SHORT).show();
return;
}
mPriceValueTxt.setText(max + " Rs min :"+ min);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog al = builder.create();
al.show();
}
Below is the layout of the custom dialog Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TextInputLayout
android:id="#+id/minPriceSelector"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="text"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toLeftOf="#+id/maxPriceSelector"
android:layout_marginRight="8dp"
android:layout_marginLeft="8dp">
<android.support.design.widget.TextInputEditText
android:id="#+id/minPrice"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Min Price"
android:inputType="number"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/maxPriceSelector"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="text"
app:layout_constraintLeft_toRightOf="#+id/minPriceSelector"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp">
<android.support.design.widget.TextInputEditText
android:id="#+id/maxPrice"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Max Price"
android:inputType="number"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
</android.support.constraint.ConstraintLayout>
This is the error i am getting while clicking submit
09-03 13:11:30.180 22652-22652/com.example.ashis.propertysearch E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ashis.propertysearch, PID: 22652
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.support.design.widget.TextInputEditText.getText()' on a null object reference
at com.example.ashis.propertysearch.FiltersActivity$1.onClick(FiltersActivity.java:290)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6204)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)

you have to do like below.
builder.setView(dialogView);
final android.support.design.widget.TextInputEditText minPrice = (android.support.design.widget.TextInputEditText) dialogView.findViewById(R.id.minPrice);
final android.support.design.widget.TextInputEditText maxPrice = (android.support.design.widget.TextInputEditText) dialogView.findViewById(R.id.maxPrice);

Related

Why is EditText.getText() returning null?

So while I was making my first project in android studio, I tried making an alert box where I can take inputs from 2 EditTexts and take them as arguments for creating an RecyclerView Element, but it turns out it's returning null (even though IDs of the EditTexts are mentioned correctly)
fa = findViewById(R.id.add_alarm_fab);
fa.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this);
builder.setTitle("Add slots");
View customLayout = getLayoutInflater().inflate(R.layout.alert_dialog_layout,null);
builder.setView(customLayout);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
EditText editText1 = findViewById(R.id.edCentre);
EditText editText2 = findViewById(R.id.edSlots);
String centreName = editText1.getText().toString();
Integer slots = Integer.parseInt(editText2.getText().toString());
if (centreName!=null && slots!=null)
medCentreArrayList.add(new MedCentre(centreName,slots));
ad.notifyDataSetChanged();
}
});
builder.create().show();
}
});
This is my XML file for the alert dialog:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/edSlots"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:ems="10"
android:hint="Slots available"
android:inputType="textPersonName"
android:padding="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/edCentre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:padding="20dp"
android:ems="10"
android:hint="Centre Name"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="#+id/edSlots"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Image of alert dialog layout:
And Image of alert dialog:
Looks like you need to find your view in the dialog container, something like this:
EditText editText1 = customLayout.findViewById(R.id.edCentre);

AlertDialog to only stay open on condition not working

I have the following code and only want my positive button to close if a certain condition is met, otherwise I want it to stay open with the same data:
protected void showInputDialog() {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.phrase_input_layout, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle("Create new phrase flashcard");
dialogBuilder.setPositiveButton("Done", (dialog, whichButton) -> {
SubmissionState state = addCardToDocument(dialogView);
if (state == SubmissionState.SUBMITTED_WITH_RESULTS_FOUND){
dialog.dismiss();
} else {
// still stay open here, but it still closes...
}
});
dialogBuilder.setNegativeButton("Cancel", (dialog, whichButton) -> Log.d("DEBUG", "Cancelled creating new phrase card."));
AlertDialog b = dialogBuilder.create();
b.show();
}
However, it appears no matter what, when I press the positive button, the dialogBuilder will close, regardless if it goes into the else statement or not; also, even if I comment out all of the code for the setPositiveButton it will still dismiss the dialog!
What am I doing wrong?
If it's relevant, here is my phrase_input_layout too:
<TextView
android:id="#+id/phrase_translate_radio_group_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="14dp"
android:layout_marginBottom="4dp"
android:text="#string/select_translation_mode"
android:textAppearance="#style/TextAppearance.AppCompat.Body2" />
<RadioGroup
android:id="#+id/phrase_translate_radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/phrase_manual_translation"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/manual_translation" />
<RadioButton
android:id="#+id/eng_auto_translation"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="#string/english_auto_translation" />
<RadioButton
android:id="#+id/swe_auto_translation"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/swedish_auto_translation" />
</RadioGroup>
<EditText
android:id="#+id/englishPhrase"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="#string/english_phrase" />
<EditText
android:id="#+id/swedishPhrase"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="#string/swedish_phrase" />
</LinearLayout>
You cannot do that by using the provided setPositiveButton method. If you set a listener using this method, then whenever the button is clicked the listener is invoked and then the dialog is dismissed. I don't see a way to override this behavior as AlertDialog internally uses an AlertController object that implements this behavior.
So what you can do is use custom buttons instead of the default ones.
For example, you could add two buttons at the bottom of phrase_input_layout xml.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/negativeButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<View
android:id="#+id/buttonSeparator"
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#color/separator" />
<Button
android:id="#+id/positiveButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
Set click listeners for these buttons. Like so:
AlertDialog dialog;
protected void showInputDialog() {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.phrase_input_layout, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle("Create new phrase flashcard");
Button positiveButton = (Button) dialogView.findViewById(R.id.positiveButton);
Button negativeButton = (Button) dialogView.findViewById(R.id.negativeButton);
positiveButton.setText("Create new phrase flashcard");
positiveButton.setOnClickListener(view -> {
SubmissionState state = addCardToDocument(dialogView);
if (state == SubmissionState.SUBMITTED_WITH_RESULTS_FOUND){
dialog.dismiss();
} else {
}
});
negativeButton.setText("Cancel");
negativeButton.setOnClickListener(view -> {
dialog.dismiss()
});
dialog = dialogBuilder.create();
dialog.show();
}

NPE at android.text.Editable android.widget.EditText.getText()' on a null object reference

I have this NPE when I call getText() on EditText.
I have an alert and I set my layout as a view to an alert and I need to get the text from EditText.
Thank you for any help
Here is my code
LinearLayout view;
EditText input;
Button in;
Button gfxtr;
Button gfh;
private void numItem(int position) {
view = (LinearLayout) getLayoutInflater()
.inflate(R.layout.dialog, null);
input = (EditText) findViewById(R.id.input);
in = (Button) findViewById(R.id.in);
gfxtr = (Button) findViewById(R.id.gfxtr);
gfh = (Button) findViewById(R.id.gfh);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Введите новое количество");
alert.setView(view);
alert.setPositiveButton("ДА", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String qq = input.getText().toString();
}
});
alert.setNegativeButton("НЕТ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<EditText
android:id="#+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"></EditText>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<Button
android:id="#+id/in"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:onClick="in"
android:scaleType="fitCenter"
android:text="шт"></Button>
<Button
android:id="#+id/gfxtr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="gfxtr"
android:scaleType="fitCenter"
android:text="пачек"></Button>
<Button
android:id="#+id/gfh"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="gfh"
android:scaleType="fitCenter"
android:text="пар"></Button>
</LinearLayout>
</LinearLayout>
I get this error:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.text.Editable android.widget.EditText.getText()' on a null
object reference
You don't call findViewById on view. Try it like this:
input = (EditText) view.findViewById(R.id.input);

Android dialog layout broken how to fix?

I had problems with this when I was programming it. I thought I'd cured it by specifying a fixed percentage height for the body of the dialog. I thought this was bad form, because the user might have a slim display, or set large fonts, which would cut of the EditText box.
Anyway that solution has failed beyond the emulator.
It looks like Android is assigning a fixed height to a dialog, and if my custom title has devoured too much of this height, squeezing everything else off. Is this correct and how do I fix it?
Problem
public class GetUserNameDialogFragment extends DialogFragment {
final String TAG = "GetUserNameDialog";
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogStyle);
//TODO getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
LayoutInflater inflater = getActivity().getLayoutInflater();
final View sunburst =inflater.inflate(R.layout.dialog_user_name, null);
builder.setView(sunburst);
builder.setCancelable(false)
.setPositiveButton("Let's go!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.wtf(TAG, "button press");
EditText name = (EditText) sunburst.findViewById(R.id.nameEditText);
String userName = name.getText().toString().trim();
//TODO needs to be validated
SharedPreferences sharedPref = getActivity().getSharedPreferences("userDetails", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("userName", userName );
editor.commit();
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Here's the xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
app:srcCompat="#drawable/ic_ball_sunburst_classic"
android:background="#color/colorAccent"
/>
<LinearLayout
android:layout_width="250dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:layout_height="125dp">
<EditText
android:id="#+id/nameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:hint="Enter your first name"/>
</LinearLayout>
</LinearLayout>
All help very much appreciated, the first impression of my app - what a disaster!
Why don't you use Dialog instead of AlertDialog ?
I built the example using a Dialog and it works perfectly
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:layout_width=" 290dp"
android:layout_height="wrap_content"
android:background="#4CAF50">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
android:src="#drawable/base"
android:background="#color/colorAccent"
/>
<EditText
android:textColor="#fff"
android:textColorHint="#fff"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:id="#+id/nameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your first name"/>
<Button
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:id="#+id/letsGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Let's Go"
android:textColor="#fff"
android:background="#android:color/transparent"/>
final Dialog dialog = new Dialog(context);
if(dialog.getWindow() != null){
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
dialog.setContentView(R.layout.dialog);
Button letsGO = (Button) dialog.findViewById(R.id.letsGo);
EditText nameEditText = (EditText) dialog.findViewById(R.id.nameEditText);
letsGO.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Lets GO!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.show();

Problems in designing AlertDialog

I am trying to design AlertDialog, but I can't get rid of the black surrounding (As indicated by the red line), and the orange surrounding (As indicated by the blue line).
This is my xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#android:color/darker_gray" >
<TextView
android:src="#drawable/save_as"
android:id="#+id/label_save_as"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:text="#string/save_as" />
<EditText
android:id="#+id/filename"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="#string/filename" />
</LinearLayout>
This is the code:
AlertDialog.Builder saveAsBuilder = new AlertDialog.Builder(this);
LayoutInflater saveAsInflater = this.getLayoutInflater();
saveAsBuilder.setView(saveAsInflater.inflate(R.layout.saveas, null))
.setNeutralButton(R.string.saveAsImg, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// do something
}
})
.setPositiveButton(R.string.saveAsSkt, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do something
}
});
d = saveAsBuilder.create();
d.setCanceledOnTouchOutside(true);
d.show();
How can I get rid of those?
BTW , I am using API 10.
Once try to change like this and try..
AlertDialog.Builder saveAsBuilder = new AlertDialog.Builder(this,android.R.style.Theme_Translucent);
setting the theme for the dialog to remove the black spaces
with using dialog..
Dialog dialog=new Dialog(getApplicationContext());
dialog.setContentView(R.layout.yourlayout);
for this you have to create two buttons in layout and implement listeners for that..

Categories

Resources