Why can't I call a Static method from another class which contains a Toast?

故事扮演 提交于 2019-12-11 15:04:11

问题


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(); 

        }

    }


来源:https://stackoverflow.com/questions/15438473/why-cant-i-call-a-static-method-from-another-class-which-contains-a-toast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!