【发布时间】: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