在android工作室创建的一个应用程序中,我对单例有一个问题。
Class MyApplication is created :
public class MyApplication extends Application { // code - freeCodeCamp.org
private static MyApplication singleton;
private List<Location> myLocations;
public List<Location> getMyLocations() {
return myLocations;
}
public void setMyLocations(List<Location> myLocations) {
this.myLocations = myLocations;
}
public MyApplication getInstance(){
return singleton;
}
public void OnCreate() {
super.onCreate();
singleton = this;
myLocations = new ArrayList<>();
}
}当我在主活动中调用MyApplication时,它会产生一个错误,即特定null:
MyApplication myApplication = (MyApplication)getApplicationContext();
savedLocations = myApplication.getMyLocations();
savedLocations.add(currentLocation);currentLocation有一个有效的位置值。有什么暗示吗?谢谢
发布于 2021-10-15 07:39:47
myLocations为null,因为您拼写错了onCreate方法签名,实际上从未调用它。
您应该改变这种情况:
public void OnCreate() {对此:
@Override
public void onCreate() {这是解决你的问题的办法,但老实说,你不应该那样做。请阅读应用程序架构,并了解如何定义数据的范围。在android应用程序类中使用单例数组在99.99%的情况下是错误的。
发布于 2021-10-15 07:56:17
您必须像Ernest那样使用@Override void onCreate(),并编写这段代码来获取应用程序实例并使用它。
import MyApplication;
public OtherClass {
public void otherMethod() {
MyApplication myApp = MyApplication.getInstance();
savedLocations = myApp.getMyLocations();
savedLocations.add(currentLocation);
}
}https://stackoverflow.com/questions/69581286
复制相似问题