如何清除片段中的共享偏好?谢谢
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
sharedPreferences = getActivity().getSharedPreferences("login.conf", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.clear();
editor.commit();
Intent logout = new Intent(getActivity(), LoginActivity.class);
startActivity(logout);
Log.d(TAG, sharedPreferences.getString("username", ""));
Log.d(TAG, sharedPreferences.getString("password", ""));
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_logout, container, false);
}
我的片段
答案 0 :(得分:5)
您可以直接使用偏好设置名称并从任何地方清除它。
SharedPreferences preferences = getSharedPreferences("Mypref", 0);
preferences.edit().remove("shared_pref_key").commit();
或
SharedPreferences preferences = context.getSharedPreferences("Mypref", Context.MODE_PRIVATE);
preferences .edit().clear().commit();
答案 1 :(得分:1)
使用类似的东西:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_logout, container, false);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("login.conf", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
Intent logout = new Intent(getActivity(), LoginActivity.class);
startActivity(logout);
Log.d(TAG, sharedPreferences.getString("username", ""));
Log.d(TAG, sharedPreferences.getString("password", ""));
// Inflate the layout for this fragment
return view;
}