FATAL EXCEPTION: Fragment not attached to a context [Kotlin]

27 views Asked by At

I have a switch on menu and this id can change the app theme between dark and light mode, when the app is on the dark mode it is fine and it doesn't throw any errors even if I close it and open it again, but when I switch it to the light mode it throws an fatal exception that you can see down this post whenever I open the app when the light mode is on -- Please help I tried every thing but I couldn't solve it. Can someone please explain what am I doing wrong?

P.S. I am using firebase for the data

Thank you in advance

Error

FATAL EXCEPTION: main
                                                                                 Process: com.gazelle.wadifatk, PID: 5864
                                                                                                java.lang.IllegalStateException: Fragment LatestNewsFragment{a79f812} (b7f897aa-8ffa-476a-adcb-4201e0361c4e) not attached to a context.
                                                                                                    at androidx.fragment.app.Fragment.requireContext(Fragment.java:972)
                                                                                                    at com.gazelle.wadifatk.newsList.LatestNewsFragment$realTimeNewsDataBase$1.onDataChange(LatestNewsFragment.kt:124)
                                                                                                    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
                                                                                                    at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
                                                                                                    at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
                                                                                                    at android.os.Handler.handleCallback(Handler.java:883)
                                                                                                    at android.os.Handler.dispatchMessage(Handler.java:100)
                                                                                                    at android.os.Looper.loop(Looper.java:237)
                                                                                                    at android.app.ActivityThread.main(ActivityThread.java:8167)
                                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                                    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
                                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)

Main Activity

class MainActivity : AppCompatActivity() {


private lateinit var navController: NavController
private lateinit var sharedPreferences: SharedPreferences
private lateinit var  mySwitch : SwitchCompat
private lateinit var editor : Editor
private var isNightModeEnabled = false

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)


    sharedPreferences = getSharedPreferences("Mode", Context.MODE_PRIVATE)
    editor = sharedPreferences.edit()


    val nightMode = sharedPreferences.getBoolean("night", false)

    if(nightMode){
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
    }else{
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
    }



    val navHostFragment =
        supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
    navController = navHostFragment.navController
    val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)
    bottomNavigationView.setupWithNavController(navController)


    val myToolbar = findViewById<Toolbar>(R.id.myToolBar)
    setSupportActionBar(myToolbar)
    setupActionBarWithNavController(navController)
    //setupActionBar(my_toolbar)

}




override fun onSupportNavigateUp(): Boolean {
    return navController.navigateUp() || super.onSupportNavigateUp()
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.menu2, menu)
    val itemSwitch = menu!!.findItem(R.id.darkView)
    itemSwitch.setActionView(R.layout.use_switch)

    mySwitch = itemSwitch.actionView!!.findViewById(R.id.switchMode)
    val switchState = sharedPreferences.getBoolean("switchState", false)
    mySwitch.isChecked = switchState


    mySwitch.setOnCheckedChangeListener { _, isChecked ->

        isNightModeEnabled = isChecked
        editor.putBoolean("night", isNightModeEnabled)
        editor.putBoolean("switchState", isChecked)
        editor.apply()

        if (isNightModeEnabled){
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
        }else{
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

        }
    }

    return super.onCreateOptionsMenu(menu)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when(item.itemId){
       
    }

    val navController = findNavController(R.id.fragmentContainerView)
    return item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item)
}
}

LatestNewsFragment

class LatestNewsFragment : Fragment() {

private lateinit var newslist: ArrayList<NewsListViewModel>
private lateinit var mRef: DatabaseReference
private lateinit var recyclerView: RecyclerView
private lateinit var progress: ProgressBar
private lateinit var layout: LinearLayout
private lateinit var realm: Realm
private lateinit var overLoad: OverLoad
private lateinit var pendingIntent: PendingIntent

private var mInterstitialAd: InterstitialAd? = null


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val view = inflater.inflate(R.layout.fragment_latest_news, container, false)

