Why can't I call a Static method from another

2019-09-08 15:49发布

问题:

Before posting this I did my research, but I am struggling to understand exactly what the issue is. So here is my method in class 1:

public static void scan() {
    for( int j=0; j< objarray.size();j++)
    {

        locationB.setLatitude(objarray.get(j).getlat());
        locationB.setLongitude(objarray.get(j).getlon());

        float distance = locationA.distanceTo(locationB);

        if((distance < 600)&&(distance > 0.0) )
        {
            Toast.makeText(getApplicationContext(),"You can go to" +objarray.get(j).gettitle(),Toast.LENGTH_SHORT).show(); 

        }

    }

Everything in this method is Static, and the only thing giving me an error is the Toast.makeText call. Do I need to pass something to class1 which contains the scan method?

Like this:

Class1.Scan(something);

I think this may have something to do with the getApplicationContext() within the Toast, but I am unsure exactly what I need to do in order to fix this problem. Any explanation is appreciated!

回答1:

Do I need to pass something to class1 which contains the scan method?

Yes, you will need to pass current Activity context to Scan method for showing Toast instead of calling directly getApplicationContext() method in Class1 (from non Activity class). change Scan method as :

public static void Scan(Context context) {
   //...your code here....
    Toast.makeText(context,"You can go to"  
                  +objarray.get(j).gettitle(),Toast.LENGTH_SHORT).show(); 

    }


回答2:

Have you tried passing the application context to the method? Class1.Scan(getApplicationContext())

public static void scan(Context context) {
    for( int j=0; j< objarray.size();j++)
    {

        locationB.setLatitude(objarray.get(j).getlat());
        locationB.setLongitude(objarray.get(j).getlon());

        float distance = locationA.distanceTo(locationB);

        if((distance < 600)&&(distance > 0.0) )
        {
            Toast.makeText(context,"You can go to" +objarray.get(j).gettitle(),Toast.LENGTH_SHORT).show(); 

        }

    }