简体   繁体   中英

Cant trace out cause of error java.lang.NullPointerException

why sometimes this code is throwing errors and sometime not ??

 if ( getActivity().getApplicationContext() != null ){
    File file = new File(getActivity().getApplicationContext().getFilesDir() + "/img.jpg"); }

the above code is inside my fragment

my Error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference

If you are running this in seperate AsyncTask or thread and activity that has started this no longer exists or active. getActivity() might return null.

So solution is to add null check for getActivity() too along with getActivity().getApplicationContext().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM