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);
editor.commit();
}
public String getLogedInKey() {
return sharedPreferences.getString(LogedInKey, null);
}
public void clearLogin() {
editor.putString(LogedInKey, null);
editor.commit();
}}
My Profile Fragment:
public class ProfileFragment extends Fragment {
private Context context;
private SharedPrefs sharedPrefs=new SharedPrefs(context);
public ProfileFragment(Context context) {
this.context = context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, null);
TextView userName=view.findViewById(R.id.userName);
String a=sharedPrefs.getLogedInKey();
userName.setText(a);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}}