Null pointer Exception on .setOnClickListener - java

I am having an issue with a click listener for a login modal submit button.
This is the error.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I have a reasonable understanding of what a null pointer exception is and I have search thoroughly for an issue similar to mine. I have tried to reformat the click listener in several ways, made sure I have the correct view ID etc.
package...
import...
public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {
//Variables
String currentPage = "";
Stack<String> crumbs = new Stack<String>();
//Fragment managing the behaviors, interactions and presentation of the navigation drawer.
private NavigationDrawerFragment mNavigationDrawerFragment;
// Used to store the last screen title. For use in {#link #restoreActionBar()}.
public CharSequence mTitle;
//temp
AuthenticateUserTokenResult authenticateUserTokenResult;
String loginErrorMessage = "";
String loginErrorTitle = "";
Boolean logonSuccessful = false;
Dialog loginDialog;
// Login EditTexts
EditText Username;
EditText CompanyID;
EditText Password;
Button Submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle(); // Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
if(authenticateUserTokenResult == null) {
attemptLogin();
}
}
public void attemptLogin() {
loginDialog = new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
loginDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
loginDialog.setContentView(R.layout.login_modal);
loginDialog.setCancelable(false);
//loginDialog.setOnCancelListener(cancelListener);
loginDialog.show();
Submit = (Button)findViewById(R.id.Submit);
Submit.setOnClickListener(new View.OnClickListener() // the error is on this line (specifically the .setOnClickListener)
{
#Override
public void onClick(View v)
{
ClyxUserLogin user = new ClyxUserLogin();
Username = (EditText)findViewById(R.id.Username);
user.logon = Username.getText().toString();
CompanyID = (EditText)findViewById(R.id.CompanyID);
user.idCompany = Integer.parseInt(CompanyID.getText().toString());
Password = (EditText)findViewById(R.id.Password);
user.password = Password.getText().toString();
user.idApplication = 142;
authenticate(user);
}
});
}
There is more, obviously, but not relevant to the topic I think.
Here is the XML file for the dialog that has the button on it.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#3366FF">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#FFFFFF" >
<TextView
android:id="#+id/LoginTitle"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_marginStart="10dp"
android:textColor="#000000"
android:textSize="20sp"
android:text="Login" />
<EditText
android:id="#+id/Username"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/LoginTitle"
android:layout_margin="10dp"
android:hint="Username" />
<EditText
android:id="#+id/CompanyID"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/Username"
android:layout_alignStart="#+id/Username"
android:inputType="number"
android:hint="Company ID" />
<EditText
android:id="#+id/Password"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/CompanyID"
android:layout_alignStart="#+id/Username"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:inputType="textPassword"
android:hint="Password" />
<Button
android:id="#+id/Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Password"
android:layout_marginBottom="10dp"
android:layout_centerHorizontal="true"
android:text="Login" />
</RelativeLayout>
</RelativeLayout>
Any help would be greatly appreciated.

Submit is null because it is not part of activity_main.xml
When you call findViewById inside an Activity, it is going to look for a View inside your Activity's layout.
try this instead :
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Another thing : you use
android:layout_below="#+id/LoginTitle"
but what you want is probably
android:layout_below="#id/LoginTitle"
See this question about the difference between #id and #+id.

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
Because Submit button is inside login_modal so you need to use loginDialog view to access button:
Submit = (Button)loginDialog.findViewById(R.id.Submit);

Try giving your Button in your main.xml a more descriptive name such as:
<Button
android:id="#+id/buttonXYZ"
(use lowercase in your xml files, at least, the first letter)
And then in your MainActivity class, declare it as:
Button buttonXYZ;
In your onCreate(Bundle savedInstanceState) method, define it as:
buttonXYZ = (Button) findViewById(R.id.buttonXYZ);
Also, move the Buttons/TextViews outside and place them before the .setOnClickListener - it makes the code cleaner.
Username = (EditText)findViewById(R.id.Username);
CompanyID = (EditText)findViewById(R.id.CompanyID);

I too got similar error when i misplaced the code
text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
I got it working on placing the code in right order as shown below
setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});

Related

New Value EditText not being displayed , no errors whatsoever

