java - 如何在不同的片段/活动中维护 android 中的会话?
问题描述
在使用 SharedPreferences 登录期间,我有这段用于会话管理的代码。该代码在登录期间运行良好,但是当我在另一个片段/活动中使用它时,它不再工作了。我收到错误“尝试在空对象引用上调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)'”。
有人可以帮助我正确调用 sessionmanagement 对象吗?这是我的代码
会话管理.java
public class SessionManagement {
//URL to our login.php file
public static final String LOGIN_URL = "http://10.0.2.2:63343/login-test-session/login.php?";
//Keys for email and password as defined in our $_POST['key'] in login.php
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";
//If server response is equal to this that means login is successful
public static final String LOGIN_SUCCESS = "success";
//Keys for Sharedpreferences
//This would be the name of our shared preferences
public static final String SHARED_PREF_NAME = "themoneygerapp";
//This would be used to store the email of current logged in user
public static final String EMAIL_SHARED_PREF = "email";
//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
费用视图.java(片段)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_expenses_view, container, false);
profiletest = (TextView) view.findViewById(R.id.txtProfileExpenses);
SharedPreferences sharedPreferences = getActivity().getApplicationContext().getSharedPreferences(SessionManagement.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String email = sharedPreferences.getString(SessionManagement.EMAIL_SHARED_PREF,"Not Available");
profiletest.setText("Expenses for user: " + email);
loadExpenses();
return view;
}
解决方案
推荐阅读
- node.js - 当我尝试使用 createReadStream 通过 apollo-server 上传文件时出现此错误,
- sql - Postgres 从 jsonb 数组中获取值匹配的所有元素
- vue.js - 在 Vue 中添加空格
- java - 在 Spring JPA 中使用 @ManyToOne 关系保存实体
- flutter - Flutter - 在小部件文本中放置一个 List[][]
- c# - WPF TreeView - XAML ContextMenu 可以基于属性有条件吗?
- javascript - 我的 JavaScript 排序代码有什么问题?
- php - NotBlank 不适用于嵌入式表单
- python - 我有 urls.py 模式错误
- html - 如何用 CSS 填补此表中的空白