我想在片段中實現SharedPreferences。我正在嘗試顯示登錄用戶的詳細信息。但是,我無法在帳戶Fragment上顯示它。在MainActivity中顯示SharedPreferences時沒有問題。我正在尋找一個解決方案,以便如何迎合代碼,以便它能夠在一個片段中工作。片段中的SharedPreferences
MainActivity.java
if(!SharedPrefManager.getInstance(this).isLoggedIn()){
finish();
startActivity(new Intent(this, LoginActivity.class));
}
textviewUsername = (TextView)findViewById(R.id.usernameLabel);
textviewUsername.setText(SharedPrefManager.getInstance(this).getUsername());
在這種AccountFragment我試圖顯示帳戶細節。
AccountFragment.java
public class AccountFragment extends Fragment {
private TextView textViewUsername, textViewEmail, textViewFirstName, textViewLastName;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_account, container, false);
if(!SharedPrefManager.getInstance(getContext()).isLoggedIn()) {
startActivity(new Intent(getContext(), LoginActivity.class));
}
textViewUsername = (TextView) getView().findViewById(R.id.editTextUsername);
textViewEmail = (TextView) getView().findViewById(R.id.editTextEmail);
textViewFirstName = (TextView) getView().findViewById(R.id.editTextFirstName);
textViewLastName = (TextView) getView().findViewById(R.id.editTextLastName);
textViewUsername.setText(SharedPrefManager.getInstance(getActivity()).getUsername());
textViewEmail.setText(SharedPrefManager.getInstance(getActivity()).getEmail());
textViewFirstName.setText(SharedPrefManager.getInstance(getActivity()).getFirstName());
textViewLastName.setText(SharedPrefManager.getInstance(getActivity()).getLastName());
}