requireActivity().getApplicationContext() "may produce a NullPointerExeption"

requireActivity().getApplicationContext() "may produce a NullPointerExeption"

下面是我的应用程序的一些代码。我需要帮助的部分在 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));
         }
      });
   }
   ...
}

我只想确保 SettingsFragment class 中的 requireActivity() 不会抛出 nullpointerexeption。你能帮我查一下吗?

需要Activity()

如果 Activity 由于任何原因为 null,

可以抛出 null。 我相信如果用户存在该应用程序或强制停止它等,它可以为空。或者在您所在的上下文中从未创建过一个

试一试

Activity activity;
try {
    activity = requireActivity()
    editText.setBackground(
        ContextCompat.getDrawable(
            activity.getApplicationContext(),
            R.drawable.fondo_edittextpreference));
} catch (NullPointerException orTypeOfException) {
    //handle here when the activity is null
}

您可以执行以下任一操作而不是 requireActivity().getApplicationContext()

  1. editText.setBackground(ContextCompat.getDrawable(editText.getContext(), R.drawable.fondo_edittextpreference))
  2. editText.setBackgroundResource(R.drawable.fondo_edittextpreference)