处理toString NullPointException,即使在检查!null之后也是如此

时间:2020-02-04 19:04:10

标签: java android nullpointerexception

我经常因

崩溃
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,所以我还能检查什么?

2 个答案:

答案 0 :(得分:0)

您要检查savedInstance是否为nil,但要对尚未进行空检查的toString的结果调用getCharSequence(KEY_LOCATION_NAME)方法。

您应该尝试这样的事情

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

答案 1 :(得分:0)

也许您没有将成功charSecuence设置为bundle。

应该是这样的:

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

请注意,如果您实现protected void onSaveInstanceState(final Bundle outState, PersistableBundle outPersistentState)是另一种方法!