gpt4 book ai didi

java - 处理字符串空指针异常,即使在检查 !null 后也是如此

转载 作者:行者123 更新时间:2023-12-01 18:35:29 26 4
gpt4 key购买 nike

我经常崩溃

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 还显示方法调用 .toString 可能会产生 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,我还可以检查什么?

最佳答案

您正在检查 savedInstance 是否为零,但对 getCharSequence(KEY_LOCATION_NAME) 的结果调用 toString 方法却没有已进行 null 检查。

你应该尝试这样的事情

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

关于java - 处理字符串空指针异常,即使在检查 !null 后也是如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60064008/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com