EDIT : By the way , if i hard code edt4.setText("any text") IN THE SCOPE , it shows the value
EDIT2: tried rebuilding/cleaning project , could this be a bug in settext method, it looks like im doing it right . When i look at other code with settext
EDIT3: startactivityforresult might be my answer ? , i openend another question related to what i wanna try out , i still havent found another solution , stuck with this for a week now : (
this is the link to my question Can i use startActivityForResult , with one activity?
EDIT4 : now trying it with making views visible and invisible
I have read every single article about anything related on stackoverflow , dreamincode etc, and i cant find anybody that knows the answer for my problem.
I have a qr scanner and after a successful scan the result needs to be put in a EDIT TEXT field with name editText4 , my code throws no errors but it is NOT displaying any value .
I've posted on different forums but to no avail (https://www.dreamincode.net/forums/topic/412000-settext-is-not-showing-set-value-in-edittext-in-gui/page__st__15__gopid__2372214&#entry2372214)
, as you can see the commented code . That's pretty much also what I've tried , I think I somehow got to get my handle result method inside of the scope.
NOTE : Log.v outputs the result very well , but when i try anything else with the result it just don't works or being displayed
ps: I m beginner at java
Thanks for your help
here's my mainactivity
` public class MainActivity extends Activity implements
ZXingScannerView.ResultHandler {
Button sendButton;
EditText edt4;
EditText edt2;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt4 = findViewById(R.id.editText4);
mScannerView = findViewById(xmlScannerView);
mScannerView.setFormats(ZXingScannerView.ALL_FORMATS);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
EditText delete2;
Button button3;
button3 = findViewById(R.id.button3);
delete2 = findViewById(R.id.editText2);
final EditText finalEdittext = delete2;
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Clear EditText
finalEdittext.getText().clear();
}
});
EditText delete4;
Button button4;
delete4 = findViewById(editText4);
button4 = findViewById(R.id.button4);
final EditText finalEdittext1 = delete4;
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Clear EditText
finalEdittext1.getText().clear();
}
});
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
public void onClick(View v){
RelativeLayout someid = findViewById(R.id.someId);
mScannerView.setVisibility(View.VISIBLE);
someid.setVisibility(View.INVISIBLE);
}
// EditText edt4;
#Override
public void handleResult(final Result result) {
//handle result
Log.v("handleResult", result.getText());
edt4 = findViewById(editText4);
edt4.setText(result.getText());
//edt4.setText(String.valueOf(result.getText()));
// edt4.setText(new
StringBuilder().append("Resultaat:").append(result.getText()).toString());
}
`
this is xml :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:background="#mipmap/ic_launcher_foreground">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true">
<me.dm7.barcodescanner.zxing.ZXingScannerView
android:id="#+id/xmlScannerView"
android:visibility="gone"
android:layout_height="match_parent"
android:layout_width="match_parent" />
<RelativeLayout
android:id="#+id/someId"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/editText4"
android:layout_width="match_parent"
android:layout_height="62dp"
android:layout_marginTop="67dp"
android:ems="10"
android:hint="#string/scan_locatie"
android:inputType="text"
android:text=""
tools:backgroundTint="#android:color/holo_red_light" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText4"
android:layout_centerHorizontal="true"
android:background="#android:color/holo_red_light"
android:onClick="onClick"
android:text="#string/scan_qr"
tools:text="scan qr code" />
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="61dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="197dp"
android:ems="10"
android:hint="#string/scan_order"
android:inputType=""
android:visibility="visible"
tools:backgroundTint="#android:color/holo_red_light" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:background="#android:color/holo_red_light"
android:onClick="onClick"
android:text="#string/scan_qr"
tools:text="scan qr code" />
<Button
android:id="#+id/sendButton"
android:layout_width="157dp"
android:layout_height="32dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="72dp"
android:background="#android:color/holo_red_light"
android:text="#string/button"
tools:text="Versturen.." />
<Button
android:id="#+id/button3"
android:layout_width="40dp"
android:layout_height="38dp"
android:layout_alignBaseline="#+id/editText2"
android:layout_alignParentEnd="true"
android:background="#android:drawable/ic_delete" />
<Button
android:id="#+id/button4"
android:layout_width="39dp"
android:layout_height="37dp"
android:layout_alignBaseline="#+id/editText4"
android:layout_alignParentEnd="true"
android:background="#android:drawable/ic_delete" />
</RelativeLayout>
EDIT:5 also changed XML , and main , still not working :(
try removing recreate();
you are recreating the activity after setting the value, so the previous value is lost
I think result.getText() is a String anyway, so you could change the following line:
edt4.setText(String.valueOf(result.getText()));
To:
edt4.setText(result.getText());
After that you call updateScannerData, which is also writing to the EditText once again, but from the UI-Thread. I would recommend to remove the UI-Thread code as well since I assume the code runs on that Thread anyway.
You can either use
edt4.clear();
or
edt4.setText("");

Button is not reacting to click

I created a simple activity that is intended to send two pieces of information to another activity. However, my button isn't registering any click events. Does anyone have any idea why this would be? I expected that by adding the onClick = "onClickWrite" to the XML file that they would be linked but there is no response when clicked. If anyone could help me out, I would greatly appreciate it. I have tried implementing the onClickListener, however, with that implementation, it throws an error on my Toasts.
Activity
public class InitializeClass extends Activity {
private Service service;
private Button button;
EditText infoOne;
EditText infoTwo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button_control);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(clicked);
infoOne= (EditText) findViewById(R.id.editText);
infoTwo= (EditText) findViewById(R.id.editText1);
}
private View.OnClickListener clicked = new View.OnClickListener(){
#Override
public void onClick(View view) {
if (service != null) {
int size = 100;
byte[] byteArray = new byte[size];
byte[] byteArrayTwo = new byte[size];
byteArray = infoOne.getText().toString().getBytes(Charset.defaultCharset());
byteArrayTwo= infoTwo.getText().toString().getBytes(Charset.defaultCharset());
if ((!(infoOne.getText().toString().isEmpty())) && (!(infoTwo.getText().toString().isEmpty()))) {
service.setInfo(byteArray);
service.setInfoTwo(byteArrayTwo);
intentMethod();
}
}
}
};
public void intentMethod() {
Intent intent = new Intent(this, DeviceScanActivity.class);
startActivity(intent);
}
}
XML:
<?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"
tools:context=".InitializeClass">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="#string/send_info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColor="#color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText1" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="150dp"
android:ems="10"
android:inputType="textPersonName"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColorHint="#android:color/white"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColorHint="#android:color/white"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText" />
</android.support.constraint.ConstraintLayout>
You need to initialize your button first.
Button button = (Button) findViewById(R.id.button);
Hope this helps!
In your activity class assign the button to the id of the button in the xml:
private Button btn = findViewById(R.id.button);
You will then create an OnClickListener:
private View.OnClickListener clicked = new View.OnClickListener(){
#Override
public void onClick(View view) {
//Insert Code here
}
};
In your onCreate method in the same activity class you will instantiate the button and assign the button to the onClickListener:
btn = new Button(this);
btn.setOnClickListener(clicked);
There are couple of things you need to do for that.
Create Field.
private Button button;
Initialize button.
Button button = (Button) findViewById(R.id.button);
Set Listener on button.
button.setOnClickListener();
I found the answer. Service in if (service != null) was never being initialized. Stupid mistake on my part. Thanks, everyone for the help and directing me in a way to implement onClickListener!
You need to cast the button (name) with you Java code .
for example on xml you have id/button (name)
declare it on your Java file, and do the casting.
and the onClickListener will look like this :
Cast the button : Button button ;
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});

