我想在片段中实现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());
}