【问题标题】:handle toString NullPointException, even after checking for !null处理字符串空指针异常,即使在检查 !null 之后也是如此
【发布时间】:2020-02-04 19:04:10
【问题描述】:

我经常崩溃

Fatal Exception: java.lang.RuntimeException
Unable to start activity ComponentInfo{com.example.phocast/com.example.phocast.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference

AndroidStudio 也显示Method invocation .toString may produce NullPointException

我的代码是:

public class SunFragment extends Fragment {

  ArrayList<Object> sunsList;
  Typeface sunfont;
  Double Dlat;
  Double Dlang;

  private AdView mAdView;

  //to be called by the MainActivity
  public SunFragment() {
    // Required empty public constructor
  }

  private static final String KEY_LOCATION_NAME = "location_name";
  public String TAG = "SunFragment";
  public String location;//="No location name found";

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
      location = savedInstanceState.getCharSequence(KEY_LOCATION_NAME).toString();
      } else {
      location = "";
    }
  }

既然我已经在检查savedInstanceState,我还能检查什么?

【问题讨论】:

  • savedInstanceState 上调用.getCharSequence(KEY_LOCATION_NAME) 似乎返回null。
  • savedInstanceState.getCharSequence(KEY_LOCATION_NAME) 为空。对整个表达式进行空检查。
  • 是的,但我已经尝试检查该字符序列是否也不为空,并且没有任何变化

标签: java android nullpointerexception


【解决方案1】:

您正在检查 savedInstance 是否为 nil,但在未检查为空的 getCharSequence(KEY_LOCATION_NAME) 的结果上调用 toString 方法。

你应该试试这样的

if (savedInstance != null && savedInstance.getCharSequence(KEY_LOCATION_NAME) != null)
   location = savedInstance.getCharsequence(KEY_LOCATION_NAME).toString()

【讨论】:

    【解决方案2】:

    也许你没有在 bundle 上设置成功 charSecuence。

    应该是这样的:

        @Override
        protected void onSaveInstanceState(final Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putCharSequence(KEY_LOCATION_NAME, location);
        }
    

    如果你实现protected void onSaveInstanceState(final Bundle outState, PersistableBundle outPersistentState),请小心,这是一种不同的方法!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-24
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2015-07-15
      • 1970-01-01
      相关资源
      最近更新 更多