Android 单例
Android Singleton
我在 android studio 创建的应用程序中遇到单例问题。
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<>();
}
}
当我在 Main aactivity 中调用 MyApplication 时,它给出了一个错误,具体为 null:
MyApplication myApplication = (MyApplication)getApplicationContext();
savedLocations = myApplication.getMyLocations();
savedLocations.add(currentLocation);
currentLocation 具有有效的 Location 值。
有什么提示吗?谢谢
myLocations
为空,因为您拼错了 onCreate
方法签名,实际上它从未被调用过。
你应该改变这个:
public void OnCreate() {
对此:
@Override
public void onCreate() {
这是您问题的解决方案,但老实说,您不应该那样做。请阅读应用程序架构并了解如何定义数据范围。在您的 android 应用程序 class 中使用单例数组在 99.99% 的情况下是错误的答案。
你必须像欧内斯特说的那样使用@Override public void onCreate(),并编写这段代码来获取应用程序实例并使用它。
import MyApplication;
public OtherClass {
public void otherMethod() {
MyApplication myApp = MyApplication.getInstance();
savedLocations = myApp.getMyLocations();
savedLocations.add(currentLocation);
}
}
我在 android studio 创建的应用程序中遇到单例问题。
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<>();
}
}
当我在 Main aactivity 中调用 MyApplication 时,它给出了一个错误,具体为 null:
MyApplication myApplication = (MyApplication)getApplicationContext();
savedLocations = myApplication.getMyLocations();
savedLocations.add(currentLocation);
currentLocation 具有有效的 Location 值。 有什么提示吗?谢谢
myLocations
为空,因为您拼错了 onCreate
方法签名,实际上它从未被调用过。
你应该改变这个:
public void OnCreate() {
对此:
@Override
public void onCreate() {
这是您问题的解决方案,但老实说,您不应该那样做。请阅读应用程序架构并了解如何定义数据范围。在您的 android 应用程序 class 中使用单例数组在 99.99% 的情况下是错误的答案。
你必须像欧内斯特说的那样使用@Override public void onCreate(),并编写这段代码来获取应用程序实例并使用它。
import MyApplication;
public OtherClass {
public void otherMethod() {
MyApplication myApp = MyApplication.getInstance();
savedLocations = myApp.getMyLocations();
savedLocations.add(currentLocation);
}
}