Android: Null Pointer Exception in Dialog - android

I have a dialog box to be shown with two edittextboxes in it.
When I fill the fields and click on the submit button, I need to save the values in database. I am trying to get the values entered in the fields, but the Null Pointer Exception is raised.
My code is follows
View v = getLayoutInflater().inflate(R.layout.sample, null);
new AlertDialog.Builder(Context)
.setTitle(R.string.Details)
.setView(v)
.setNegativeButton(R.string.Cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
})
.setPositiveButton(R.string.Submit,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
final EditText txtname=(EditText)findViewById(R.id.editText1);
final EditText txtnumber=(EditText)findViewById(R.id.editText2);
Save(txtname.getText().toString(),txtnumber.getText().toString());
}
when I debug and checked, It shows the txtname and txtnumber values as empty. Where did I went wrong? I was using a layout to show the fields
The layout is,
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Name" />
<EditText
android:id="#+id/editText1"
android:layout_width="195dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:ems="10"
android:hint="FirstName LastName"
android:inputType="textPersonName" />
</TableRow>
<TableRow>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Phone" />
<EditText
android:id="#+id/editText2"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:ems="10"
android:inputType="number"
android:maxLength="10" />
</TableRow>
Please help me out to solve this exception!!

Your txtname and txtnumber are null
i.e
final EditText txtname=(EditText)findViewById(R.id.editText1);
final EditText txtnumber=(EditText)findViewById(R.id.editText2);
when you are trying to access null reference you will get NullPointerException
Try to get them like this
final EditText txtname=(EditText)v.findViewById(R.id.editText1);
final EditText txtnumber=(EditText)v.findViewById(R.id.editText2);

I think you are looking at the wrong place. Try using:
final View v = getLayoutInflater().inflate(R.layout.sample, null);
and than
final EditText txtname=(EditText)v.findViewById(R.id.editText1);
final EditText txtnumber=(EditText)v.findViewById(R.id.editText2);
to find the EditText at the "v" view.

Since you haven't provided the full code and a stack trace, I'm taking a wild guess, but I'm assuming it's correct:
You're fetching the edit texts using findViewById from the activity's content view and not from the inflated view.
Change:
findViewById(R.id.editText1);
findViewById(R.id.editText2);
to
v.findViewById(R.id.editText1);
v.findViewById(R.id.editText1);

you need to get the views from the dialod's layout
public void onClick(DialogInterface dialog,
int which) {
final EditText txtname=(EditText)dialog.findViewById(R.id.editText1);
final EditText txtnumber=(EditText)dialog.findViewById(R.id.editText2);
Save(txtname.getText().toString(),txtnumber.getText().toString());
}

please check the resource id it will also make cause for NPE.

findViewById is relative to the Activity. Your views are not in the activity, but rather in the dialog. You need to call
dialog.findViewById
from this scope.

Related

Get value of radio button in custom alert dialog