    return view
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)



    recyclerView = view.findViewById(R.id.newsList)
    recyclerView.layoutManager = LinearLayoutManager(
        context,
        LinearLayoutManager.VERTICAL,
        false
    )

    newslist = arrayListOf()
    progress = view.findViewById(R.id.progress_news)
    layout = view.findViewById(R.id.progress_layout)

    realm = Realm.getDefaultInstance()
    overLoad = OverLoad(requireContext())
  //  frame = view.findViewById(R.id.myAd)

    interstitialAd()
    MobileAds.initialize(requireContext())

}



override fun onStart() {
    realTimeNewsDataBase()
    val refresh = view?.findViewById<SwipeRefreshLayout>(R.id.refresh_layout)

    refresh?.setOnRefreshListener(object : SwipeRefreshLayout.OnRefreshListener {

        @SuppressLint("NotifyDataSetChanged")
        override fun onRefresh() {
            recyclerView.adapter!!.notifyDataSetChanged()
            refresh.isRefreshing = false
        }

    })
    getAlarm()
    super.onStart()

}

fun realTimeNewsDataBase() {

    val shared = requireContext().getSharedPreferences("LatestNewsSaving", Context.MODE_PRIVATE)
    val editor = shared.edit()
    editor.apply()

    progress.visibility = View.VISIBLE
    val database = FirebaseDatabase.getInstance()
    mRef = database.getReference("LatestNews")

    mRef.addValueEventListener(object : ValueEventListener {

        override fun onDataChange(snapshot: DataSnapshot) {
            newslist.clear()
            if (snapshot.exists()) {
                for (list in snapshot.children) {
                    val data = list.getValue(NewsListViewModel::class.java)
                    newslist.add(0, data!!)
                    progress.visibility = View.GONE
                }
                //الكود الخاص لعرض اعلانات البينية بعد الضغط عدة مرات على الـ items

                val adapter = NewsListAdapter(
                    requireContext(), newslist,
                    onClick = {
                        //sharedpref
                        var counter = shared.getInt("count", 0)

                        if (counter > 3) {

                            if (mInterstitialAd != null) {
                                mInterstitialAd?.show(context as Activity)
                            } else {
                                Log.d("TAG", "The interstitial ad wasn't ready yet.")

                            }
                            //sharedpref
                            editor.remove("count").apply()

                            // passing data from adapter to second fragment
                            val passData = LatestNewsFragmentDirections
                                .actionLatestNewsFragmentToNewsDetailFragment(newslist[it])
                            Navigation.findNavController(requireView()).navigate(passData)

                        } else {
                            counter++
                            //sharedpref
                            editor.putInt("count", counter)
                            editor.apply()

                            // passing data from adapter to second fragment
                            val passData = LatestNewsFragmentDirections
                                .actionLatestNewsFragmentToNewsDetailFragment(newslist[it])
                            Navigation.findNavController(requireView()).navigate(passData)
                        }
                    })
                recyclerView.adapter = adapter
                recyclerView.adapter!!.notifyDataSetChanged()

            }
        }


        override fun onCancelled(error: DatabaseError) {
            Log.w(TAG, "onCancelled", error.toException())
            Toast.makeText(context, error.message, Toast.LENGTH_SHORT).show()
            progress.visibility = View.GONE
        }

    })


}


fun interstitialAd() {
    val interstitialAdId = getString(R.string.interstitialAdId)
    val adRequest = AdRequest.Builder().build()
    InterstitialAd.load(requireContext(), interstitialAdId, adRequest, object :
        InterstitialAdLoadCallback() {
        override fun onAdFailedToLoad(adError: LoadAdError) {
            Log.d(TAG, adError.message)
            mInterstitialAd = null
        }

        override fun onAdLoaded(interstitialAd: InterstitialAd) {
            Log.d(TAG, "Ad was loaded.")
            mInterstitialAd = interstitialAd
        }
    })
}
0

There are 0 answers