Home > Back-end >  requireActivity().getApplicationContext() "may produce a NullPointerExeption"
requireActivity().getApplicationContext() "may produce a NullPointerExeption"

Time:10-13

Bellow there is some of the code of my application. The part where I need help is in requireActivity() in SettingFragment.java:

MainActivity.java

...
public class MainActivity extends AppCompatActivity {
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      ...
   }

   public void iniciarIntent3() {   //this method is called by a button in activity_main.xml
        Intent intent = new Intent(this, Settings.class);
        startActivityForResult(intent, 1);
   }
}

Settings.java

...

public class Settings extends AppCompatActivity implements SettingsFragment.SendToActivity {
   ...
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      ...
      if (savedInstanceState == null) {
         getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.settings, new SettingsFragment())
            .commit();
      }
   }

   @Override
   public void onAttachFragment(Fragment fragment) {
      if (fragment instanceof SettingsFragment) {
         SettingsFragment settingsFragment = (SettingsFragment) fragment;
         settingsFragment.setSendToActivity(this);
      }
   }
   public void send(int result) {
      ...
   }
}   

SettingsFragment.java

public class SettingsFragment extends PreferenceFragmentCompat {

   SendToActivity callback;

   public void setSendToActivity (SendToActivity callback) {
      this.callback = callback;
   }

   public interface SendToActivity {
      void send(int result);
   }
   
   if (editTextPreference != null) {
      editTextPreference.setOnBindEditTextListener(new 
      EditTextPreference.OnBindEditTextListener() {
         @Override
         public void onBindEditText(@NonNull EditText editText) {
            editText.setInputType(InputType.TYPE_CLASS_NUMBER);
            editText.setText("");                
            editText.setBackground(ContextCompat.getDrawable(requireActivity()
               .getApplicationContext(), R.drawable.fondo_edittextpreference));
         }
      });
   }
   ...
}

I just want to be sure that requireActivity() in SettingsFragment class is not going to throw a nullpointerexeption. Can you help me to check?

CodePudding user response:

requireActivity()

can throw null if the Activity is null for whatever reason that may be. I believe that can be null if the user exists the application or forefully stops it etc. Or there was never one created in the context that youre in

Just do a null check

Activity activity = requireActivity()
if (activity != null)
    editText.setBackground(ContextCompat.getDrawable(activity
           .getApplicationContext(), R.drawable.fondo_edittextpreference));
else
    //handle here when the activity is null
  • Related