[英]Android Studio null object reference when creating
I am creating the class object before using it to set a variable in the class but I still get the null reference error.我正在创建 class object,然后使用它在 class 中设置变量,但我仍然收到 null 引用错误。 Why is this happeing?为什么会这样?
public void onCreate() {
MainActivity ma = new MainActivity();
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if(ma.isWalking) {
Log.i("walk","walking");
}
You absolutely positively cannot create an Activity
like this:您绝对不能创建这样的Activity
:
MainActivity ma = new MainActivity();
Only the Android framework can instantiate Android components ( Activity
, Service
, etc.)只有Android框架可以实例化Android个组件( Activity
、 Service
等)
Just use public static
variables for this purpose which can be accessed from any class.为此,只需使用public static
变量即可,可以从任何 class 访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.