0

I have activity and fragment. I get shared pref. in my fragment:

   private var dManager: DataManager?=null
   private lateinit var sp: SharedPreferences
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View?{
    val view = inflater.inflate(R.layout.fragment_test1_new_design, container, false)
    level = arguments!![Constants.LEVEL].toString()
    sp = activity!!.getSharedPreferences(Constants.APP_PREFERENCES, AppCompatActivity.MODE_PRIVATE)
    dManager = MyApp.gManager.getDataManager(sp,level,test)

And some times I get crash report that

lateinit property sp has not been initialized

I do not use sp before initialization, so it means activity!!.getSharedPreferences(Constants.APP_PREFERENCES, AppCompatActivity.MODE_PRIVATE) returns null. Is it means that activity has been destroyed?

If I check that sp == null, what should I do futher in fragment? Restart app or recreate activity? What is the right way?

Dima
  • 1,189
  • 1
  • 8
  • 12
  • 1
    show full code please – IntelliJ Amiya Sep 24 '19 at 10:20
  • if you are using `sp = activity!!.getSharedPreferences()` inside fragment then please don't use `activity/getActivity()` to get `Context` inside fragment because `activity/getActivity()` retuns `null` if the your `fragment` is not currently attached to a parent `activity` – AskNilesh Sep 24 '19 at 10:25
  • @NileshRathod is correct, but it should have crashed if the activity is `null` and not let the rest of the code block to execute due to the `!!`. Please share a bigger code snippet, is the initialization right before passing the sharedPreferences around? – Giorgos Neokleous Sep 24 '19 at 10:51
  • @Giorgos Neokleous I shared more code. There is no initialination before using sp. The crash happens in less than 0.5% cases. I think it can be connected with memory clearing, but I do not understand how to prevent this crash (what to do after checking sp and other lateinit properties) – Dima Sep 24 '19 at 11:18
  • @Nilesh Rathod Thanks, but what should I do instead? – Dima Sep 24 '19 at 11:19
  • @Dima try to get `context` inside `fragment` like this https://stackoverflow.com/a/52732620/7666442 – AskNilesh Sep 24 '19 at 11:21

1 Answers1

-1

One way to solve this would be calling:

if(!::sp.isInitialized) {
    sp = activity!!.getSharedPreferences(Constants.APP_PREFERENCES, AppCompatActivity.MODE_PRIVATE)
    dManager = MyApp.gManager.getDataManager(sp,level,test)
}

In the fragment onStart() method.

Razvan S.
  • 753
  • 7
  • 21