I have Fragment A and Fragment B, on fragment A i have an input searchbox and when I open the fragment it shows the softkeyboard which is intended. When switching fragments sometimes a NullPointerException occurs. I cannot reproduce the error but the log file says that the error occurs on the onResume() function. Below is the code i used on my onResume(), what can be the reason i get java.lang.NullPointerException?
#Override
public void onResume() {
super.onResume();
getActivity().setTitle(R.string.app_name);
if (getActivity().getWindow().getCurrentFocus() == searchbox) {
searchbox.postDelayed(new Runnable() {
#Override
public void run() {
InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(searchbox, InputMethodManager.SHOW_IMPLICIT);
}
}
}, 300);
}
}
Edit:
Here is logcat:
java.lang.NullPointerException:
at com.myapp.fragments.MyMain$7.run (MyMain.java:258)
at android.os.Handler.handleCallback (Handler.java:815)
at android.os.Handler.dispatchMessage (Handler.java:104)
at android.os.Looper.loop (Looper.java:207)
at android.app.ActivityThread.main (ActivityThread.java:5811)
at java.lang.reflect.Method.invoke (Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:907)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:768)
Inside the run method you have:
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
getActivity() may be null if the fragment is not attached to the Activity after 300 milliseconds.
Null pointer exception means you are trying to work with a variable that has not been initialized yet. So in your onResume method, check all the variables. Make sure they survive the activity distruction. Because many variables don't resume in the onResume.
You will need to figure out which variable is giving null pointer exception and then initialize that variable in the onResume method.
You can use try catch method on each code line in your onResume method to fugure out which of the codeline is giving error. in catch method you can print out the error to console as follows
try{
//1st code line
}catch{ System.out.println("1st line gives the error")
}
Yes I agreewith magnetar. That should solve your issue.
try{
//code line 1
}catch(Exception e){
Log.i(TAG, "method: "+e.getMessage());
}
try this on each line
Another way you can go about it is by debugging your project and adding breakpoints in onResume method. That could be more helpful.
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);
I have a toggle button, That is working as expected.
To test i have a Toast message, and they are both working.
However i have tried to store a the value of the Toggle to shared preference, I keep getting a error about Null object?
I have used this SharedPreference code throughout my app and i have never had an issue with it.
But this is the first time i am trying to use a Toggle, Everything else is Buttons, Radio or sliders.
Am i missing something?
If i comment out the PreferenceManager Store value, it works fine.
Here is the Code for my Toggle:
Switch myToggleButton = inflated.findViewById(R.id.switchon);
myToggleButton.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked)
{
if(isChecked) {
preferenceManager.storeValue(packageName, true);
Toast.makeText(context, "You have Enabled "+ appName + " Notification", Toast.LENGTH_SHORT).show(); }
else{
preferenceManager.storeValueapp(packageName, false);
Toast.makeText(context, "You have DISABLED "+ appName +" Notification", Toast.LENGTH_SHORT).show();
}
}
});
I also tried double checking null by running:
if (myToggleButton!=null){ //run code here }
But this was still the same
Here is the Error i am getting when pressing the Toggle On.
2020-05-14 12:08:35.360 23783-23783/com.enigamcodes.cutoutnotification E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.enigamcodes.cutoutnotification, PID: 23783
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.enigamcodes.cutoutnotification.Utils.PreferenceManager.storeValue(java.lang.String, java.lang.Object)' on a null object reference
at com.enigamcodes.cutoutnotification.Settings.NotificationColor$2.onCheckedChanged(NotificationColor.java:133)
this message
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.enigamcodes.cutoutnotification.Utils.PreferenceManager.storeValue(java.lang.String, java.lang.Object)' on a null object reference
means preferenceManager hasn't been initialized.
I am getting this error in my published application, only clients receive this error. I already tried several times to replicate the same mistake however unsuccessfully.
I also already tried to use the below code at all locations where there is a Dialog but also not solved.
if (dialog.isShowing ()) {
dialog.dismiss ();
}
The error report
java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView{16faa139 V.E..... R.....I. 0,0-0,0} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:412)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:338)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:122)
at android.app.Dialog.dismissDialog(Dialog.java:522)
at android.app.Dialog.dismiss(Dialog.java:504)
**at br.my.project.de.a(Unknown Source)
at br.my.project.de.onPostExecute(Unknown Source)**
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
I could see that you are trying to dismiss a ProgressDialog on the postExecute of an AsyncTask. This in itself is a good practice but is sometimes buggy, I kind of experienced this also before especially while you're showing the ProgressDialog and suddenly rotate the view.
A solution I've found to fix this is below:
You will need these function to handle the proper dismissal and avoid crashes.
private void dismissProgressDialog(ProgressDialog progressDialog) {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
//get the Context object that was used to create the dialog
Context context = ((ContextWrapper) progressDialog.getContext()).getBaseContext();
// if the Context used here was an activity AND it hasn't been finished or destroyed
// then dismiss it
if (context instanceof Activity) {
// Api >=17
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed()) {
dismissWithExceptionHandling(progressDialog);
}
} else {
// Api < 17. Unfortunately cannot check for isDestroyed()
if (!((Activity) context).isFinishing()) {
dismissWithExceptionHandling(progressDialog);
}
}
} else
// if the Context used wasn't an Activity, then dismiss it too
dismissWithExceptionHandling(progressDialog);
}
progressDialog = null;
}
}
public void dismissWithExceptionHandling(ProgressDialog dialog) {
try {
dialog.dismiss();
} catch (final IllegalArgumentException e) {
// Do nothing.
} catch (final Exception e) {
// Do nothing.
} finally {
dialog = null;
}
}
On your AsyncTask's onPostExecute implement the function.
#Override
protected void onPostExecute(Boolean b) {
// pass in the progressDialog as a parameter to the method
dismissProgressDialog(progressDialog);
}
fun Activity?.dismissDialog(dialog: Dialog?) {
if (isActivityActive()) {
dialog?.apply {
if (isShowing) dismiss()
}
}
}
fun Activity?.isActivityActive(): Boolean {
return null != this && !isFinishing && !isDestroyed
}
You are calling dismiss on a dialog that is currently not being shown anymore. As in: your Activity/Fragment is possibly already destroyed when you call dismiss.
Write this code in your activity's
onStop()
method.When anybody presses the home button and if dialog is opened than this error will come. Because on click of home button onPause() and onStop() method calls.Hope this helps.
if (dialog!=null && dialog.isShowing ()) {
dialog.dismiss ();
}
Here is the code
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(this.redirectUrl+"?username="+getValue(loginString)+"&password="+getValue(pwdString)));
startActivity(browserIntent);
I have this error :
10-17 15:30:35.288 5467-5467/com.example.android.navigationdrawerexample W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40cd7930)
10-17 15:30:35.298 5467-5467/com.example.android.navigationdrawerexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Fragment PlanetFragment{41b91f78} not attached to Activity
at this line :
startActivity(browserIntent);
This and this DOESN'T work for me.
What i can do ?
Why don't you just call getActivity() from Fragment and then call startActivity() like getActivity().startActivity(intent);
From the exception, it looks like you're calling this method on a Fragment that is not (yet?) attached to an Activity. From the source of the Fragment class:
public void startActivity(Intent intent, Bundle options) {
if (mActivity == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
...
To fix this, just change the place where this method is called, i.e. after onAttach() and before onDetach().