Home > Mobile >  shared preference in activity and fragment
shared preference in activity and fragment

Time:01-03

I m fetching the data in fragment from activity through shared preferences but Im not able to perform that task.

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
    }
}

CodePudding user response:

You could use the arguments and a serializable data:

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

And in your fragment:

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
        }
    }
}

You need to call in the Activity ProfileFragment.newInstance(yourData) to fetch the Fragment.

And to fetch the data into the fragment:

arguments!!.getSerializable(ARG_USER_DATA_UI) as UserDataUI

Use the !! if the data is mandatory, in this case, never will be null

CodePudding user response:

Try to do like this

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

When you use requireActivity() it can give an exception if the fragment is not attached to the activity.

  • Related