gpt4 book ai didi

java - 从 Activity 中的另一个类调用方法返回 null

转载 作者:行者123 更新时间:2023-12-02 06:17:57 25 4
gpt4 key购买 nike

我有2个类,第一个是Location,第二个是MainActivity,我想要做的是使用Location类中的方法获取Activity类中的纬度,下面是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());
}

这是 MainActivity 类的一部分

locac nova=new locac(this.m);
int latitu=nova.GetLat();
Context m;
Toast.makeText(getApplicationContext(), latitu, Toast.LENGTH_LONG).show();

我得到的错误是:

Caused by: java.lang.NullPointerException
at com.example.alarma.locac.GetLat(locac.java:71)

我猜 Context 返回 null,但不明白为什么

附注

我正在添加完整的 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);










}



}

最佳答案

在你的构造函数中,行:

this.context=Ctx;

不执行任何操作,因为 Ctxthis.context 都引用实例变量,因此在创建对象时为 null (对象的默认值)。

应该是:

private final Context context; //remove this line
public Context Ctx;


public locac (Context context){
this.Ctx = context;
}

另请注意,getLastKnownLocation 也可以返回 null

P.S:尽量尊重命名约定。

关于java - 从 Activity 中的另一个类调用方法返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21283303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com