[英]Calling method from another class in Activity returns null
I have 2 classes, the one is the Location and the second one the MainActivity, what i want to do is get the Latitude in the the Activity Class , using a method from the Location Class , below is the Location class : 我有2个类,一个是Location,第二个是MainActivity,我想要做的是使用Location Class中的方法获取Activity类中的Latitude,下面是Location类:
public class locac implements LocationListener {
public Context Ctx;
private final Context context;
public locac (Context context) {
this.context=Ctx;
}
public int GetLat() {
LocationManager manag;
manag=(LocationManager)Ctx.getSystemService(Ctx.LOCATION_SERVICE);
Location alfa=manag.getLastKnownLocation(manag.GPS_PROVIDER);
return (int) (alfa.getLatitude());
}
and here is the part of the MainActivity class 这是MainActivity类的一部分
locac nova=new locac(this.m);
int latitu=nova.GetLat();
Context m;
Toast.makeText(getApplicationContext(), latitu, Toast.LENGTH_LONG).show();
the error i get is: 我得到的错误是:
Caused by: java.lang.NullPointerException
at com.example.alarma.locac.GetLat(locac.java:71)
i guess the the Context returns null, but can't understand why 我猜Context返回null,但不明白为什么
PS PS
i am adding the full Activity class : 我正在添加完整的Activity类:
public class MainActivity extends Activity {
public static final String content="test";
public static final Integer kom=2;
Context m;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbadapter mkola=new dbadapter(MainActivity.this);
mkola.openToWrite();
locac nova=new locac(MainActivity.this);
int latitu=nova.GetLat();
Toast.makeText(getApplicationContext(),
latitu, Toast.LENGTH_LONG).show();
mkola.insert(content);
}
}
In your constructor, the line: 在你的构造函数中,行:
this.context=Ctx;
does nothing because Ctx
and this.context
refer both to the instance variables and hence are null
when you're creating your object (default value for an object). 什么也不做,因为Ctx
和this.context
引用了实例变量,因此在创建对象时(对象的默认值)为null
。
It should be : 它应该是 :
private final Context context; //remove this line
public Context Ctx;
public locac (Context context){
this.Ctx = context;
}
Also be aware that getLastKnownLocation
can also returns null
. 另请注意, getLastKnownLocation
也可以返回null
。
PS :Try to respect naming conventions. PS:尽量尊重命名约定。
I don't see any initializing for Ctx. 我没有看到任何Ctx的初始化。
public Context Ctx;
public locac (Context context){
this.context=Ctx;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.