【问题标题】:shared preference in activity and fragment活动和片段的共同偏好
【发布时间】:2022-01-02 10:56:08
【问题描述】:

我正在通过共享首选项从活动中获取片段中的数据,但我无法执行该任务。

class ProfileFragment : Fragment() {

    lateinit var sharedPreference: SharedPreferences

    lateinit var txtName:TextView
    lateinit var txtEmail:TextView
    lateinit var txtMobileNo:TextView
    lateinit var txtAddress:TextView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_profile, container, false)

        sharedPreference = this.requireActivity().getSharedPreferences(getString(R.string.preference_file_name), Context .MODE_PRIVATE)

        txtName = view.findViewById(R.id.title)
        txtEmail = view.findViewById(R.id.Semail)
        txtMobileNo = view.findViewById(R.id.Smobile)
        txtAddress = view.findViewById(R.id.Sadress)

       txtName.setText(sharedPreference.getString("title", "default")).toString()
        txtName.setText(sharedPreference.getString("Email", "default")).toString()
        txtName.setText(sharedPreference.getString("Mobile", "default")).toString()
        txtName.setText(sharedPreference.getString("delivery", "default")).toString()

        return view
    }
}

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    您可以使用参数和可序列化的数据:

    data class UserDataUI(
        val title: String,
        val email: String,
        val mobile: String,
        val delivery: String
    ) : Serializable
    

    在你的片段中:

    companion object {
        private const val ARG_USER_DATA_UI = "ARG_USER_DATA_UI"
    
        fun newInstance(userDataUI: UserDataUI): ProfileFragment {
            val bundle = Bundle().apply {
                putSerializable(ARG_USER_DATA_UI, userDataUI)
            }
    
            return ProfileFragment().apply {
                arguments = bundle
            }
        }
    }
    

    您需要调用 Activity ProfileFragment.newInstance(yourData) 来获取 Fragment。

    并将数据提取到片段中:

    arguments!!.getSerializable(ARG_USER_DATA_UI) as UserDataUI
    

    使用 !!如果数据是强制性的,在这种情况下,永远不会为空

    【讨论】:

      【解决方案2】:

      尝试这样做

      @Override
      public void onAttach(Context context) {
          super.onAttach(context);
          SharedPreferences preferences = context.getSharedPreferences(getString(R.string.preference_file_name),Context .MODE_PRIVATE );
      }
      

      当您使用requireActivity() 时,如果片段未附加到活动,它会给出异常。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-29
        • 2016-11-19
        • 2016-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多