Home > front end >  How to solve view binding null pointer exception when activity restarts and fragment recreates
How to solve view binding null pointer exception when activity restarts and fragment recreates

Time:01-02

Anytime my MainActivity restarts because of changing of dark mode and i try to click i get nullpointer exception. The error is below

I have a 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()

I also have a 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)
    }
}

I get this null pointer exception

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.wh, PID: 26862 java.lang.NullPointerException at com.wh.ui.fragment.post.PostFragment.getBinding(PostFragment.kt:101) at com.wh.ui.fragment.post.PostFragment.toggleOrientation(PostFragment.kt:160) at com.wh.ui.fragment.post.PostFragment.changeLayout(PostFragment.kt:154)

CodePudding user response:

As @Tenfour04 has said , you're accessing the binding when the fragment has been detached. You need to first check if the fragment has been added like so

if(isAdded){
//do something with the binding
}

CodePudding user response:

Thanks a lot. I finally found the solution. I was checking if state is null for my bottom navigation view fragments and if null using new fragment, if not finding fragmentbytag. I just guessed to create the fragment without checking state and it worked.

  • Related