亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

什么是靜態上下文變量

什么是靜態上下文變量

喵喔喔 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 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號