【问题标题】:How do i read data to a fragment in kotlin? sharedpreferance如何将数据读取到 kotlin 中的片段?共享偏好
【发布时间】:2020-02-29 19:22:13
【问题描述】:

所以我将把我正在写入的一些数据写入活动中的文件,并且我希望它显示在我的第一个活动中的片段中。我对 Kotlin 很陌生,刚刚了解到我不能在框架中使用相同的语法。

我想使用共享偏好。

我的主要活动看起来像这样,并且工作正常:

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】:

    使用

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

    而不是 textView2.text = str textView2 也应该在您的 R.layout.fragment_frag1 内

    【讨论】:

    • findViewById 在片段中不起作用,但我解决了 textView 为空的问题。刚刚添加了 textView2?。现在的问题是我似乎无法将信息断言到 textView2 中。虽然没有错误
    猜你喜欢
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    相关资源
    最近更新 更多