Nullable problem with Intents with extras - java

I am learning how to develop for Android (and development in general). I am trying to create a Quiz App, so I can learn the basics.
While trying to use an Intent to go to another class with an extra variable on it, I found this problem (which I think is pretty usual): My app crashes when I go to the next Activity.
This is the code in the activity that gets the username ("usuario and nomeUsuario"):
package com.isa56.quiz2;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class HomeActivity extends AppCompatActivity {
public EditText usuario;
public EditText senha;
public Button botaoLogin;
public String nomeUsuario;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
botaoLogin = findViewById(R.id.botaoLogin);
senha = findViewById(R.id.senha);
usuario = findViewById(R.id.usuario);
nomeUsuario = usuario.getText().toString();
Log.d("nome de usuario", nomeUsuario);
botaoLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(HomeActivity.this, FirstQuestionActivity.class);
i.putExtra("nome", nomeUsuario);
startActivity(i);
}});
}
}
And this is the code on the SecondQuestionActivity:
package com.isa56.quiz2;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class FirstQuestionActivity extends AppCompatActivity {
public Button prox1;
public Button respUm1;
public Button respUm2;
public TextView texto1;
public int pontuacao = 0;
Intent i = getIntent();
String nome = i.getStringExtra("nome");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstquestion);
prox1 = findViewById(R.id.prox1);
respUm1 = findViewById(R.id.botao1a);
respUm2 = findViewById(R.id.botao1b);
texto1 = findViewById(R.id.texto1);
respUm1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
texto1.setText("Resposta errada!");
respUm1.setEnabled(false);
respUm2.setEnabled(false);
prox1.setEnabled(true);
}});
respUm2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
texto1.setText("Resposta certa!");
respUm2.setEnabled(false);
respUm1.setEnabled(false);
pontuacao += 1;
prox1.setEnabled(true);
}});
prox1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(FirstQuestionActivity.this, SecondQuestionActivity.class);
i.putExtra("pontos", pontuacao);
i.putExtra("nome", nome);
startActivity(i);
}
});
}
}
What is wrong with it? How can I prevent it?
Thank you!
P.S.: I am not used to forum or development in general, so I might have done this wrongly. I'm sorry.
Edit: Also, if anyone wanna take a look at the whole project, it's here.
Edit2: This is the Logcat output:
2020-11-13 21:05:18.531 7517-7517/com.isa56.quiz2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.isa56.quiz2, PID: 7517
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.isa56.quiz2/com.isa56.quiz2.FirstQuestionActivity}: 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:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
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.isa56.quiz2.FirstQuestionActivity.<init>(FirstQuestionActivity.java:18)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 

Keep these lines inside onCreate() method.
Intent i = getIntent();
String nome = i.getStringExtra("nome");

Related

how to fix android app crashing on startup? [duplicate]

This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 4 months ago.
i'm a begginner developer and the app in question is a test app for an api, from jkutner's tutorial on github. it is crashing as soon as it opens, which is weird, because i've used this exact same code at least thrice and it used to work. i'll leave the code and the logcat below, thank you in advance for your help!
MainActivity
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity
{
final EditText isbnInput = (EditText) findViewById(R.id.isbnInput);
final TextView textView = (TextView) findViewById(R.id.textView);
final Button button = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://venusdove.herokuapp.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
final BookService service = retrofit.create(BookService.class);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Book book = new Book(isbnInput.getText().toString());
Call<Book> createCall = service.create(book);
createCall.enqueue(new Callback<Book>() {
#Override
public void onResponse(Call<Book> _, Response<Book> resp) {
Book newBook = resp.body();
textView.setText("Created Book with ISBN: " + newBook.isbn);
}
#Override
public void onFailure(Call<Book> _, Throwable t) {
t.printStackTrace();
textView.setText(t.getMessage());
}
});
}
});
}
}
Book class
package com.example.myapplication;
import com.google.gson.annotations.SerializedName;
public class Book
{
#SerializedName("id")
int id;
#SerializedName("isbn")
String isbn;
public Book(int id, String isbn) {
this.id = id;
this.isbn = isbn;
}
public Book(String isbn) {
this.isbn = isbn;
}
}
BookService class
package com.example.myapplication;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
public interface BookService
{
#GET("books")
Call<List<Book>> all();
#GET("books/{isbn}")
Call<Book> get(#Path("isbn") String isbn);
#POST("books/new")
Call<Book> create(#Body Book book);
}
logcat
2022-10-19 08:56:03.651 8041-8041/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 8041
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.myapplication.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:2679)
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 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:655)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:852)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:819)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:261)
at com.example.myapplication.MainActivity.<init>(MainActivity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1174)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
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)
You need to "find" view after they are created.
EditText isbnInput;
TextView textView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
isbnInput = (EditText) findViewById(R.id.isbnInput);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
}
It is because of findViewById. You should call it inside OnCreate. Because it needs View that it is being called from to be initialized.
private EditText isbnInput;
private TextView textView;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState)
{
isbnInput = (EditText) findViewById(R.id.isbnInput);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);

