My app is crashing while switching from the after login activity to the in app´s profile activity.
Build is complete without errors.
Any ideas why? (Thankful for every Help)
//////////////////////////////////////////////////////////////////////////
ProfileActivity ---->
package com.smarthelp.smarthelp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import com.google.firebase.auth.FirebaseAuth;
public class ProfileActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
firebaseAuth= FirebaseAuth.getInstance();
logout = (Button)findViewById(R.id.btnLogout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Logout();
}
});
configureibtnHelp();
}
private void Logout(){
firebaseAuth.signOut();
finish();
startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
}
private void configureibtnHelp() {
ImageButton ibtnHelp = (ImageButton) findViewById(R.id.ibtnHelp);
ibtnHelp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.profile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.logoutMenu:{
Logout();
}
}
return super.onOptionsItemSelected(item);
}
}
///////////////////////////////////////////////////////////////////////
HelpActivity ---->
package com.smarthelp.smarthelp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import com.google.firebase.auth.FirebaseAuth;
public class HelpActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
configureibtnProfile();
}
private void configureibtnProfile(){
ImageButton ibtnProfile = (ImageButton) findViewById(R.id.ibtnProfile);
ibtnProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(HelpActivity.this, ProfileActivity.class));
}
});
}
}
//////////////////////////////////////////////////////////////////////////////
activity_help.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=".HelpActivity">
<ImageButton
android:id="#+id/ibtnProfile"
android:layout_width="51dp"
android:layout_height="52dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:contentDescription="ProfilButton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.025"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.983"
app:srcCompat="#drawable/profil" />
<ImageButton
android:id="#+id/ibtnOrder"
android:layout_width="52dp"
android:layout_height="52dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:contentDescription="OrderButton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.983"
app:srcCompat="#drawable/order" />
<ImageButton
android:id="#+id/ibtnHelp"
android:layout_width="51dp"
android:layout_height="53dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="236dp"
android:layout_marginRight="8dp"
android:layout_marginStart="236dp"
android:layout_marginTop="8dp"
android:contentDescription="HelpButton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.875"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.983"
app:srcCompat="#drawable/help" />
</android.support.constraint.ConstraintLayout>
///////////////////////////////////////////////////////////////////////////////
------->Logcat
08-13 19:13:15.273 21068-21068/com.smarthelp.smarthelp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.smarthelp.smarthelp, PID: 21068
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.smarthelp.smarthelp/com.smarthelp.smarthelp.ProfileActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.smarthelp.smarthelp.ProfileActivity.configureibtnHelp(ProfileActivity.java:48)
at com.smarthelp.smarthelp.ProfileActivity.onCreate(ProfileActivity.java:35)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
From the crash log it seems
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
there is an NPE on the button for which you are trying to set onclick listener.
In your ProfileActivity set the button to one of the ImageButtons of XML
Assuming you are trying to do for first of your image buttons
just add the following line before setting onClickListener
logout=(Button) findViewById(R.id.ibtnProfile);
Change
firebaseAuth.getInstance();
to
FirebaseAuth.getInstance();
at line 14 in ProfileActivity.java
It's pretty much said in the stacktrace: trying to call addOnClickListener on a null object at ProfileActivity on line 27
You haven't initialized logout button with any value. Probably forgot to findViewById it.
Related
I know that this question looks similar to others on SO but i have tried all the suggestions in the other similar questions and haven't had any success.
I'm getting this error:
2020-08-03 20:41:21.372 8916-8916/com.example.spacing E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.spacing, PID: 8916
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.spacing/com.example.spacing.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:159)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:675)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.spacing.MainActivity.<init>(MainActivity.java:15)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2020-08-03 20:41:21.411 8916-8916/com.example.spacing I/Process: Sending signal. PID: 8916 SIG: 9
on this code:
package com.example.spacing;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
public int firstValue;
EditText first;
String firstString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
first = (EditText)findViewById(R.id.firstNum);
firstString = first.getText().toString();
Button Go = (Button) findViewById(R.id.goButton);
Go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstValue = Integer.parseInt(firstString);
System.out.print(firstValue);
}
});
}
}
Here is the XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/goButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/buttonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.898" />
<TextView
android:id="#+id/FirstAttribute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/spacedMaterial"
app:layout_constraintBottom_toTopOf="#+id/goButton"
app:layout_constraintEnd_toStartOf="#+id/firstNum"
app:layout_constraintHorizontal_bias="0.457"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.043" />
<EditText
android:id="#+id/firstNum"
android:layout_width="165dp"
android:layout_height="40dp"
android:ems="10"
android:hint="#string/inMM"
android:importantForAutofill="no"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="#+id/FirstAttribute"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.934"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/FirstAttribute"
app:layout_constraintVertical_bias="0.476" />
<TextView
android:id="#+id/secondAttribute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/amount"
app:layout_constraintBottom_toTopOf="#+id/goButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.073"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.131" />
<EditText
android:id="#+id/secondNumber"
android:layout_width="165dp"
android:layout_height="40dp"
android:ems="10"
android:hint="#string/number"
android:importantForAutofill="no"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="#+id/secondAttribute"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.934"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/secondAttribute" />
<TextView
android:id="#+id/thirdAttribute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/areaWidth"
app:layout_constraintBottom_toTopOf="#+id/goButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.068"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.218" />
<EditText
android:id="#+id/thirdNumber"
android:layout_height="40dp"
android:layout_width="165dp"
android:ems="10"
android:hint="#string/inMM"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="#+id/thirdAttribute"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.934"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/thirdAttribute"
app:layout_constraintVertical_bias="0.476"
android:importantForAutofill="no" />
</androidx.constraintlayout.widget.ConstraintLayout>
Suggestions i have tried:
I have tried changing the init for the edit text to before and after on-create.
I have made sure that all ids are correct and are referencing the right thing.
And about 5 other things that i cant recall but none of them worked when i tried to build.
Any help is appreciated.
Problem is:
you are trying to initialize the "firstString" variable OUTSIDE of the click listener and as soon as the Activity is created, which means the variable will always be a null object because you did not actually write something in the EditText.
Simply initialize the String inside the ClickListener!
` package com.example.spacing;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
public int firstValue;
EditText first;
String firstString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
first = (EditText)findViewById(R.id.firstNum);
Button Go = (Button) findViewById(R.id.goButton);
Go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstString = first.getText().toString();
firstValue = Integer.parseInt(firstString);
System.out.print(firstValue);
}
});
}
}`
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I have problem with LoginNew activity. When I click "Zaloguj się" button (id LogIn) app stops working.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference error is displaying.
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.zapp4, PID: 23951
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.zapp4.LoginNew.userLogin(LoginNew.java:61)
at com.example.zapp4.LoginNew.onClick(LoginNew.java:120)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Process 23951 terminated.
LoginNew.java code:
package com.example.zapp4;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
public class LoginNew extends AppCompatActivity implements View.OnClickListener {
FirebaseAuth mAuth;
EditText EditTextUsername;
EditText EditTextPassword;
ProgressBar progressBar;
Button Przyciskzaloguj;
ImageView zcoinimage;
TextView zcoinnumber;
CardView LogIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_new);
mAuth = FirebaseAuth.getInstance();
EditTextUsername = (EditText) findViewById(R.id.EditTextUsernameedit);
EditTextPassword = (EditText) findViewById(R.id.EditTextPasswordedit);
Przyciskzaloguj = (Button) findViewById(R.id.Przyciskzaloguj);
zcoinnumber = (TextView) findViewById(R.id.zcoinnumber);
zcoinimage = (ImageView) findViewById(R.id.zcoinimage);
progressBar = findViewById(R.id.progressBar);
LogIn = findViewById(R.id.LogIn);
findViewById(R.id.LogIn).setOnClickListener(this);
}
private void userLogin() {
String username = EditTextUsername.getText().toString();
String password = EditTextPassword.getText().toString().trim();
if (username.isEmpty()) {
EditTextUsername.setError("Email jest wymagany");
EditTextUsername.requestFocus();
return;
}
if (password.isEmpty()) {
EditTextPassword.setError("Hasło jest wymagane");
EditTextPassword.requestFocus();
return;
}
if (password.length() < 6) {
EditTextPassword.setError("Minimalna długość hasła wynosi 6");
EditTextPassword.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(username).matches()) {
EditTextUsername.setError("Wprowadź poprawny email");
EditTextUsername.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(username, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
finish();
Intent intent = new Intent(LoginNew.this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Przyciskzaloguj.setVisibility(View.GONE);
zcoinnumber.setVisibility(View.VISIBLE);
zcoinimage.setVisibility(View.VISIBLE);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() != null) {
finish();
startActivity(new Intent(this, HomeActivity.class));
}
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.LogIn) {
userLogin();
}
}
}
activity_login_new.xml code:
<?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"
android:background="#drawable/gradient"
tools:context=".LoginNew">
<ImageView
android:id="#+id/imageView"
android:layout_width="233dp"
android:layout_height="297dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="88dp"
android:layout_marginTop="47dp"
android:layout_marginEnd="88dp"
android:layout_marginBottom="387dp"
android:contentDescription="#string/todo"
app:srcCompat="#drawable/znaczek_druzyny" />
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/EditTextUsernameedit"
android:layout_width="250dp"
android:layout_height="40dp"
android:background="#11000000"
android:hint="#string/prompt_email"
android:inputType="textPersonName"
android:textSize="16sp"
android:layout_marginBottom="35dp"
android:layout_above="#+id/EditTextPasswordedit"
android:layout_centerHorizontal="true"
android:autofillHints="" />
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/EditTextPasswordedit"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_alignStart="#+id/EditTextUsernameedit"
android:layout_alignParentBottom="true"
android:layout_marginStart="2dp"
android:layout_marginBottom="201dp"
android:background="#11000000"
android:textSize="16sp"
android:hint="#string/prompt_password"
android:inputType="textPassword"
android:autofillHints="" />
<androidx.cardview.widget.CardView
android:id="#+id/LogIn"
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="55dp"
android:layout_marginEnd="55dp"
android:layout_marginBottom="85dp"
app:cardBackgroundColor="#color/colorAccent"
app:cardCornerRadius="25dp"
app:cardElevation="10dp">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginTop="13dp"
android:layout_marginBottom="13dp"
android:text="#string/action_sign_in"
android:textColor="#fff"
android:textSize="30sp" />
</androidx.cardview.widget.CardView>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="265dp"
android:layout_height="265dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="65dp"
android:layout_marginTop="230dp"
android:layout_marginEnd="65dp"
android:layout_marginBottom="230dp"
android:visibility="gone" />
</RelativeLayout>
Change
EditText EditTextUsername;
EditText EditTextPassword;
To
AppCompatEditText EditTextUsername;
AppCompatEditText EditTextPassword;
And try
First, you have to import androidx.appcompat.widget.AppCompatEditText instead of android.widget.EditText
Secondly, use AppCompatEditText instead of EditText. you should modify the following lines
FirebaseAuth mAuth;
AppCompatEditText EditTextUsername;
AppCompatEditText EditTextPassword;
...
hope it helps you.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I tried to click the signup button in the loginactivity but when click the button in the app, it will jump out and give an error like this, it's true that there are questions similar to the one I'm asking, but I really tried all the solutions you proposed but it does not work for me.
The error:
> E/AndroidRuntime: FATAL EXCEPTION: main
> Process: com.fivenine.shareit, PID: 17033
> java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fivenine.shareit/com.fivenine.shareit.AccountActivity.SignUpActivity}:
> java.lang.NullPointerException: Attempt to invoke virtual method 'void
> android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
> on a null object reference
> at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2747)
> 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 'void
> android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
> on a null object reference
> at com.fivenine.shareit.AccountActivity.SignUpActivity.onCreate(SignUpActivity.java:44)
> at android.app.Activity.performCreate(Activity.java:6845)
> at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
> at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2700)
> 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)
here is the SignUpActivity.java:
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.fivenine.shareit.MainActivity;
import com.fivenine.shareit.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class SignUpActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private Button btnSignIn, btnSignUp, btnResetPassword;
private ProgressBar progressBar;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignIn = (Button) findViewById(R.id.sign_in_button);
btnSignUp = (Button) findViewById(R.id.sign_up_button);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnResetPassword = (Button) findViewById(R.id.btn_reset_password);
btnResetPassword.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
startActivity(new Intent(SignUpActivity.this, ResetPasswordActivity.class));
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
if (TextUtils.isEmpty(email)){
Toast.makeText(getApplicationContext(), "Enter email address!",
Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)){
Toast.makeText(getApplicationContext(), "Enter password!",
Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6){
Toast.makeText(getApplicationContext(), "Password too short,enter minimum 6 characters!",
Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignUpActivity.this,"createUserWithEmail:onComplete:" + task.isSuccessful(),
Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
if(!task.isSuccessful()){
Toast.makeText(SignUpActivity.this, "Authenticaton faled." + task.getException(),
Toast.LENGTH_SHORT).show();
}else{
startActivity(new Intent(SignUpActivity.this,
MainActivity.class));
finish();
}
}
});
}
});
}
#Override
protected void onResume(){
super.onResume();
progressBar.setVisibility(View.GONE);
}
}
The activity_sign_up.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="com.fivenine.shareit.AccountActivity.SignUpActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/gradient_6"
android:gravity="center"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<ImageView
android:layout_width="75dp"
android:layout_height="80dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="30dp"
android:contentDescription=""
android:src="#drawable/profile"
tools:ignore="ContentDescription" />
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:textColor="#android:color/black"/>
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="true"
android:hint="#string/hint_password"
android:imeActionId="#integer/login"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:textColor="#android:color/black"/>
<Button
android:id="#+id/sign_up_button"
style="?android:textAppearanceSmall"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:background="#drawable/btn_corner_pink_gradient"
android:text="#string/action_sign_in_short"
android:textColor="#android:color/white"
android:textStyle="bold"/>
<!-- <Button
android:id="#+id/btn_reset_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:background="#null"
android:text="#string/btn_forgot_password"
android:textAllCaps="false"
android:textColor="#color/colorAccent"/> -->
<!-- Link to login screen -->
<Button
android:id="#+id/sign_in_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:background="#null"
android:text="#string/btn_link_to_login"
android:textAllCaps="false"
android:textColor="#color/colorWhite"
android:textSize="15sp"/>
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center|bottom"
android:layout_marginBottom="20dp"
android:visibility="gone"/>
</android.support.constraint.ConstraintLayout>
you commented the btn_reset_password in xml. so it invokes the null object reference. Just un-comment the btn_reset_password in xml and try.
the code for 'btn_reset_password' button is commented. Just uncomment the button code and it should work.
I am using firebase authentication and Realtime database. My textViewSingup was working perfectly fine to swap Activities until I added the real-time database and after that whenever I click to change the activity it crashes my app. After few tries to fix it I added a button to see if that will do the trick but it does exactly the same thing.
Here is my code.
Main Activity Code
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
EditText editTextEmail, editTextPassword;
ProgressBar progressBar;
private Button button;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextPassword);
progressBar = findViewById(R.id.progressBar);
findViewById(R.id.textViewSignup).setOnClickListener(this);
findViewById(R.id.buttonLogin).setOnClickListener(this);
button = (Button) findViewById(R.id.buttonRegister);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openRegistration();
}
});
}
public void openRegistration(){
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
}
private void userLogin(){
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if(email.isEmpty()){
editTextEmail.setError("Please provide your Email");
editTextEmail.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
editTextPassword.setError("Please Enter a Valid Email Address");
editTextPassword.requestFocus();
return;
}
if(password.length()<6){
editTextPassword.setError("Password is Incorrect");
editTextPassword.requestFocus();
return;
}
if(password.isEmpty()){
editTextPassword.setError("Please provide your Password");
editTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful()){
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}else{
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.textViewSignup:
startActivity(new Intent(this, SignUpActivity.class));
break;
case R.id.buttonLogin:
userLogin();
break;
}
}
}
MainActivity.xml code
<?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="ie.wit.ca2.MainActivity">
<EditText
android:id="#+id/editTextPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.374" />
<Button
android:id="#+id/buttonLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Login"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.63" />
<TextView
android:id="#+id/textViewSignup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Create an account here"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.869" />
<EditText
android:id="#+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="Email Address"
android:inputType="textEmailAddress"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.233" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.477" />
<Button
android:id="#+id/buttonRegister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Register"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/buttonLogin"
app:layout_constraintVertical_bias="0.055" />
</android.support.constraint.ConstraintLayout>
SignupActivity code
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener{
ProgressBar progressBar;
EditText editTextEmail, editTextPassword;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextPassword);
progressBar = findViewById(R.id.progressBar);
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.buttonSignUp).setOnClickListener(this);
findViewById(R.id.textViewSignup).setOnClickListener(this);
}
private void registerUser(){
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if(email.isEmpty()){
editTextEmail.setError("Please provide your Email");
editTextEmail.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
editTextPassword.setError("Please Enter a Valid Email Address");
editTextPassword.requestFocus();
return;
}
if(password.length()<6){
editTextPassword.setError("Password must have minimum 6 characters");
editTextPassword.requestFocus();
return;
}
if(password.isEmpty()){
editTextPassword.setError("Please provide your Password");
editTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful()){
Intent intent = new Intent(SignUpActivity.this, ProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}else{
if(task.getException() instanceof FirebaseAuthUserCollisionException){
Toast.makeText(getApplicationContext(), "This Email has already been registered", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.buttonSignUp:
registerUser();
break;
case R.id.textViewLogin:
startActivity(new Intent(this, MainActivity.class));
break;
}
}
}
This is the error i am getting when I try to change activities.
04-29 11:41:04.775 12204-12204/ie.wit.ca2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: ie.wit.ca2, PID: 12204
java.lang.RuntimeException: Unable to start activity ComponentInfo{ie.wit.ca2/ie.wit.ca2.SignUpActivity}: 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:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
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 ie.wit.ca2.SignUpActivity.onCreate(SignUpActivity.java:41)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
So after few more hours trying to find the problem, I finally managed to notice whats wrong. In line 41 of my Signup activity, I was calling a text view that didn't exist thus making my app crash all the time.
Iam trying to set a text(data ) of Edittext widget obtained from a database,But iam getting the above error,Iam trying to resolve but not getting the actual idea,Please help me with this,Thanks in advance,
This is my MainActivity.java
package com.mycompany.newlogin;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button btLogout;
EditText etName,etPhone,etEmail,etUsername;
private static String url = "jdbc:mysql://31.170.160.74:3306/a5582611_mane";
private static String user = "a5582611_nanu";
private static String password = "sonne0";
UserLocalStore userLocalStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName=(EditText)findViewById(R.id.etName);
etPhone=(EditText)findViewById(R.id.etPhone);
etEmail=(EditText)findViewById(R.id.etEmail);
etUsername=(EditText)findViewById(R.id.etUsername);
btLogout=(Button)findViewById(R.id.btLogout);
userLocalStore=new UserLocalStore(this);
btLogout.setOnClickListener(this);
}
#Override
protected void onStart(){
super.onStart();
if(authenticate()==true){
//go to your question window
displayUserDetails();
}else {
startActivity(new Intent(MainActivity.this,Login.class));
}
}
private void displayUserDetails(){
User user=userLocalStore.getLoggedInUser();
etName.setText(user.name);
etEmail.setText(user.email);
etUsername.setText(user.username);
}
private boolean authenticate(){
return userLocalStore.getUserLoggedIn();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btLogout:
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
startActivity(new Intent(this, Login.class));
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And my activity_xml file is like this,
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etName"
android:layout_marginBottom="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Email"
android:layout_marginBottom="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etUsername"
android:layout_marginBottom="10dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btLogout"
android:text="Logout"
android:layout_gravity="center"/>
And here is my error details,
FATAL EXCEPTION: main
Process: com.mycompany.newlogin, PID: 2787
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mycompany.newlogin/com.mycompany.newlogin.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
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:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.mycompany.newlogin.MainActivity.displayUserDetails(MainActivity.java:51)
at com.mycompany.newlogin.MainActivity.onStart(MainActivity.java:42)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1243)
at android.app.Activity.performStart(Activity.java:5969)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
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:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Please help me to resolve this
Your etEmail edit text is null:
In place of- etEmail=(EditText)findViewById(R.id.etEmail);
It should be-etEmail=(EditText)findViewById(R.id.Email);
Since your etEmail id is "Email" not "etEmail".