android - 如何使用 Kotlin 修复此错误,找不到 Fragment 构造函数?

标签 android android-fragments kotlin

我正在开发Android使用 Kotlin 的应用程序。在我的应用程序中包含 TabViewPager所以我实现了两个选项卡。当我移动到另一个 Activity 并压缩到选项卡 View Activity 时,应用程序会停止并logcat显示在错误下方。

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
    }

主.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):
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)
                    }
                }
    }

主要.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()

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)

最佳答案

当您获得有关错误的简短描述时,您将看到:

避免在 fragment 中使用非默认构造函数:使用默认构造函数加上 Fragment setArguments(Bundle)反而更少。
从 fragment 文档:

每个 fragment 都必须有一个空的构造函数,因此可以在恢复其 Activity 状态时对其进行实例化。强烈建议子类不要有其他带参数的构造函数,因为 fragment 重新实例化时不会调用这些构造函数;相反,调用者可以使用 setArguments(Bundle) 提供参数后来被 fragment 检索到 getArguments() .

例如 :

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

现在调用 fragment :
 0 -> fragment = ReceiveFragment.newInstance(new Bundle)

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

关于android - 如何使用 Kotlin 修复此错误,找不到 Fragment 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52268841/

相关文章:

java - 将多个输入打印为不同的纯文本 - Android Studio

java - Android Studio 中的多个根标签

java - 列表的 Kotlin Gson 自定义反序列化器

android - 继承 AppCompatButton 的正确方法是什么?

android - 如何使用暴力取消 AsyncTask

java - 随机生成形状和颜色并绘制到 Canvas 上

java - 将 parse api 连接到 android 滑动布局

android - 具有方向更改的单 Activity 应用程序中的 YouTubePlayerSupportFragment

Android studio Unresolved 懒惰引用(kotlin)

android - 我可以使用同一个 keystore 文件来签署两个不同的应用程序吗?