Android Studio Emulator Crashing On Button Click

I am very new to Android Studio and am trying to create a log in screen which then opens an inventory screen. The problem I am having is when I click Submit to the username and password, the app completely crashes. Right now, I am just working out how to organize the layout portion of things, but need to figure out how to get this transition to work. Any help would be great!
This is the main activity code:
package com.example.cs360projectone;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText username, password;
Button buttonLogIn, buttonRegister;;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.newPassword);
buttonLogIn = (Button) findViewById(R.id.buttonLogIn);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(username.getText().toString().trim().length() <1 || password.getText().toString().trim().length() <1){
username.setError("You must enter a valid username and password");
}
else {
openInventory();
}
}
});
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
openRegisterScreen();
}
});
}
public void openRegisterScreen() {
Intent intent = new Intent(this, RegisterScreen.class);
startActivity(intent);
}
public void openInventory() {
Intent intent = new Intent(this, InventoryScreen.class);
startActivity(intent);
}
}
This is the inventory screen code:
package com.example.cs360projectone;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class InventoryScreen extends AppCompatActivity {
Button buttonSMS, buttonSignOut;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_screen);
buttonSMS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
openSMSPermission();
}
});
}
public void openSMSPermission() {
Intent intent = new Intent(this, SMSPermissionScreen.class);
startActivity(intent);
}
}
This is the error from logcat when the button is pressed:
2022-08-03 16:54:09.037 8043-8043/com.example.cs360projectone E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cs360projectone, PID: 8043
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cs360projectone/com.example.cs360projectone.InventoryScreen}: 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: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.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.cs360projectone.InventoryScreen.onCreate(InventoryScreen.java:18)
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) 
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) 
2022-08-03 16:54:09.062 8043-8043/com.example.cs360projectone I/Process: Sending signal. PID: 8043 SIG: 9
You need to get the SMS button in the InventoryScreen onCreate method the same way you did with the other buttons in MainActivity.
This means doing a
buttonSMS = (Button) findViewById(R.id.buttonSMS);
before setting up an onClickListener.

Android chat app keeps on crashing when I run it

I have just begun writing some code for my Chat app after days of planning but the problem is that keeps on crashing right after the Gradle Build has finished and the app is installed on my device. I have created a button that is expected to open a new activity but instead of doing so it crashes. Everything works before I have written any code, the app opens and logcat doesn't show any errors. Here is the error:
2022-08-10 19:26:48.372 15348-15348/? E/e.myapplicatio: Unknown bits set in runtime_flags: 0x40000000
2022-08-10 19:26:48.391 15348-15348/? E/RefClass: java.lang.reflect.InvocationTargetException
2022-08-10 19:26:48.474 15348-15348/com.example.myapplication E/Perf: perftest packageName : com.example.myapplication App is allowed to use Hide APIs
2022-08-10 19:26:48.515 15348-15374/com.example.myapplication E/libEGL: Invalid file path for libcolorx-loader.so
2022-08-10 19:26:48.528 15348-15348/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 15348
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.myapplication.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:3628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3887)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:263)
at android.app.ActivityThread.main(ActivityThread.java:8292)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006)
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:183)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
at android.content.Context.obtainStyledAttributes(Context.java:744)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:848)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:815)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:259)
at com.example.myapplication.MainActivity.<init>(MainActivity.java:12)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1254)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3616)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3887) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:263) 
at android.app.ActivityThread.main(ActivityThread.java:8292) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006) 
I tried following some other suggestions but they didn't work. Here's the snippet of my code:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public Button signUp = findViewById(R.id.signUpBtn);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity();
}
});
}
public void openActivity(){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
You can not use findViewById() outside of onCreate() like this and if you really wanna do that, do it by creating a new method for setting up IDs and then add that method in onCreate().
this code will do the work now:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public Button signUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signUp = findViewById(R.id.signUpBtn);
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity();
}
});
}
public void openActivity(){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}