I have created a custom alertdialog with a radiogroup, radiobuttons, and edittext.
The goal is to trying to get the text value from the selected radiobutton and the edittext. At this point, I can only get the value entered in the edittext.
I have seen the following link and tried to adjust the code to adapt, but it seems that the code still doesn't work.
Android getting value from selected radiobutton
http://www.mkyong.com/android/android-radio-buttons-example/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="#+id/radioPersonGroup"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RadioButton
android:id="#+id/gButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_weight="1"
android:text="G" />
<RadioButton
android:id="#+id/kButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_weight="1"
android:text="K" />
</RadioGroup>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_weight="1"
android:ems="10"
android:hint="$10.00"
android:inputType="numberDecimal" />
</LinearLayout>
java file
private RadioButton radioSelectedButton;
...
FloatingActionButton fab = findViewById(R.id.fab);
final RadioGroup group = findViewById(R.id.radioPersonGroup);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
final View dialogView = getLayoutInflater().inflate(R.layout.custom_dialog, null);
builder.setTitle("Who Paid")
.setView(dialogView)
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int selectedId = group.getCheckedRadioButtonId();
radioSelectedButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MainActivity.this,
radioSelectedButton.getText(), Toast.LENGTH_SHORT).show();
EditText input = dialogView.findViewById(R.id.editText2);
Toast.makeText(MainActivity.this,input.getText().toString(), Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
When I click on either buttons followed by the Ok to submit the dialog the following exception occurs.
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.RadioGroup.getCheckedRadioButtonId()' on a null object reference
You're getting a NullPointerException in this line
int selectedId = group.getCheckedRadioButtonId();
because you tried to "find" the RadioGroup in the wrong View when you wrote
final RadioGroup group = findViewById(R.id.radioPersonGroup);
The RadioGroup is part of the Dialog, so you need to look for it in the View tree of dialogView:
// inside onClick()
final View dialogView = getLayoutInflater().inflate(R.layout.custom_dialog, null);
final RadioGroup group = dialogView.findViewById(R.id.radioPersonGroup);
Similarly, you need to "find" selectedRadioButton in a ViewGroup which contains it. e.g.
radioSelectedButton = (RadioButton) dialogView.findViewById(selectedId);
or
radioSelectedButton = (RadioButton) group.findViewById(selectedId);

how to add buttons that appear dynamically in a dialog using android studio

I have a dialog that shows an error message,
i know i can take that error message and just make it invisible, and visible in the code,
but then the Dialog would still save room in it and it will just show as a white space.
I want the error message to be added dynamical so if no error message will be shown the dialog will be sized accordingly.
how do i do that ?
here is my Dialog >
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:id="#+id/textContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:counterEnabled="true"
app:counterMaxLength="14">
<EditText
android:id="#+id/barcode_activity_input_editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:ems="10"
android:hint="Enter Serial Number"
android:inputType="number"
android:maxLength="14" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/barcode_activity_button_cancel"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/barcode_activity_manual_input_check_box"
android:text="Cancel" />
<Button
android:id="#+id/barcode_activity_button_ok"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_below="#+id/barcode_activity_manual_input_check_box"
android:layout_toEndOf="#+id/barcode_activity_button_cancel"
android:text="Ok" />
<TextView
android:id="#+id/barcode_activity_text_view_warning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textContainer"
android:layout_toRightOf="#+id/barcode_activity_image_view_warning"
android:paddingTop="5dp"
android:text="Serial doesn't match Workorder"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#f00000"
android:textSize="13dp" />
<ImageView
android:id="#+id/barcode_activity_image_view_warning"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_below="#+id/textContainer"
android:background="#drawable/warning" />
<CheckBox
android:id="#+id/barcode_activity_manual_input_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/barcode_activity_image_view_warning"
android:text="Allow Serial In Workorder"
android:textSize="13dp" />
</RelativeLayout>
and here is my main file >
inputFieldDialog = new Dialog(this); // CASTING
//inputFieldDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
inputFieldDialog.setContentView(R.layout.aligment_manager_manual_input_layout); // INFLATING VIEW
Button cancelInputButton, confirmInputButton; //declaring BOXES
final EditText inputField;
TextView warningTextView;
ImageView warningImageView;
CheckBox warningCheckBox;
cancelInputButton = (Button) inputFieldDialog.findViewById(R.id.barcode_activity_button_cancel); //casting
confirmInputButton = (Button) inputFieldDialog.findViewById(R.id.barcode_activity_button_ok); //casting
inputField = (EditText) inputFieldDialog.findViewById(R.id.barcode_activity_input_editText); //casting
warningTextView = (TextView) inputFieldDialog.findViewById(R.id.barcode_activity_text_view_warning); //casting
warningImageView = (ImageView) inputFieldDialog.findViewById(R.id.barcode_activity_image_view_warning); //casting
warningCheckBox = (CheckBox) inputFieldDialog.findViewById(R.id.barcode_activity_manual_input_check_box); //casting
warningTextView.setVisibility(TextView.INVISIBLE); //sets warnings invisible
warningImageView.setVisibility(ImageView.INVISIBLE); //sets warnings invisible
warningCheckBox.setVisibility(CheckBox.INVISIBLE); //sets warnings invisible
cancelInputButton.setOnClickListener(new View.OnClickListener() { //listeners for the buttons
#Override
public void onClick(View v) {
inputFieldDialog.hide();
}
});
confirmInputButton.setOnClickListener(new View.OnClickListener() { //listeners for the buttons
#Override
public void onClick(View v) {
scanResults = String.valueOf(inputField.getText());
scanBarcodeText.setText(inputField.getText());
editor.putString("boxID", String.valueOf(inputField.getText())); //saves the data as antenaNamein shared prefrences
editor.commit();
if (checkIfIdMatched(String.valueOf(inputField.getText())) == true) { //checkks if id is maching the one in the workorder
aligmentManagerClass.scanFromBarcodeApproved(); //ID MACHED
if (mainDialog != null) {
mainDialog.show();
}
loaderScreenMainText.setText("initlizing WiFi");//shows the user on screen message
wifiWrapper myWifiWrapper = new wifiWrapper(); //- INIZILIZING WIFI
myWifiWrapper.checkWifiState(getApplication(), callbackFunctionForisWifiOn);
} else {
loaderScreenMainText.setText("Scan Doesn't Match Data In Workoder"); // notify onScreen User
if (mainDialog != null) { // hides the loading dialog
mainDialog.hide();
}
AlertDialog wrongNumberDialog = getAlertDialogForWrongId(); //shows to user alert dialog for Wrong Number
wrongNumberDialog.show(); // show it
}
}
For remove white space...
Use "View.GONE" property of setVisibility() method rather than "TextView.INVISIBLE".
Set below code for hide views
warningTextView.setVisibility(View.GONE);
warningImageView.setVisibility(View.GONE);
warningCheckBox.setVisibility(View.GONE);
And for visible view just user
warningTextView.setVisibility(View.VISIBLE);
warningImageView.setVisibility(View.VISIBLE);
warningCheckBox.setVisibility(View.VISIBLE);
You can add buttons dynamically by creating buttons in Java file
Add this XML to dialog like dialog.addView(...)
Then Create Dynamically Buttons by according to values like
for(){
Create Buttons and add to above layout
layout.addView(button);
}
Hope it will help.

AlertDialog Builder Control Access

I have a Custom AlertDialog.Builder but I couldn't reach the EditText.
This is my DEFAULT Class;
AlertDialog.Builder Builder = new AlertDialog.Builder(this);
LayoutInflater Inflater = this.getLayoutInflater();
View AddCategory = Inflater.inflate(R.layout.category_new, null);
final EditText etCategoryName = (EditText) AddCategory.findViewById(R.id.btnAddCategory);
Builder.setView(AddCategory)
.setTitle("Add Category")
.setPositiveButton("ADD", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Time Today = new Time(Time.getCurrentTimezone());
Today.setToNow();
//This code has error !...
String CategoryName = etCategoryName.getText().toString();
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
Builder.show();
This
String CategoryName = etCategoryName.getText().toString();
This is my Costum AlertDialog layout;
<?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="60dp" >
<TextView
android:id="#+id/tvAddCategoryName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:text="#string/AddCategoryName"
android:textColor="#color/White"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/etAddCategoryName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvAddCategoryName"
android:layout_alignBottom="#+id/tvAddCategoryName"
android:layout_toRightOf="#+id/tvAddCategoryName"
android:layout_marginLeft="20dp"
android:hint="#string/CategoryName"
android:ems="10" >
<requestFocus />
</EditText>
Please help me ...
try this.
final EditText etCategoryName = (EditText) AddCategory.findViewById(R.id.etAddCategoryName);
In Your xml file your editText id is etAddCategoryName and in your java file you initialize different name (btnAddCategory).
So please change btnAddCategory to etAddCategoryName .
The Problem is occurred because you are passing button id instead of edittext id
Please Write below line of code
final EditText etCategoryName = (EditText) AddCategory.findViewById(R.id.etAddCategoryName);
instead of
final EditText etCategoryName = (EditText) AddCategory.findViewById(R.id.btnAddCategory);
If Seems like you mistyped the EditText id, you put R.id.btnAddCategory and seems like it should be R.id.etAddCategoryName.

Add dynamically input text and buttons in activity android

I have an application with an input text where the users have to insert an information and a button "+" beside to input text.
I would like to make my form dynamic in a way that when a user pushes on "+" button appears dynamically another text input and another "+" button beside this one, the process is repeated in the same way.
I created and xml file, sample_content:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/attempt"
android:layout_alignParentBottom="true"
android:text="TextView" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="36dp"
android:layout_height="32dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="22dp"
android:text="+" />
<EditText
android:layout_width="229dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="14dp"
android:layout_toLeftOf="#+id/addKey"
android:background="#drawable/inputtext_corner"
android:ems="10"
android:textSize="18sp" >
<requestFocus />
</EditText>
</RelativeLayout>
and in my Activity, AddDeviceActivity I put:
inflater = LayoutInflater.from(AddDeviceActivity.this);
Button addKey = (Button) findViewById(R.id.addKey);
addKey.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
final RelativeLayout canvas = (RelativeLayout) AddDeviceActivity.this.findViewById(R.id.my_canvas);
final View childView = inflater.inflate(R.layout.sample_component, canvas, false);
// TODO: Look up the 5 different signatures of the addView method,
// and pick that best fits your needs
canvas.addView(childView);
}
});
But this solution doesn't work because when I add the first input text and the first button, I don't know how to make the second button work in my AddDeviceActivity dynamicly
Just wondering whether you can do this:
Have your activity implement OnClickListener and add this method to your activity:
public void onClick(View v) {
final RelativeLayout canvas = (RelativeLayout) AddDeviceActivity.this.findViewById(R.id.my_canvas);
final View childView = inflater.inflate(R.layout.sample_component, canvas, false);
canvas.addView(childView);
((Button)childView.findViewById(R.id.addKey)).setOnClickListener(AddDeviceActivity.this);
}
And then change your initial code to use
addKey.setOnClickListener(this);
instead of an anonymous inner class.
I haven't tested this, but don't see why it wouldn't work.
check out this, pass null instead of canvas object in inflate() method
addKey.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
final RelativeLayout canvas = (RelativeLayout) AddDeviceActivity.this.findViewById(R.id.my_canvas);
final View childView = inflater.inflate(R.layout.sample_component, null, false);
// TODO: Look up the 5 different signatures of the addView method,
// and pick that best fits your needs
canvas.addView(childView);
}
});

