I stored values in SharedPreference and now I want to access all that in Fragment. When I tried to run my App, it crashed.
public class Credentials extends Fragment {
Button submit, change;
EditText user, id;
Context ctx;
Context context = getActivity();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View windows = inflater.inflate(R.layout.credential, container, false);
((TextView)windows.findViewById(R.id.textView)).setText("Credentials");
submit = ((Button)windows.findViewById(R.id.submit));
change = ((Button)windows.findViewById(R.id.change));
user = ((EditText)windows.findViewById(R.id.username));
id = ((EditText)windows.findViewById(R.id.Useremail));
SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
String username = "";
String email = "";
pref.getString("username", username);
pref.getString("email", email);
Toast.makeText(getActivity(), "Pressed", Toast.LENGTH_SHORT).show();
user.setText(username);
id.setText(email);
}
I have Created a Util Class for SharedPreference, Hope It will help you.
Now to store String Value: use below statement in your fragment
To get String Value: use below statement in your fragment
Same way you can store and retrieve any other value from any fragment or activity of your application.
There is problem with your receiving method.
So when you use
pref.getString()
method, you have to store return value to something.Try below example.