Android Studio Activity doesn't start

When starting my activity there is always an error message and the app does not open.
Error:
2022-05-11 23:18:12.470 17222-17222/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 17222
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.feuerwerkzndanlage.Biometric_Authentication}: 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:3455)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3699)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2135)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8056)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
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:133)
at com.example.feuerwerkzndanlage.Biometric_Authentication.<init>(Biometric_Authentication.java:23)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1254)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3443)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3699) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2135) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:236) 
at android.app.ActivityThread.main(ActivityThread.java:8056) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967) 
Activity:
package com.example.feuerwerkzndanlage;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;
import java.util.concurrent.Executor;
public class Biometric_Authentication extends AppCompatActivity {
private TextView authStatusTv;
private BiometricPrompt biometricPrompt;
private BiometricPrompt.PromptInfo promptInfo;
Context context = getApplicationContext();
CharSequence error_txt = "Indentifizierung Fehlgeschlagen: ";
CharSequence suceed_txt = "Indentifizierung Erfolgreich";
CharSequence failed_txt = "Indentifizierung Fehlgeschlagen";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biometric_authentication);
authStatusTv = findViewById(R.id.authStatusTv);
Button btn_auth = findViewById(R.id.btn_auth);
Executor executor = ContextCompat.getMainExecutor(this);
biometricPrompt = new BiometricPrompt(Biometric_Authentication.this, executor, new BiometricPrompt.AuthenticationCallback() {
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
authStatusTv.setText("Indentifizierung Fehlgeschlagen: " + errString);
Toast.makeText(context, error_txt, duration).show();
}
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationSucceeded(#NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
authStatusTv.setText("Indentifizierung Erfolgreich");
Toast.makeText(context, suceed_txt, duration).show();
}
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
authStatusTv.setText("Indentifizierung Fehlgeschlagen");
Toast.makeText(context, failed_txt, duration).show();
}
});
promptInfo = new BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometrische Indentifizierung")
.setSubtitle("Login")
.setNegativeButtonText("Benutzer Passwort")
.build();
btn_auth.setOnClickListener(view -> biometricPrompt.authenticate(promptInfo));
}
}
Context context = getApplicationContext();
You can't do that at init time. You can't call any Context related functions, including getApplicationContect() until onCreate is called. This is because the framework hasn't fully initialized the activity before then. To make this work, you'd need to move this line into onCreate, and move any code that depends on this variable being set into onCreate or later as well.

How to solve NullPointerException in the following code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
[This is the code where the exception occurred.
package com.example.shrine;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
final TextInputLayout password1 = findViewById(R.id.password_text_input);
final TextInputEditText password = findViewById(R.id.password_edit_text);
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
MaterialButton Next=findViewById(R.id.next_button);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ctx,"This can't be happening!",Toast.LENGTH_SHORT).show();
Intent products = new Intent(MainActivity.this, products_act.class);
startActivity(products);
}
});
}
}
package com.example.shrine;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class products_act extends AppCompatActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context=this;
setContentView(R.layout.activity_products_act);
Button back=findViewById(R.id.button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Back Button Clicked!!", Toast.LENGTH_SHORT).show();
Intent backToHome = new Intent(products_act.this, MainActivity.class);
startActivity(backToHome);
}
});}}
ERROR:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.shrine, PID: 18243
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.shrine/com.example.shrine.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:2718)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
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:152)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:655)
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.shrine.MainActivity.<init>(MainActivity.java:18)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1173)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2708)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
Please look into this problem of NullPointerException as I am new to Android development and still Learning therefore please help.The attached photos [1] and [2] are the code snaps. Please check them out.
P.S.-I have removedthe code as images.Thankyou for the suggestion
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.shrine.MainActivity.<init>(MainActivity.java:18)
This tells you're calling findViewById() too early in MainActivity's init phase e.g. when initialising its fields. Move the findViewById() calls to onCreate() after setContentView().

Categories