Trying to Read Edit box inside Custom Dialog... Getting FC

I am trying to read a EditText box and send its contents to another method from within a Custom dialog box. My current code causes a Force Close. The logcat is very vague... however I know the uncaught exception takes place in this method:
public void getName(){
Dialog dialog = new Dialog(main.this);
dialog.setContentView(R.layout.customdialog);
dialog.setTitle("New Game");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!
final EditText inputBox = new EditText(this);
//set up text
final TextView text = (TextView) dialog.findViewById(R.id.TextView01);
text.setText("Enter Your Name...");
//set up button
final Button button = (Button) dialog.findViewById(R.id.namebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String str = inputBox.getText().toString();
setName(str);
}
});
//now that the dialog is set up, it's time to show it
dialog.show();
}
Here is the custom XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/linearLayout1">
<TextView android:text="#+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/nameprompt"></TextView>
<EditText android:layout_width="fill_parent" android:id="#+id/editText1" android:layout_height="wrap_content" android:inputType="textPersonName" android:text="Player">
<requestFocus></requestFocus>
</EditText>
<Button android:layout_height="wrap_content" android:id="#+id/namebutton" android:text="Ok" android:layout_width="fill_parent"></Button>
</LinearLayout>
</RelativeLayout>
Any ideas???
You have the EditText in your XML for the Dialog's layout... and you're properly using findViewById() to instantiate your TextView...
You need to do the same for the EditText, also use findViewById() to instantiate it.
final EditText inputBox = (EditText) dialog.findViewById(R.id.editText1);
Something is up with the inputBox object. You create it in this method, but I don't see you actually adding to the layout anywhere. When this method completes, you'll be displaying the dialog box, but the input box won't be displayed anywhere. In fact, I think that inputBox might be garbage collected since there are not references to if around after the getName() method completes. Therefore when you call get input on it, it might be null.
I think what you meant to do was this:
final EditText inputBox = (EditText)dialog.findViewById(R.id.editText1)

Categories

Resources