How to store data in one fragment to get it in another fragment?

I am storing a string in my shared preference class and I want to use this String in another fragment.

I think I am doing something wrong with the Context, Application Context. I did not know about the context thing. Whenever I open my Profile Fragment the app crashes.

Shared Preference Class

public class SharedPrefs {
private static final String myPrefs = “myprefs”;
private static final String LogedInKey = “Key”;
private final Context context;
private final SharedPreferences sharedPreferences;
private final SharedPreferences.Editor editor;

public SharedPrefs(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(myPrefs, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();

public void savePref(String key) {
editor.putString(LogedInKey, key);

public String getLogedInKey() {
return sharedPreferences.getString(LogedInKey, null);

public void clearLogin() {
editor.putString(LogedInKey, null);
My Profile Fragment:

public class ProfileFragment extends Fragment {
private Context context;
private SharedPrefs sharedPrefs=new SharedPrefs(context);

public ProfileFragment(Context context) {
this.context = context;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, null);
TextView userName=view.findViewById(;
String a=sharedPrefs.getLogedInKey();

return view;

public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);


You might be getting a null pointer exception

As you can notice that you have declared a context but not initialised it and then passing it to the constructor of your shared preferences class, which is bound to give a null pointer exception.

Also from the title It seems that you are trying to sore the data of one fragment to pass it into another fragment, for this shared preferences is not the preferred approach.
It is better to use Inter-Fragment Communication

Basically what you do is you define an interface in your Fragment, and then your Activity can implement that interface. After that call the interface method in your Fragment, and your Activity will receive the event. In your activity, you can call your second Fragment to update the textview with the received value.

In your Activity that implements fragment

public void sendDetails(String text){
        // Get Fragment B
        FragmentB frag =getSupportFragmentManager().findFragmentById(;

Fragment A defines an Interface, and calls the method when needed:-

public interface TextClicked{
        public void sendDetails(String text);

Fragment B has a public method to do something with the text

public void updateDetails(String text){
        // Here you can use the detai;s