在许多类(Activity、Fragment、Adapter、...)中,我需要访问对象。
所以我进入了应用程序类。(应用程序,用户)
主应用程序.java
private static MainApplication singleton;
public static MainApplication getApplication() {
return singleton;
}
@Override
public void onCreate() {
super.onCreate();
singleton = this;
}
private UserVo user; // I did not put null value
public UserVo getUser()(...)
public void setUser(UserVo user){...} // Called in LoginActivity
ActivityA.java、ActivityB.java、ActivityC.java
UserVo user;
@Override
public void onCreate(Bundle savedInstanceState) {
//...
app = ((MainApplication) getApplicationContext());
// or app = MainApplication.getApplication();
user = app.getUser(); // Always Not Null
//...
}
@Override
public void onResume() {
user.getData(); // Sometimes NullPointerExeception By GC (Maybe?)
}
如何防止空指针异常?
我想了几个主意。但是我不确定它们是否可以解决...
1.将MainApplication中的UserVo用户改为静态成员
像这样(MainApplication.java)
private static UserVo user;
public static UserVo getUser()(...)
2. 调用 getUser() 不使用 UserVo Memeber
像这样(Activity.java)
@Override
public void onResume() {
MainApplication.getApplication().getUser().getData();
}
3.制作界面(很复杂......我不想这样做)
像这样(MainApplication.java)
interface OnUser {
void onUser(UserVo user);
}
public void getUser(OnUser onUser) {
if (user == null)
// Start Login Activity, and receive UserVo from Server.
else
onUser.onUser(user);
}
(活动.java)
@Override
public void onResume() {
MainApplication.getApplication().getUser(new OnUser() {
void onUser(UserVo user) {
//Do Work.
}
});
}
请给我一些提示。