为了账号安全,请及时绑定邮箱和手机立即绑定

什么是静态上下文变量

什么是静态上下文变量

喵喔喔 2022-05-12 18:49:11
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;}不,我的编程达不到标准。请多多包涵
查看完整描述

2 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

你得到了

public static String getURL()

这意味着可以在不使用类实例的情况下调用此方法。因此,该方法中使用的所有内容也必须是静态的(如果不作为参数传递)。

我只能假设纬度、经度或 appId 都不是静态的。要么将它们设为静态,要么staticgetUrl.


查看完整回答
反对 回复 2022-05-12
?
月关宝盒

TA贡献1772条经验 获得超5个赞

假设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;

}


查看完整回答
反对 回复 2022-05-12
  • 2 回答
  • 0 关注
  • 155 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号