【发布时间】:2015-02-06 10:02:04
【问题描述】:
嗨,我的 android 项目是
- 提供纬度和经度的 GPSTracker.java 类
- 从地址 API 获取 JSON 的 RemoteFetch.java 类处于静态状态
-
一个 MainActivity.java 但是获取 json 的 url 是这样的:
私有静态最终字符串 OPEN_WEATHER_MAP_API = “http://api.openweathermap.org/data/2.5/weather?” + "q=%s&" +"lat="+"&lon=" + "&units=metric";
我的纬度和经度在 GPSTracker 中,但是当我获取它们时,它不会让我获取这些值,因为它们不是静态格式...
所以一旦我将它们添加到我的 openweatherapi 网址中,我就会遇到错误:
“不能从静态上下文引用非静态字段”。
有没有办法将字符串/int 格式“转换”为静态格式??
如果您需要更多信息,请告诉我。
这里有一些代码
private void updateWeatherData(final String city){
new Thread(){
public void run(){
final JSONObject json = RemoteFetch.getJSON(MainActivity.this,city);
if(json == null){
handler.post(new Runnable(){
public void run(){
Toast.makeText(MainActivity.this.getApplicationContext(),R.string.place_not_found,Toast.LENGTH_LONG).show();
}
});
} else {
handler.post(new Runnable(){
public void run(){
renderWeather(json);
}
});
}
}
}.start();
}
在 RemoteFetch.java 中
private static final String OPEN_WEATHER_MAP_API =
"http://api.openweathermap.org/data/2.5/weather?" + "q=%s&" +"lat="+"&lon=" + "&units=metric";
public static JSONObject getJSON(Context context, String city){
try {
// gps.getLatitude();
URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key",
context.getString(R.string.open_weather_maps_app_id));
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
【问题讨论】:
-
你能把你的 GPSTracker 类获取坐标的方法改成静态的吗?