This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My problem is that one specific activity in my app can't be launched for some reason, and it throws:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
All other launching code that looks like this work fine, the problem is ONLY when I'm launching Player1. The class surely exists, and I can't understand what is the problem.
I'm launching an activity called Player1 from an activity called ChooseLevel. When some button is pressed, the call is:
Intent intent = new Intent(ChooseLevel.this, Player1.class);
Bundle b = new Bundle();
b.putInt("game_level", 1);
intent.putExtras(b);
startActivity(intent);
finish();
The logs show that the error is in: Player1.onCreate(Player1.java:50)
The code in line Player1:50 is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
changeIndex = 0;
cards = new ArrayList<Card>(8);
score = (TextView) findViewById(R.id.score_text);
message = (TextView) findViewById(R.id.msg_text);
timer = (TextView) findViewById(R.id.timer);
timer.setText(String.valueOf(definitions.TIMER_START)); # LINE 50
Bundle b = getIntent().getExtras();
...
}
When this launching code runs, I get this in my logs:
33:04.338 18302-18302/com... D/AndroidRuntime: Shutting down VM
01-18 10:33:04.338 18302-18302/com... E/AndroidRuntime: FATAL EXCEPTION: main
Process: com..., PID: 18302
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.../com....Player1}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at com....Player1.onCreate(Player1.java:50)
EDIT:
I found my answer, it had to do with some object that I had in my Player1.onCreate() method. In a wierd way, android-studio raised the exception regarding getClass(). If someone knows why this happend, please share :)
use context,getApplicationContext()orgetActivity()`
Intent intent = new Intent(context, Player1.class);
Bundle b = new Bundle();
b.putInt("game_level", 1);
intent.putExtras(b);
startActivity(intent);
finish();
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
Guys i have been making this simple Uber app and whenever the Driver LogsOut my app crashes because the getCurrentUser() method is returning a null value. But whenever the user logsOut im closing the activity, and before calling getCurrentUser() i have this if(getApplicationContext()!=null) which should return false because the activity is closed so it should prevent getCurrentUser() from being called. How do i prevent it from crashing? What am i missing here?
This is where on Button click i logOut my user
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some code here
mLogout=(Button)findViewById(R.id.logout);
mLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isLoggingOut = true;
disconnectDriver();
//Signing out user here
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(DriverMapActivity.this, MainActivity.class);
startActivity(intent);
return;
}
});
//some code here
}
This is where the error is happening
#Override
//this is going to run whenever the driver location changes
public void onLocationChanged(Location location) {
if(getApplicationContext()!=null) {
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//
//This is where the error is happening
//java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference refAvailable = FirebaseDatabase.getInstance().getReference("driversAvailable");
DatabaseReference refWorking = FirebaseDatabase.getInstance().getReference("driversWorking");
GeoFire geoFireAvailable = new GeoFire(refAvailable);
GeoFire geoFireWorking = new GeoFire(refWorking);
switch(customerId){
case "":
geoFireWorking.removeLocation(userId);
geoFireAvailable.setLocation(userId, new GeoLocation(location.getLatitude(), location.getLongitude()));
break;
default:
geoFireAvailable.removeLocation(userId);
geoFireWorking.setLocation(userId, new GeoLocation(location.getLatitude(), location.getLongitude()));
break;
}
}
}
This is the Error Log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jonanako.uber, PID: 15522
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.jonanako.uber.DriverMapActivity.onLocationChanged(DriverMapActivity.java:211)
at com.google.android.gms.internal.location.zzat.notifyListener(com.google.android.gms:play-services-location##18.0.0:2)
at com.google.android.gms.common.api.internal.ListenerHolder.zaa(com.google.android.gms:play-services-base##18.0.1:2)
at com.google.android.gms.common.api.internal.zacb.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
Since you assign false to your isLoggingOut = true; whenever you click on the button, you should just check if(getApplicationContext()!=null && !isLoggingOut) so the code wont run whenever isLoggingOut==false;
getApplicationContext() won't be null when you finish() Activity, even last or one and only. consider using if(!isFinishing()), lifecycle checking or just set own boolean flag.
additionally you may (should) also check that getCurrentUser() returns null, that would mean that user logs out. if is null then don't call any method on returned object (because nothing is returned in fact)
if(!isFinishing() && FirebaseAuth.getInstance().getCurrentUser()!=null) {
In my project I have two activities: MainActivity.class and SecondActivity.class.
To switch from the MainActivity to the SecondActivity I use the following code:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
MainActivity.this.startActivity(intent);
And it works.
I use the same code to switch from the SecondActivity to the MainActivity but the app crashes:
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
SecondActivity.this.startActivity(intent);
If I try to open the MainActivity from the MainActivity itself it crushes too, but this doesn't happen if I try to open the SecondActivity from the SecondActivity.
Any idea?
Here my stack trace:
2021-09-29 17:25:56.843 25827-25827/st.com.st25androiddemoapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: st.com.st25androiddemoapp, PID: 25827
java.lang.RuntimeException: Unable to resume activity {st.com.st25androiddemoapp/st.com.st25androiddemoapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4270)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4302)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at st.com.st25androiddemoapp.MainActivity.onResume(MainActivity.java:279)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1454)
at android.app.Activity.performResume(Activity.java:8050)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4260)
Thank You
If what you want is to return to MainActivity then in SecondActivity you should simply do:
finish()
This will destroy the activity and return to the previous one.
When you start MainActivity using startActivity(intent), Intent.getAction() method will return null. This method is called in MainActivity#onResume.
To prevent your app from crashing, you need to make sure that action is not null before calling any methods (equals() in your case.)
I found the source code. Just and action != null && here
if (action != null && (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED) ||
action.equals(NfcAdapter.ACTION_TECH_DISCOVERED) ||
action.equals(NfcAdapter.ACTION_TAG_DISCOVERED))) {
// If the resume was triggered by an NFC event, it will contain an EXTRA_TAG providing
// the handle of the NFC Tag
Tag androidTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (androidTag != null) {
// This action will be done in an Asynchronous task.
// onTagDiscoveryCompleted() of current activity will be called when the discovery is completed.
new TagDiscovery(this).execute(androidTag);
}
}
don't forget to add brackets ()
It will fix the NPE, but I'm not sure if this is the best solution. I don't know what you are trying to achieve.
upd
If you want to navigate back to main activity by closing Second activity, which was opened on top of MainActivity, then just use finish() method
have you tried replace getapplicationcontext() with this ?
Intent intent = new Intent(SecondActivity.this,MainActivity.class);
startActivity(intent);
My java code:
public class StartActivity extends AppCompatActivity {
private Button mRegBtn;
private Button mLoginBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mRegBtn = (Button) findViewById(R.id.start_reg_btn);
mLoginBtn = (Button) findViewById(R.id.start_login_btn);
mRegBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent reg_intent = new Intent(StartActivity.this, RegisterActivity.class);
startActivity(reg_intent);
}
});
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent login_intent = new Intent(StartActivity.this, LoginActivity.class);
startActivity(login_intent);
}
});
}
}
The LogCat shows this:
2020-04-30 12:53:42.391 31407-31407/com.example.chattting E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chattting, PID: 31407
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chattting/com.example.chattting.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2947)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3012)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1716)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:232)
at android.app.ActivityThread.main(ActivityThread.java:6802)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1103)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at com.example.chattting.LoginActivity.onCreate(LoginActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6974)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3012)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1716)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:232)
at android.app.ActivityThread.main(ActivityThread.java:6802)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1103)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
first answer i give.
Based on your log, the line
"Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference" says, that is having trouble setting an AppBar Title.
My bet is that you have some sort of error, in one of the Activities you are trying to start, from the buttons.
If you want more help, tell what is the button that is failing, and send the Other two activities code.
I am trying to pass an integer from a fragment to another java class however I keep getting an error: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String, int)' on a null object reference
Bundle b = new Bundle();
b.putInt("id", position);
Intent passInt = new Intent(view.getContext(), displayAccount.class);
passInt.putExtras(b);
startActivity(passInt);
startActivity(new Intent(view.getContext(), displayAccount.class));
Then in displayAccount.java:
int id = (getIntent().getExtras().getInt("id",0));
You called double times startActivity. It will be work when you delete this line startActivity(new Intent(view.getContext(), displayAccount.class));. Because you didn't put bundle on this line, you just starting the activity. You already give intent with startActivity(passInt);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
i try to add onClick this button then create contact in database
Here is code i try to add it to main_fragment
final Button addBtn = (Button) view.findViewById(R.id.btnadd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
import_fragment.Contact contact = new import_fragment.Contact(dbHandler.getContactsCount(), String.valueOf(nametxt.getText()), String.valueOf(phoneTxt.getText()), String.valueOf(emailTxt.getText()), String.valueOf(addressTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
contactAdapter.notifyDataSetChanged(); // Error in this line
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
}
});
When i press this button in my app, 'app has stopped working'
Here is my logcat
01-22 08:31:04.014 29398-29398/com.al3almya.users.al3almya E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.al3almya.users.al3almya, PID: 29398
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.notifyDataSetChanged()' on a null object reference
at com.al3almya.users.al3almya.main_fragment$1.onClick(main_fragment.java:77)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20262)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Either the contactAdapter is not initialized(contactAdater is null) or the object on which the adapter is set is null.
Make sure you have initialized all the variables. Else try running dubugger.
It appears that the variable contactAdapter has not been set.