Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...