简体   繁体   中英

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 :

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

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

PS

i am adding the full Activity class :

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).

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 .

PS :Try to respect naming conventions.

I don't see any initializing for Ctx.

public Context Ctx;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM