Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

android - App crash after activity has been killed in background

i have an issue with an app that use ViewPager for display fragment. All works fine until the app goes in background and be killed from OS. It seems that after restore i have 2 IncidentScreenFragment that handle events, one with a null presenter (MVP) that crash my app.

My HomeActivity looks like:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
        presenter.onViewCreated()
        initViews(savedInstanceState)
    }

    private fun initViews(savedInstanceState: Bundle?){
        mapView.onCreate(savedInstanceState)
        mapView.getMapAsync(this)
        initFragment()
        initMenu()
    }
    private fun initFragment(){
        homeFragment = HomeScreenFragment.newInstance()
        incidentFragment = IncidentScreenFragment.newInstance()
        chatFragment = ChatFragment.newInstance()
        weatherFragment = WeatherFragment.newInstance()

        viewPager.adapter = ViewPagerAdapter(supportFragmentManager, this)
        viewPager.offscreenPageLimit = 4

        viewPager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {}
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
            override fun onPageSelected(position: Int) {bottom_navigation.currentItem = position}
        })
    }

    override fun getFragmentByPos(pos: Int): Fragment {
        return when(pos){
            0 -> homeFragment
            1 -> incidentFragment
            2 -> chatFragment
            3 -> weatherFragment
            else -> {
                homeFragment
            }
        }
    }

And my Adapter:

class ViewPagerAdapter internal constructor(fm: FragmentManager, activity:infinite_software.intelligence_center.intelligencecenter.ui.home.FragmentManager) : FragmentPagerAdapter(fm) {

    private val COUNT = 4
    private val activity = activity

    override fun getItem(position: Int): Fragment{
        var fragment: Fragment? = null
        when (position) {
            0 -> fragment = activity.getFragmentByPos(0)
            1 -> fragment = activity.getFragmentByPos(1)
            2 -> fragment = activity.getFragmentByPos(2)
            3 -> fragment = activity.getFragmentByPos(3)
        }

        return fragment!!
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        super.destroyItem(container, position, `object`)
    }

    override fun getCount(): Int {
        return COUNT
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return "Section " + (position + 1)
    }
}

Each Fragment have a static method that return new Fragment:

    companion object {
        fun newInstance(): HomeScreenFragment {
            return HomeScreenFragment()
        }
    }

When the app has been killed in background i figure out that there is 2 objects (Fragment) that listen to event, one with Presenter correctly instantiate and one without.

Below my abstract BaseFragment class:

abstract class BaseFragment<P : BasePresenter<BaseView>> : BaseView,Fragment() {
    protected lateinit var presenter: P

    override fun getContext(): Context {
        return activity as Context
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        presenter = instantiatePresenter()
    }

    override fun showError(error: String) {
        (activity as BaseActivity<BasePresenter<BaseView>>).showError(error)
    }

    override fun showError(errorResId: Int) {
        (activity as BaseActivity<BasePresenter<BaseView>>).showError(errorResId)
    }

    abstract fun onBackPressed(): Boolean

    /**
     * Instantiates the presenter the Fragment is based on.
     */
    protected abstract fun instantiatePresenter(): P
    abstract val TAG: String

Incident Fragment code:

class IncidentScreenFragment: BaseFragment<IncidentScreenPresenter>(), BaseView, IncidentView, AlertFilterListener, AlertItemClickListener, IncidentDetailListener {

    var rvAdapter : IncidentAdapter? = null

    var state : Int = LIST_STATE

    override fun instantiatePresenter(): IncidentScreenPresenter {
        return IncidentScreenPresenter(this)
    }

    override val TAG: String
        get() = "INCIDENT"

