Hi I'm new to android programming and am running into a frustrating bug. I'm trying to get the value from an edittext and put it into an object. My code will print the value into Log.v but throws a NullPointerException when I try to use mEdit.getText().toString() in my setter method. Here's the code:
Button mButton;
EditText mEdit;
WorkoutTop workoutTop;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_workout);
mButton = (Button) findViewById(R.id.addButton);
mEdit = (EditText) findViewById(R.id.addEditText);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("This works: ", mEdit.getText().toString());
workoutTop.setName(mEdit.getText().toString());
Log.v("Never gets here:", workoutTop.getName());
}
}
}
);
}
The xml:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context="eric.hork.AddWorkout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/addEditText"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/addButton"
android:layout_below="#+id/addEditText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
and the Class I'm trying to use:
package eric.hork.Workout;
import java.util.ArrayList;
/**
* Created by eric on 4/29/15.
*/
public class WorkoutTop {
private String name;
private ArrayList<WorkoutDay> workoutDays;
public String getName(){
return name;
}
public void setName(String workoutName){
name = workoutName;
}
public ArrayList<WorkoutDay> getWorkoutDays(){
return workoutDays;
}
public Boolean addWorkoutDay(WorkoutDay workoutDay){
return workoutDays.add(workoutDay);
}
}
The error occurs in this line:
workoutTop.setName(mEdit.getText().toString());
Here's the log:
04-29 16:22:37.131 20937-20937/eric.hork E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: eric.hork, PID: 20937
java.lang.NullPointerException: Attempt to invoke virtual method 'void eric.hork.Workout.WorkoutTop.setName(java.lang.String)' on a null object reference
at eric.hork.AddWorkout$1.onClick(AddWorkout.java:35)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20926)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Thanks for any help!
You have to initialize workoutTop variable.
workoutTop = new WorkoutTop();
Within your onCreate Method you must initialize workoutTop.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_workout);
workoutTop = new WorkoutTop(); //add this
mButton = (Button) findViewById(R.id.addButton);
mEdit = (EditText) findViewById(R.id.addEditText);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("This works: ", mEdit.getText().toString());
workoutTop.setName(mEdit.getText().toString());
Log.v("Never gets here:", workoutTop.getName());
}
}
}
);
}
Related
First of all I'm very new with coding just trying and also new with the features of Firebase. The problem is that, I'm trying to get specific value from firebase by putting number associated with the value. As I have designed it as my first activity (Buffer2) to put the serial number with EditText and thus pass the value from this activity to next activity (Buffer3). and assigned this intent.getExtra string and then making this as int to put the serial number. But the process getting crash (or stopped as to saying it null).
Is there, another way to get this done? any help will be appreciated.
Here is my code (xml and java) for buffer2 and buffer3
buffer2 xml----------------------------
<LinearLayout
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Buffer2">
<LinearLayout
android:layout_gravity="center"
android:gravity="center"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/etGo"
android:hint="Go To Page No"
android:inputType="number"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnGo"
android:text="Go"
android:textStyle="bold"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
Buffer2 java---------------------------------------
public class Buffer2 extends AppCompatActivity {
Button BtnGo;
EditText EtGo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buffer2);
BtnGo=findViewById(R.id.btnGo);
EtGo=findViewById(R.id.etGo);
String number = Buffer2.this.EtGo.getText().toString();
BtnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Buffer2.this, Buffer3.class);
intent.putExtra("numberto", number);
startActivity(intent);
}
});
}
}
buffer3 xml-------------------------------
<LinearLayout
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Buffer3">
<TextView
android:id="#+id/nameTv"
android:textSize="28sp"
android:gravity="center"
android:text="Loading..."
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"/>
<TextView
android:id="#+id/professionTv"
android:textSize="28sp"
android:gravity="center"
android:text="Loading..."
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"/>
</LinearLayout>
Buffer3 java------------------------------
public class Buffer3 extends AppCompatActivity {
TextView Name, Profession;
DatabaseReference reference;
String Number = getIntent().getStringExtra("numberto");
int count = Integer.parseInt(String.valueOf(Number));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buffer3);
Name = findViewById(R.id.nameTv);
Profession = findViewById(R.id.professionTv);
reference=FirebaseDatabase.getInstance().getReference().child("What")
.child(String.valueOf(count));
}
protected void onStart() {
super.onStart();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
String type = dataSnapshot.child("type").getValue().toString();
Name.setText(name);
Profession.setText(type);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Logcat------------------------
2020-04-22 18:39:48.939 11231-11231/com.potato.manpower I/Timeline: Timeline: Activity_launch_request time:419024820 intent:Intent { cmp=com.potato.manpower/.Buffer3 (has extras) }
2020-04-22 18:39:48.969 11231-11231/com.potato.manpower D/AndroidRuntime: Shutting down VM
2020-04-22 18:39:48.970 11231-11231/com.potato.manpower E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.potato.manpower, PID: 11231
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.potato.manpower/com.potato.manpower.Buffer3}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2649)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2808)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
at com.potato.manpower.Buffer3.<init>(Buffer3.java:17)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2639)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2808)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)
2020-04-22 18:39:48.999 11231-11231/com.potato.manpower I/Process: Sending signal. PID: 11231 SIG: 9
Firebase Structure
enter image description here
It looks like getIntent() returns null in this line:
String Number = getIntent().getStringExtra("numberto");
I expect that problem will disappear if you move the initialization of Number into the onCreate method:
public class Buffer3 extends AppCompatActivity {
TextView Name, Profession;
DatabaseReference reference;
String Number;
int count = Integer.parseInt(String.valueOf(Number));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buffer3);
Number = getIntent().getStringExtra("numberto");
Name = findViewById(R.id.nameTv);
Profession = findViewById(R.id.professionTv);
reference=FirebaseDatabase.getInstance().getReference().child("What")
.child(String.valueOf(count));
}
...
A few other notes:
It is idiomatic to have the names of member fields start with lowercase letters, so number instead of Number.
When you get a NullPointerException, follow the advice from this post to learn how to troubleshoot it yourself: What is a NullPointerException, and how do I fix it?
I have two methods defined inside this class:
RegisterButtonClicked successfully calls an activity, but LoginButtonClicked won't....
The result of running this code is that it prints out "inside LoginButtonClicked2" log message which means the code is running the LoginButtonClicked method but not successfully executing the startActivity inside the method.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void RegisterButtonClicked(View view) {
Log.d("registerButtonClicked", "inside registerButtonClicked");
Button Register = findViewById(R.id.RegisterButton);
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, Register.class));
}
});
}
public void LoginButtonClicked(View view) {
Log.d("LoginButtonClicked", "inside LoginButtonClicked");
Button login = findViewById(R.id.LoginButton);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("LoginButtonClicked", "inside LoginButtonClicked2");
startActivity(new Intent(MainActivity.this, Login2.class));
}
});
}
}
here is my activity_main.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/RegisterButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="191dp"
android:layout_marginStart="134dp"
android:layout_marginLeft="134dp"
android:text="Register"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="266dp"
android:onClick = "RegisterButtonClicked"/>
<Button
android:id="#+id/LoginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="150dp"
android:layout_marginStart="134dp"
android:layout_marginLeft="134dp"
android:text="Log in"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="200dp"
android:onClick = "LoginButtonClicked"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginStart="107dp"
android:layout_marginLeft="107dp"
android:text="Welcome to Pick Rose!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</RelativeLayout>
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pickrose3, PID: 8252
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pickrose3/com.pickrose3.Login2}: java.lang.IllegalArgumentException: Given String is empty or null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.Preconditions.checkNotEmpty(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(com.google.firebase:firebase-auth##19.0.0:202)
at com.pickrose3.Login2.onCreate(Login2.java:60)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
You may change your java code as below (consider it as one of the possible ways to solve this, please!):
public class MainActivity extends AppCompatActivity {
public void RegisterButtonClicked(View RegisterButtonClicked) {
startActivity(new Intent(MainActivity.this, Register.class));
}
public void LoginButtonClicked(View LoginButtonClicked) {
startActivity(new Intent(MainActivity.this, Login2.class));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
If your are setting click from xml then dont need to set click listener in code.
public void RegisterButtonClicked(View view) {
Log.d("registerButtonClicked", "inside registerButtonClicked");
startActivity(new Intent(MainActivity.this, Register.class));
}
public void LoginButtonClicked(View view) {
Log.d("LoginButtonClicked", "inside LoginButtonClicked");
startActivity(new Intent(MainActivity.this, Login2.class));
}
This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 4 years ago.
this is my android code when we run application and it is automatically close when login method is call on the clicking of the button
FATAL EXCEPTION: main Process: soubhagya.hostinger, PID: 25611
java.lang.IllegalStateException: Could not execute method for
android:onClick at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5640)
at android.view.View$PerformClick.run(View.java:22455)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6165)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5640)
at android.view.View$PerformClick.run(View.java:22455)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6165)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.text.Editable android.widget.EditText.getText()' on a
null object reference
at soubhagya.hostinger.Login.logIn(Login.java:51)
at soubhagya.hostinger.Login.radhaJi(Login.java:106)
at java.lang.reflect.Method.invoke(Native Method)
at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5640)
at android.view.View$PerformClick.run(View.java:22455)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6165)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Here's the Login activity.
public class Login extends AppCompatActivity {
//web url string
public static final String LOGIN_URL="http://abhinavin.000webhostapp.com/userregistration/login.php";
public static final String KEY_EMAIL="email";
public static final String KEY_PASSWORD="password";
public static final String LOGIN_SUCCESS="success";
public static final String SHARED_PREF_NAME="tech";
public static final String EMAIL_SHARED_PREF ="email";
public static final String LOGGEDIN_SHARED_PREF="loggedin";
private EditText editTextEmail;
private EditText editTextPassword;
private Button btn_SignIn;
private boolean loggedIn=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//this is text fields
editTextEmail=findViewById(R.id.email);
editTextPassword=findViewById(R.id.password);
btn_SignIn=findViewById(R.id.btn_signup);
}
//End of onCreate method
this login method is call on the click of button
private void logIn() {
//error is in this line i think.
//get value of email from edit text
final String email = editTextEmail.getText().toString();
//get value of password from edit text
final String password = editTextPassword.getText().toString();
StringRequest stringRequest=new StringRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<String>() {
//override the onResponse method
#Override
public void onResponse(String response) {
//check condition
if (response.trim().equalsIgnoreCase(LOGIN_SUCCESS)) {
SharedPreferences sharedPreferences = Login.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putBoolean(EMAIL_SHARED_PREF, Boolean.parseBoolean(email));
editor.commit();
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
} else {
Toast.makeText(Login.this, "Invalid password", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
//overridre getParams
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> prams=new HashMap<>();
//put the data in map
prams.put(KEY_EMAIL, email);
prams.put(KEY_PASSWORD,password);
//return prams
return prams;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
End of login method
//overtide the onResume method
#Override
protected void onResume() {
super.onResume();
//get SharedPreferences
SharedPreferences sharedPreferences=getSharedPreferences(SHARED_PREF_NAME,Context.MODE_PRIVATE);
loggedIn=sharedPreferences.getBoolean(LOGGEDIN_SHARED_PREF ,false);
if(loggedIn)
{
//set Intent object
Intent i=new Intent(Login.this, MainActivity.class);
//StartActivity
startActivity(i);
}
}
//this is onclick function
public void btn_Click(View view) {
//call login function
logIn();
}
}
xml code in this code edit text and button are defined
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="soubhagya.hostinger.Login">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editText3" android:hint="Emile"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/editText4" android:hint="Password"/>
<Button
android:text="Signin"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/button3"
android:onClick="btn_Click"
/></LinearLayout>
this is my xml code in whis we can design ui of our application
You should change to btn_Click in your xml
from android:onClick="radhaJi"
to android:onClick="btn_Click".
Your button initialize wrong id
btn_SignIn=findViewById(R.id.btn_signup);
should be
btn_SignIn=findViewById(R.id.button3);
You need implement the View.OnClickListener along with your Activity like the following.
public class Login extends AppCompatActivity implements View.OnClickListener {
#Override
public void onClick(View view) {
if(view.getId() == R.id.btn_signup)
logIn();
}
}
And change the layout to look like the following.
<?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:orientation="vertical">
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Emile"
android:inputType="textPersonName" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Password"
android:inputType="textPassword" />
<Button
android:id="#+id/btn_signup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Signin" />
</LinearLayout>
This question already has answers here:
findViewById returns null
(4 answers)
Closed 5 years ago.
I have a button in my XML that I'm retrieving in the onCreate method of the activity's java code. When I go to run the app, though, a null pointer exception is set off.
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<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"
android:orientation="vertical"
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.example.android.chargerpoints.LogonActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/email"
android:hint="#string/prompt_email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/password"
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"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sign_in_button"
style="?android:textAppearanceSmall"
android:layout_marginTop="16dp"
android:text="#string/action_sign_in"
android:textStyle="bold"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/register_button"
style="?android:textAppearanceSmall"
android:layout_marginTop="8dp"
android:text="#string/action_register"
android:textStyle="bold"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/forgot_password_button"
style="?android:textAppearanceSmall"
android:layout_marginTop="16dp"
android:text="Forgot Password"
android:textStyle="bold"/>
</LinearLayout>
The button in question is the one with the id "sign_in_button". This is the onCreate method in the java code:
private TextView emailTextView;
private TextView passwordTextView;
private Button signInButton;
private Button registerButton;
private Button forgotPasswordButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
realm = Realm.getDefaultInstance();
emailTextView = (TextView) findViewById(R.id.email);
passwordTextView = (TextView) findViewById(R.id.password);
signInButton = (Button) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(LogonActivity.this, signIn(),
Toast.LENGTH_LONG).show();
}
});
registerButton = (Button) findViewById(R.id.register_button);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(LogonActivity.this, register(),
Toast.LENGTH_LONG).show();
}
});
forgotPasswordButton = (Button) findViewById(R.id.forgot_password_button);
}
This is the error I'm getting:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.chargerpoints, PID: 7276
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.chargerpoints/com.example.android.chargerpoints.LogonActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.android.chargerpoints.LogonActivity.onCreate(LogonActivity.java:42)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
It would be amazing if someone could help me with this. I am a novice at this stuff and this issue has gotten me stuck and its probably just a small thing I missed. Thanks!
you need to inflate the layout inside the activity/fragment first.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<xml file name>);
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//without this line your activity class doesn't know which xml file you wanna use
setContentView(R.layout.yourlayoutname);
//and only after that you can retrive names
bnt = (Button) findViewById(R.id.btn)'
}
in the moment Iam playing arround with the RecyclerView. The whole time I get some NullPointer Exceptions but I can't find why.
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.lueth.erik.birthdays/de.lueth.erik.birthdays.TodaysBirthdays.TodaysBirthdaysActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5349)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at de.lueth.erik.birthdays.TodaysBirthdays.TodaysBirthdaysActivity.onCreate(TodaysBirthdaysActivity.java:23)
at android.app.Activity.performCreate(Activity.java:6020)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2284)...
Here is my TodaysBirthdaysActivity.class
The onCreate part looks like that one that Google is showing in their RecyclerView tutorial.
public class TodaysBirthdaysActivity extends Activity{
private RecyclerView recList;
private RecyclerView.Adapter adp;
private RecyclerView.LayoutManager llm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_birthday_list);
recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
llm = new LinearLayoutManager(this);
recList.setLayoutManager(llm);
adp = new Adapter(createList(30));
recList.setAdapter(adp);
}
private List<ContactInfo> createList(int size) {
List<ContactInfo> result = new ArrayList<ContactInfo>();
for (int i=1; i <= size; i++) {
ContactInfo ci = new ContactInfo();
ci.name = ContactInfo.NAME_PREFIX + i;
ci.surname = ContactInfo.SURNAME_PREFIX + i;
ci.birthday = ContactInfo.Birthday_PREFIX + i ;
result.add(ci);
}
return result;
}}
Here is my activity_birthday_list.xml
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".TodaysBirthdaysActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent"
/></RelativeLayout>
Here my Adapter.class
public class Adapter extends RecyclerView.Adapter<ContactViewHolder> {
private List<ContactInfo> contactList;
public Adapter(List<ContactInfo> contactList) {
this.contactList = contactList;
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) {
ContactInfo ci = contactList.get(i);
contactViewHolder.vName.setText(ci.name);
contactViewHolder.vSurname.setText(ci.surname);
contactViewHolder.vBirthday.setText(ci.birthday);
contactViewHolder.vTitle.setText(ci.name + " " + ci.surname);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.contact_card, viewGroup, false);
return new ContactViewHolder(itemView);
}}
here my ContactInfo.java
public class ContactInfo {
protected String name;
protected String surname;
protected String birthday;
protected static final String NAME_PREFIX = "Name_";
protected static final String SURNAME_PREFIX = "Surname_";
protected static final String Birthday_PREFIX = "Birthday_";}
and here my ContentViewHolder.java
public class ContactViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vSurname;
protected TextView vBirthday;
protected TextView vTitle;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vSurname = (TextView) v.findViewById(R.id.txtSurname);
vBirthday = (TextView) v.findViewById(R.id.txtBirthday);
vTitle = (TextView) v.findViewById(R.id.title);
}}
and the xml for the card contact_card.xml
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#color/cardview_dark_background"
android:text="contact det"
android:gravity="center_vertical"
android:textColor="#android:color/white"
android:textSize="14dp"/>
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/title"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"/>
<TextView
android:id="#+id/txtSurname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Surname"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/txtName"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"/>
<TextView
android:id="#+id/txtBirthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Birthday"
android:textSize="10dp"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="150dp"
android:layout_alignBaseline="#id/txtName"/>
</RelativeLayout> </android.support.v7.widget.CardView>
It's all in your logcat output:
at de.lueth.erik.birthdays.TodaysBirthdays.TodaysBirthdaysActivity.onCreate(TodaysBirthdaysActivity.java:23)
That line TodaysBirthdaysActivity.java:23 gives you NPE. Which means, your variable recList is null. Why? Most probably, because there is no object with id R.id.cardList inside layout R.layout.activity_birthday_list.