Need help in debugging of specific weird issue of null object reference error on an EditText object Android [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm aware about general case of java.lang.NullPointerException, but need help in debugging of this specific case. Please look: I have connected my layout editText with my Java class EditText but still gets an error while trying to get the text from the text field.
I still see this error:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.text.Editable android.widget.EditText.getText()' on a null object
reference
and here is my code.
at com.ramadanapps.android.fireapp.Register.createUser(Register.java:56)
package com.ramadanapps.android.fireapp;
public class Register extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText mEmail;
private EditText mPassword;
private Button mRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mEmail = (EditText) findViewById(R.id.signUpEmail);
mPassword = (EditText) findViewById(R.id.singUpPassword);
mRegister = (Button) findViewById(R.id.signUpBtn);
mAuth = FirebaseAuth.getInstance();
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createUser();
}
});
}
#Override
public void onStart(){
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null){
Toast.makeText(Register.this,"Already signed in", Toast.LENGTH_LONG).show();
}
}
private void createUser() {
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(Register.this,"Successful", Toast.LENGTH_LONG).show();
startActivity(new Intent(Register.this, MainActivity.class ));
} else{
Toast.makeText(Register.this,"Failure", Toast.LENGTH_LONG).show();
}
}
});
}
[![enter image description here][1]][1]}
I don't know where is the problem.
Here is my XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.ramadanapps.android.fireapp.Register">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/signUpEmail"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="32dp"
android:hint="Email" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/singUpPassword"
android:layout_below="#+id/signUpEmail"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:hint="Password" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign Up"
android:id="#+id/signUpBtn"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign Up"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="25dp" />
</RelativeLayout>
The xml has the id signUpEmail and I don't still know where the problem is.
I installed your code on my side with only 2 differences:
1. I use my own firebase DB
2. My MainActivity is different - actually I created empty one just for testing.
The app works fine - I successfully signed-up several times with diffeent (fake) mails and passwords. Everytime I was passed to main activity, and when pressed "back" - successfully moved back to Register activity. (snapshot attached).
No failures so far.
When I failed - it is when tried to sign-up on empty fields of mail or password - it's expected, you need validate the form.
Other possible reason of failure that comes in my mind - is in your main activity. May be there in onStart or onCreate methods you refer to non-defined TextViews? Would you like to share it with corresponding XML?
Thanks and good luck! ))