    override fun getContext(): Context {
        return activity as Context
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater.inflate(R.layout.fragment_incident, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        presenter.onViewCreated()
        initObserve()
    }

    private fun initViews(){
        //Reclycler view
        alertRV.layoutManager = LinearLayoutManager(context)
        rvAdapter = IncidentAdapter(ArrayList(), context, this)
        alertRV.adapter = rvAdapter

        //Apply Listeners
        headerBox.setFilterListener(this)
        incidentDetailView.setListener(this)
    }

    override fun initObserve() {
        //Init observe presenter model
        val alertObserver = Observer<ArrayList<AlertModel>> { alerts ->
            Timber.d("Data received from Presenter [$alerts]")
            showAlertList(alerts)
        }
        presenter.filteredAlertList.observe(context as BaseActivity<BasePresenter<BaseView>>,alertObserver)
    }

    override fun updateThisFilters(boxState: Boolean, level: Int) {
        presenter.updateFilterList(boxState,level)
    }

    fun showOnlyThisLevel(level:Int){
        presenter.showOnlyThisLevel(level)
        headerBox.disableBoxExcept(level)
    }

    fun showAlertList(list: ArrayList<AlertModel>){
        rvAdapter?.updateData(list)
    }

    override fun onItemClick(model: AlertModel) {
        presenter.loadAlertDetail(model)
    }

    override fun showAlertDetail(model: AlertModel) {
        incidentDetailView.setUpFromModel(model)
        WhiteWizard.slideLeftEffect(incidentDetailView,incidentListRootElement)
        state = DETAIL_STATE
    }

    override fun onbackFromDetailPressed() {
        WhiteWizard.slideRightEffect(incidentListRootElement,incidentDetailView)
        state = LIST_STATE
    }

    override fun showLoader() {
        loaderIncident.visibility = View.VISIBLE
    }

    override fun hideLoader() {
        loaderIncident.visibility = View.INVISIBLE
    }

    override fun onBackPressed(): Boolean {
        when(state){
            LIST_STATE -> return false
            DETAIL_STATE -> {
                onbackFromDetailPressed()
                return true
            }
            else -> return false
        }
    }

    fun newInstance(): IncidentScreenFragment {
            return  IncidentScreenFragment()
    }

}

When i click on the button in homePage to display fragment content i got:

 Process: XXXXXX, PID: 3192
    kotlin.UninitializedPropertyAccessException: lateinit property presenter has not been initialized
        at infinite_software.intelligence_center.intelligencecenter.base.BaseFragment.getPresenter(BaseFragment.kt:11)
        at XXXXXX.ui.home.incidentScreen.IncidentScreenFragment.showOnlyThisLevel(IncidentScreenFragment.kt:78)
        at XXXXXX.ui.home.HomeActivity.filterDataWithSeverity(HomeActivity.kt:110)
        at XXXXXX.ui.home.homeScreen.HomeScreenFragment.filterBy(HomeScreenFragment.kt:76)
        at XXXXXX.ui.home.homeScreen.HomeScreenFragment$initViews$5.onClick(HomeScreenFragment.kt:56)

If i try to print the id of Fragment, i obtain 2 different ids from method call showOnlyThisLevel() and onBackPressed(). What i miss ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After doing some research, it seems that the problem stems from the misnaming of FragmentPagerAdapter's method - being named getItem(), but not clearly specifying that the abstract method getItem(int position) is supposed to return a new instance of a fragment rather than just "get an instance of one".

Of course, there is not much we can do about an incorrect name after it's been out in the wild for 7 years, but at least we can fix the bug that stems from this issue in your code ;)


Without further ado, the cause of your NPE is that onCreateView (where your Presenter is instantiated) is never called.

This happens because you are creating the fragment here:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_main)
    ...
    homeFragment = HomeScreenFragment.newInstance()
    incidentFragment = IncidentScreenFragment.newInstance()
}

You return this fragment from inside getItem(int position) in your FragmentPagerAdapter:

override fun getItem(position: Int): Fragment = when(position) {
     ...
     1 -> activity.incidentFragment
     ...
}

So what we know about activity.incidentFragment is that in it, onCreateView() is never called.

This is caused by the fact that it's never actually added to a FragmentManager and never displayed on the screen.

That's because super.onCreate(savedInstanceState) in Activity recreates all Fragments, using their no-args constructor, via reflection, while keeping their tag (see findFragmentByTag).

So as you can see in this answer, or as I can quote here:

    // Do we already have this fragment?
    String name = makeFragmentName(container.getId(), itemId);
    Fragment fragment = mFragmentManager.findFragmentByTag(name);
    if (fragment != null) {
        if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
        mCurTransaction.attach(fragment);
    } else {
        fragment = getItem(position);
        if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);
        mCurTransaction.add(container.getId(), fragment,
                makeFragmentName(container.getId(), itemId));

The getItem(position) method is only called if the Fragment is not found by the fragment tag that the FragmentPagerAdapter sets for the fragment, which IS automatically recreated after low memory condition kills your app.

Therefore, YOUR new fragment (that you create by hand in the Activity) is NEVER used, and therefore it has no view, never initialized, never added to FragmentManager, it's not the same instance as what's actually inside your ViewPager, and it crashes when you call it. Boom!



Solution is to instantiate the Fragment inside FragmentPagerAdapter's getItem(position) method. To get an instance of the fragment, use this answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...