猿问

什么是静态上下文变量

public Locator(Context mContext){

    getLocation();

    this.mContext = mContext;

}


public void setLatitude ( String lat ){

    this.latitude = lat;

}


public String getLatitude ( ){

    return latitude;

}


public void setLongitude ( String lon ){

    this.longitude = lon;

}


public String getLongitude ( ){

    return longitude;

}


public void getLocation ( ){

    LocationManager lm = (LocationManager)mContext.getSystemService ( Context.LOCATION_SERVICE ); 

    Location location = lm.getLastKnownLocation ( LocationManager.GPS_PROVIDER );

    longitude = String.valueOf(location.getLongitude());

    latitude = String.valueOf(location.getLatitude());

}


public static String getURL(){

    return "api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "APPID=" + APPID;

}

纬度和经度变量都给了我静态上下文错误以及调用函数。我试过让它们成为静态变量,但没有运气。有任何想法吗?


在我拥有的另一部分代码中,但无论我做什么,我都会在某处遇到静态上下文错误:


final String url = getApiUrlFromAreaId(areaId);


static String getApiUrlFromAreaId ( String areaId ){

    return URL + areaId;

}

不,我的编程达不到标准。请多多包涵


喵喔喔
浏览 156回答 2
2回答

一只名叫tom的猫

你得到了public static String getURL()这意味着可以在不使用类实例的情况下调用此方法。因此,该方法中使用的所有内容也必须是静态的(如果不作为参数传递)。我只能假设纬度、经度或 appId 都不是静态的。要么将它们设为静态,要么static从getUrl.

月关宝盒

假设latitudeandlongitude变量的声明如下所示:public class Locator{   private String latitude; //Notice this var is not static.   private String longitude; //Notice this var is not static.}并且您的目标是从另一个类中调用它,如下所示:Locator loc = new Locator(someContext);String url = loc.getURL();那么你必须将该getURL方法声明为非静态的,这意味着它可以在一个变量上调用,并且它在内部用于组成 URL的latitude和变量是所述实例的变量。longitude所以像这样声明它:public String getURL(){   return "api.openweathermap.org/data/2.5/weather?" +      "lat=" + latitude + //This instance's latitude      "&lon=" + longitude + //This instance's longitude      "APPID=" + APPID;}现在,另一方面,如果您打算这样称呼它:Locator loc = new Locator(someContext);String url = Locator.getURL(loc);然后注意这里getURL是类的静态方法,而不是类实例的方法。如果这是你的目标,那么声明getURL如下:public static String getURL(Locator loc){   return "api.openweathermap.org/data/2.5/weather?" +      "lat=" + loc.getLatitude() + //The latitude of instance loc      "&lon=" + loc.getLongitude() + //The longitude of instance loc      "APPID=" + APPID;}
随时随地看视频慕课网APP

相关分类

Java
我要回答