如何使用Kotlin修复此错误,找不到Fragment构造函数? [英] How to fix this bug using Kotlin,could not find Fragment constructor?

查看:1060
本文介绍了如何使用Kotlin修复此错误,找不到Fragment构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Kotlin开发Android应用程序.在我的应用程序包含TabViewPager的情况下,我实现了两个选项卡.当我移至另一个活动并完成选项卡视图活动时,该应用程序将停止并停止logcat在错误下方显示.

I am developing Android app using Kotlin.In my app contains Tab with ViewPager so i implement the two tabs.when i move to another activity and compack to tab view activity the app getting fource stop and the logcat shows below the error.

java.lang.RuntimeException:无法启动活动ComponentInfo {com.crypto.wallet/com.crypto.wallet.activities.MainActivity}:android.support.v4.app.Fragment $ InstantiationException:无法实例化片段com. crypto.wallet.activities.ReceiveFragment:找不到Fragment构造子

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.crypto.wallet/com.crypto.wallet.activities.MainActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.crypto.wallet.activities.ReceiveFragment: could not find Fragment constructor

MyFragment.kt

@SuppressLint("ValidFragment")
class ReceiveFragment(private val transactionList: List<TransactionEntity>, val appDatabase: AppDatabase, private val direction: TransactionAdapterDirection,
                      val networkDefinitionProvider: NetworkDefinitionProvider) : Fragment(){

    private var linearLayoutManager: LinearLayoutManager? = null

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

    }

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

        val rootView = inflater.inflate(R.layout.receive_fragment, container, false)
        val recyclerView = rootView.findViewById<RecyclerView>(R.id.transaction_recycler_in) as RecyclerView
        linearLayoutManager = LinearLayoutManager(getActivity(), LinearLayout.VERTICAL, false)
        recyclerView.layoutManager = linearLayoutManager
        recyclerView.adapter = TransactionRecyclerAdapter(transactionList,appDatabase,direction,networkDefinitionProvider)
        recyclerView.setHasFixedSize(true);
        return rootView
    }
}

ViewPager.kt

override fun getItem(position: Int): Fragment? {
        var fragment: Fragment? = null
        when (position) {
            //0 -> fragment = ReceiveFragment(MytransactionList,MyappDatabase,Myincoming,MynetworkDefinitionProvider)
            0 -> fragment = ReceiveFragment(MyIT,MyAppDatabase,MyIncoming,MyNetwork)
            1 -> fragment = SendFragment()
        }

        return fragment
    }

Main.kt OnCreate()

Main.kt OnCreate()

val viewPager = findViewById<ViewPager>(R.id.viewpager)
                if (viewPager != null) {
                    val adapter = ViewPagerAdapter(supportFragmentManager,it,appDatabase,INCOMING,networkDefinitionProvider)
                    viewPager.adapter = adapter
                }

 val pref = applicationContext.getSharedPreferences("MyPref", 0) // 0 - for private mode
                val editor = pref.edit()
                val gson = Gson()
                val json = gson.toJson(it)
                editor.putString("MyObject", json)
                editor.apply()

OnResume()

val prefs = applicationContext.getSharedPreferences("MyPref", 0)
        val gson = Gson()
        val json = prefs.getString("MyObject", "")
        val person1: List<TransactionEntity> = gson.fromJson(json, ArrayList<TransactionEntity>()::class.java)

更新: 在我尝试了这个之后,我得到了同样的错误(我尝试了Bundle和Shared pref):

UPDATE: After i tried this i get same error(i tried both Bundle and Shared pref):

companion object {
        @JvmStatic
        fun newInstance(myIT: List<TransactionEntity>, myAppDatabase: AppDatabase, myIncoming: TransactionAdapterDirection,
                        myNetwork: NetworkDefinitionProvider,
                        bundle: Bundle) =
                ReceiveFragment(myIT, myAppDatabase, myIncoming, myNetwork,bundle).apply {
                    arguments = Bundle().apply {
                       /* val prefs = getActivity()!!.getApplicationContext().getSharedPreferences("myPrefs", 0)
                        val gson = Gson()
                        val json = prefs.getString("MyObject", "")
                        val person1: List<TransactionEntity> = gson.fromJson(json,
                                ArrayList<TransactionEntity>()::class.java)
                        Log.d("Karthi", "Frag-GSON " + person1)*/

                        val dd = bundle.getSerializable("MySerializable")
                        Log.d("Karthi", "Frag-GSON " + dd)
                    }
                }
    }

Main.kt:

val bundle = Bundle()
                val gson_budle = Gson()
                val json_bundle = gson_budle.toJson(it)
                bundle.putSerializable("MySerializable", json_bundle)

                val sharedPreferences = getSharedPreferences(myPreferences, Context.MODE_PRIVATE)
                val editor = sharedPreferences.edit()
                val gson = Gson()
                val json = gson.toJson(it)
                editor.putString("MyObject", json)
                editor.putString("MyObject_json_bundle", json_bundle)
                Log.d("Karthi","After - IT" + json)
                Log.d("Karthi","After - IT" + json_bundle)
                editor.apply()

致命异常:主要 流程:com.crypto.wallet,PID:29313 java.lang.RuntimeException:无法启动活动ComponentInfo {com.crypto.wallet/com.crypto.wallet.activities.MainActivity}:android.support.v4.app.Fragment $ InstantiationException:无法实例化片段com.crypto.wallet .activities.ReceiveFragment:找不到Fragment构造函数 在android.support.v4.app.FragmentController.restoreAllState(FragmentController.java:152) 在android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:330) 在android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:84) 在com.crypto.wallet.activities.MainActivity.onCreate(MainActivity.kt:194)

FATAL EXCEPTION: main Process: com.crypto.wallet, PID: 29313 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.crypto.wallet/com.crypto.wallet.activities.MainActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.crypto.wallet.activities.ReceiveFragment: could not find Fragment constructor at android.support.v4.app.FragmentController.restoreAllState(FragmentController.java:152) at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:330) at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:84) at com.crypto.wallet.activities.MainActivity.onCreate(MainActivity.kt:194)

推荐答案

当您获得对该错误的简短描述时,您会看到:

When you get short description over the error you will see :

避免在片段中使用非默认构造函数:使用默认构造函数加Fragment setArguments(Bundle)代替. 从Fragment文档中:

Avoid non-default constructors in fragments: use a default constructor plus Fragment setArguments(Bundle) instead less. From the Fragment documentation:

每个片段都必须有一个空的构造函数,因此可以在恢复其活动状态时实例化它.强烈建议子类不要使用带有参数的其他构造函数,因为在重新实例化片段时将不会调用这些构造函数;取而代之的是,参数可以由调用方使用setArguments(Bundle)提供,然后由Fragment使用getArguments()检索.

Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments().

例如:

 fun newInstance(bundle : Bundle) : ReceiveFragment{
        val fragment = ReceiveFragment()
         fragment.arguments=bundle           
        return fragment
    }

现在调用片段:

 0 -> fragment = ReceiveFragment.newInstance(new Bundle)

更多信息: http://developer.android.com /reference/android/app/Fragment.html#Fragment()

这篇关于如何使用Kotlin修复此错误,找不到Fragment构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