Pass data from dialog to activity Android

I have problem.
I made method which creates Dialog with my own layout. And I have no idea how to pass values (Strings) from my EdiText and asing to any variable in my Activity.
In comments you can see how I was trying to solve this.
Java method
public void makeDialog(){
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_ip);
dialog.setTitle("IP connection");
// Todo passing value from dialog to activity
// final EditText ipValueConnection = (EditText)findViewById(R.id.ipValueConnection);
// ipValueConnection.setOnClickListener(this);
// EditText portValueConnection = (EditText)findViewById(R.id.portValueConnection);
// Toast.makeText(context, ipValueConnection.getText().toString(), Toast.LENGTH_LONG).show();
Button dialogButtonLogin = (Button) dialog.findViewById(R.id.dialogButtonLogin);
// if button is clicked, close the custom dialog
dialogButtonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryToConnect();
dialog.dismiss();
}
});
// set the custom dialog components - text, image and button
// TextView text = (TextView) dialog.findViewById(R.id.IP);
dialog.show();
}
XML layout
<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:src="#drawable/antena"
android:layout_width="220dp"
android:layout_height="120dp"
android:scaleType="centerInside"
android:background="#FFFFBB33"
android:contentDescription="#string/app_name"
android:adjustViewBounds="true"
/>
<EditText
android:id="#+id/ipValueConnection"
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="IP" />
<EditText
android:id="#+id/portValueConnection"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif"
android:hint="PORT"/>
<Button
android:id="#+id/dialogButtonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_marginTop="5dp"
/>
</LinearLayout>
Create a interface
public interface OnClickInterface {
public void onClick();
}
call it instantiate it in your activity onCreate()
OnClickInterface onClickInterface = new OnClickInterface() {
#Override
public void onClick() {
//Call Method from here
requiredMethod();
}
};
//And in your dialog classs or method
public void makeDialog(OnClickInterface onClickInterface){
//Your code
dialogButtonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClickInterface.onClick();
dialog.dismiss();
}
});
}
The error you are getting means that a reference to the editText cannot be found in the current layout file. You have find the EditText in the custom dialog view instead of the activity view.
So instead of:
final EditText ipValueConnection =(EditText)findViewById(R.id.ipValueConnection);
use:
final EditText ipValueConnection =(EditText)dialog.findViewById(R.id.ipValueConnection);
If i have understood your question correctly,
your edit text is in dialog_ip so you need to use
final EditText ipValueConnection = (EditText) dialog.findViewById(R.id.ipValueConnection);
Then you can get text from edit text as
String text= ipValueConnection.getText().toString;
And use that variable in your activity.

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

All I want to do is start a new intent on click of a button. Here is my code(I have removed irrelevant parts):
activity_login.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
tools:context="com.example.android.altro.LoginActivity">
<!-- Login progress -->
<ProgressBar
android:id="#+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:textColor="#color/colorWhite"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/email_sign_up_button"
style="?android:textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/rounded_button"
android:onClick="registerNewUser"
android:text="#string/action_sign_up"
android:textAllCaps="false" />
</LinearLayout>
</ScrollView>
</LinearLayout>
On clicking #+id/email_sign_up_button registerNewUser is called. I have defined this fuction in LoginActivity.java:
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo#example.com:hello", "bar#example.com:world"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
/* Button mRegisterButton = (Button) findViewById(R.id.email_sign_up_button);
mRegisterButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), RegisterActivity.class);
startActivity(intent);
}
});*/
}
public void registerNewUser(View view) {
Intent intent = new Intent(this, RegisterActivity.class);
startActivity(intent);
}
}
I also tried doing it by finding view and then creating an intent (the code is commented out in onCreate() method. That also gave me the same error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.altro/com.example.android.altro.RegisterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
You have only one Button with id email_sign_up_button
Please check your layout. Also try replacing
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
With
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_up_button);

Categories

Resources