我如何将数据读取到Kotlin中的片段?共享的偏好设置

问题描述 投票:0回答:1

因此,我要在活动中获取一些要写入文件的数据,我希望它显示在我的第一个活动中的片段中。我对Kotlin还是很陌生,只是得知我不能在frament中使用相同的语法。

我想使用共享首选项。

我的主要活动看起来像这样,并且运作良好:

private lateinit var sharedPreferences: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)

        btnSaveEvent.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)

            // Create a shared preference instance
            sharedPreferences = getSharedPreferences("com.example.gifttracker", Context.MODE_PRIVATE)


            // create editor and add the key value pair to the preference
            val editor = sharedPreferences.edit()
            editor.putString("KEY_STR", editText2.text.toString())
            editor.apply()

            //Read from file into a Toast to check that it saved
            val str = sharedPreferences.getString("KEY_STR", null)
            Toast.makeText(this, str, Toast.LENGTH_LONG).show()

        }

    }

我的片段不是很好,看起来像这样:

private var sharedPreferences = this.activity!!.getSharedPreferences("com.example.gifttracker", Context.MODE_PRIVATE)

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

        // Inflate the layout for this fragment
        val view: View = inflater.inflate(R.layout.fragment_frag1, container, false)

        view.btnAddEvent.setOnClickListener {
            requireActivity().startActivity(
                Intent(requireActivity(), Main2Activity::class.java)
            )
        }

        val str = sharedPreferences.getString("KEY_STR", null)
        textView2.text = str

        return view
    }

** 注意,这会使我的应用程序崩溃 **这是由于textView2为null,我不知道为什么

我只想从我创建的文件中读取并列出它的列表

提前感谢

android android-fragments kotlin sharedpreferences
1个回答
0
投票

使用

val txt2 = view.findViewById(R.id.textView2)
txt2.text = str

而不是textView2.text = str同样,textView2也应位于R.layout.fragment_frag1

© www.soinside.com 2019 - 2024. All rights reserved.