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

Kar*_*yan 3 android android-fragments kotlin

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

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

我的片段.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
    }
}
Run Code Online (Sandbox Code Playgroud)

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
    }
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

更新: 在我尝试这个之后,我得到了同样的错误(我尝试了 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)
                    }
                }
    }
Run Code Online (Sandbox Code Playgroud)

主.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()
Run Code Online (Sandbox Code Playgroud)

致命异常:主进程: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:在 android.support.v4.app.FragmentController.restoreAllState(FragmentController.java:152) 的 android.support.v4 上找不到 Fragment 构造函数.app.FragmentActivity.onCreate(FragmentActivity.java:330) 在 android.support.v7.app.AppCompatActivity。onCreate(AppCompatActivity.java:84) 在 com.crypto.wallet.activities.MainActivity.onCreate(MainActivity.kt:194)

Hem*_*mar 9

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

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

每个片段都必须有一个空的构造函数,以便在恢复其活动状态时可以实例化。强烈建议子类不要有其他带参数的构造函数,因为在重新实例化片段时不会调用这些构造函数;相反,参数可以由调用者提供setArguments(Bundle),然后由 Fragment with 检索getArguments()

例如 :

 fun newInstance(bundle : Bundle) : ReceiveFragment{
        val fragment = ReceiveFragment()
         fragment.arguments=bundle           
        return fragment
    }
Run Code Online (Sandbox Code Playgroud)

现在调用片段:

 0 -> fragment = ReceiveFragment.newInstance(new Bundle)
Run Code Online (Sandbox Code Playgroud)

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


Abd*_*wee 5

你能做的是创建一个零参数的默认构造函数

companion object {
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment LoginFragment.
     */
    // TODO: Rename and change types and number of parameters
    @JvmStatic
    fun newInstance(param1: String, param2: String) =
            ReceiveFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
// Or from your code, you can use Gson
   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)

            }
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它

   0 -> receiveFragment= ReceiveFragment.newInstance(firstParam, secondParam)
Run Code Online (Sandbox Code Playgroud)

你可以在以下位置接收这个参数onCreate

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    arguments?.let {
        email = it.getString(ARG_PARAM1)
        password = it.getString(ARG_PARAM2)

    }
  // Or from your code, you can use Gson
   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)
}
Run Code Online (Sandbox Code Playgroud)

你的片段构造函数是这样的

class ReceiveFragment: Fragment()
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助