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?
Related
This is what the main screen of my app is supposed to look like I have that down I just have to figure out animations but the problem is I can't get the app to open because it crashes and I can't figure out what is causing my crash I used views for the lines at the top and just a regular android background change in the xml code for the mountain picture wondering if any of that might be the problem here is the xml code:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mountains"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/nz"
tools:context=".MainActivity">
<TextView
android:id="#+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/baloo_thambi"
android:text="NZ"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textColor="#color/white"
android:textSize="120sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/purple_medium"
android:layout_width="17dp"
android:layout_height="155dp"
android:layout_marginEnd="54dp"
android:background="#drawable/purple_gradient"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/green"
android:layout_width="17dp"
android:layout_height="235dp"
android:layout_marginEnd="13dp"
android:background="#drawable/green_gradient"
app:layout_constraintEnd_toStartOf="#+id/purple_medium"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/orange_long"
android:layout_width="17dp"
android:layout_height="215dp"
android:layout_marginEnd="13dp"
android:background="#drawable/orange_gradient"
app:layout_constraintEnd_toStartOf="#+id/green"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/purple_long"
android:layout_width="17dp"
android:layout_height="265dp"
android:layout_marginEnd="13dp"
android:background="#drawable/purple_gradient"
app:layout_constraintEnd_toStartOf="#+id/orange_long"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/orange_short"
android:layout_width="17dp"
android:layout_height="110dp"
android:layout_marginEnd="13dp"
android:background="#drawable/orange_gradient"
app:layout_constraintEnd_toStartOf="#+id/purple_long"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/purple_short"
android:layout_width="17dp"
android:layout_height="60dp"
android:layout_marginEnd="13dp"
android:background="#drawable/purple_gradient"
app:layout_constraintEnd_toStartOf="#+id/orange_short"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/subText"
android:layout_width="84dp"
android:layout_height="31dp"
android:layout_marginEnd="164dp"
android:layout_marginBottom="66dp"
android:fontFamily="#font/allura"
android:text="Next NZ"
android:textColor="#android:color/darker_gray"
android:textSize="22sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Whenever I try to check out what the problem in the logcat is this is what it tells me:
2022-02-14 12:26:47.614 20077-20077/com.revolution.covidnz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.revolution.covidnz, PID: 20077
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.revolution.covidnz/com.revolution.covidnz.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
at com.revolution.covidnz.MainActivity.<init>(MainActivity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Im also going to include the main activity code in case something in my code is making the app crash:
public class MainActivity extends AppCompatActivity {
private final int SPLASH_DISPLAY_LENGTH = 2000;
Animation slide_down = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.slide_down);
Animation slide_up = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.slide_up);
View gSlideDown, gSlideUp;
View pShortSlideDown, pShortSlideUp;
View pMediumSlideDown, pMediumSlideUp;
View pLongSlideDown, pLongSlideUp;
View oShortSlideDown, oShortSlideUp;
View oLongSlideDown, oLongSlideUp;
TextView textView, textView2;
RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView2 = findViewById(R.id.subText);
gSlideDown = findViewById(R.id.green);
gSlideUp = findViewById(R.id.green);
pShortSlideDown = findViewById(R.id.purple_short);
pShortSlideUp = findViewById(R.id.purple_short);
pMediumSlideDown = findViewById(R.id.purple_medium);
pMediumSlideUp = findViewById(R.id.purple_medium);
pLongSlideDown = findViewById(R.id.purple_long);
pLongSlideUp = findViewById(R.id.purple_long);
oShortSlideDown = findViewById(R.id.orange_short);
oShortSlideUp = findViewById(R.id.orange_short);
oLongSlideDown = findViewById(R.id.orange_long);
oLongSlideUp = findViewById(R.id.orange_long);
relativeLayout = findViewById(R.id.mountains);
final ViewGroup transitionsContainer = (ViewGroup) findViewById(R.id.transition_position);
final TextView text = (TextView) transitionsContainer.findViewById(R.id.text);
gSlideUp.setOnClickListener(new View.OnClickListener() {
boolean visible;
#Override
public void onClick(View v) {
TransitionManager.beginDelayedTransition(transitionsContainer);
visible = !visible;
text.setVisibility(visible ? View.VISIBLE : View.GONE);
}
});
gSlideUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.START);
TransitionManager.beginDelayedTransition(relativeLayout, slide);
textView.setVisibility(View.VISIBLE);
}
});
gSlideUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.END);
TransitionManager.beginDelayedTransition(relativeLayout, slide);
gSlideDown.setVisibility(View.VISIBLE);
}
});
final android.os.Handler handler = new android.os.Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, Second.class);
startActivity(intent);
overridePendingTransition(R.transition.fade_in,R.transition.fade_out);
}
}, 3000);
}
}
See context can be of anything, so if you want the context of activity then use ActivityName.context, other the context you receive may not be of the activity.
One tip: Please study before making apps directly. A programmer is one who reads the documentation and creates apps.
So as you error states, you are trying to invoke getContext() on views/properties that are still null or have not been even created and that is what is happening here. You are trying to access the views and pass them the context even before they are created.
All the views are created during the onCreate method call and you can use them inside this method or after this method has been executed.
So try passing in the context to the views inside a meaningful method where your views are not null
For ref read the activity lifecycle: https://developer.android.com/guide/components/activities/activity-lifecycle
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)'
}
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());
}
}
}
);
}