如何解决活动重新启动和片段重新创建时视图绑定空指针异常

How to solve view binding null pointer exception when activity restarts and fragment recreates

提问人:Abimbola Michael 提问时间:12/28/2021 最后编辑:Abimbola Michael 更新时间:1/2/2022 访问量:3691

问:

每当我的MainActivity由于暗模式的更改而重新启动时,我尝试单击我得到nullpointer异常。 错误如下

我有一个BaseFragment

lateinit var mContext:Context
lateinit var mActivity:Activity
var myId = ""

val firebaseMethods: FirebaseMethods by lazy { FirebaseMethods(requireActivity()) }

override fun onDestroy() {
    super.onDestroy()
    removeListeners()
}
override fun onAttach(context: Context) {
    super.onAttach(context)
    showLogI("onAttach")
}
override fun onDetach() {
    super.onDetach()
    showLogI("onDetach")
}
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    mContext = requireContext()
    mActivity = requireActivity()
    showLogI("onCreate")
    if(getCurrentUser() != null){
        myId = getCurrentUserId()
    }
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?)
: View {
    showLogI("onCreateView")
    val view = setContentView(inflater, container, savedInstanceState)
    return view
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    initView(view)
    setListener()
    initData()
}
protected abstract fun setContentView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?):View
protected abstract fun setListener()
protected abstract fun initData()

我还有一个PostFragment

var posts:ArrayList<Post> = arrayListOf()
var pgPosts:ArrayList<Post> = arrayListOf()
var ids:ArrayList<String> = arrayListOf()

val keys:ArrayList<String> = arrayListOf()
var totalSize = 0
var query: Query? = null

var postAdapter:PostAdapter? = null

var counter = 0
var adUnit = ""
var adminId = ""

override fun onDestroy() {
    super.onDestroy()
    postAdapter?.removeListeners()
    destroyAds()
}
private var _binding: FragmentPostBinding? = null
private val binding get() = _binding!!

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

override fun setContentView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    _binding = FragmentPostBinding.inflate(inflater, container, false)
    return binding.root
}

override fun setListener() {

}


override fun initData() {
    getArgs()
    toggleOrientation()
    showProgress()
    setAdapter()

    val spannableString = "No Internet Connection. Retry".createSpan("Retry"){ spannableString, start, end ->
        mContext.setSpan(spannableString, "click", start, end, R.color.green){readPosts()}
    }
   
    if (mContext.isConnectingToInternet()) readPosts() else hideProgressWithSpan(spannableString)

    adUnit = mContext.getString(R.string.ads_unit_video)
    firebaseMethods.getAdmin { admin->
        adminId = admin.admin_id
        //adUnit = admin.native_ads_unit
    }
}
fun changeLayout(orientation:String){
    this.orientation = orientation
    toggleOrientation()
    setAdapter()
}
fun toggleOrientation(){
    if (orientation == "big") {
        max = 5
        binding.recyclerview.lm()
    } else if (orientation == "small") {
        max = 15
        binding.recyclerview.lm("grid", 3)
    }
}

我得到这个空指针异常

E/AndroidRuntime:致命异常:main 进程:com.wh,PID:26862 java.lang.NullPointerException 在 com.wh.ui.fragment.post.PostFragment.getBinding(PostFragment.kt:101) 在 com.wh.ui.fragment.post.PostFragment.toggleOrientation(PostFragment.kt:160) 在 com.wh.ui.fragment.post.PostFragment.changeLayout(PostFragment.kt:154)

android-studio kotlin android-activity 绑定 nullpointerexception

评论

0赞 Tenfour04 12/29/2021
需要查看整个 Fragment 的代码。您访问该属性的时间为 null。假设您遵循在分离时将其设置为 null 的模式,则必须在分离 Fragment 时进行访问。binding_bindingbinding

答:

2赞 return 0 12/31/2021 #1

正如 @Tenfour04 所说,当片段被分离时,您正在访问绑定。您需要首先检查片段是否已添加

if(isAdded){
//do something with the binding
}
0赞 Abimbola Michael 1/2/2022 #2

多谢。我终于找到了解决方案。我正在检查我的底部导航视图片段的状态是否为 null,如果没有找到 fragmentbytag,请使用新片段是否为 null。我只是猜想在不检查状态的情况下创建片段,它起作用了。

评论

0赞 Community 1/2/2022
您的答案可以通过额外的支持信息得到改进。请编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好答案的更多信息。