Java 从类到活动获取价值?
有人能帮忙吗。当我想在另一个活动中获得温度时,我得到的值为0。 在Java 从类到活动获取价值?,java,android,android-activity,android-volley,Java,Android,Android Activity,Android Volley,有人能帮忙吗。当我想在另一个活动中获得温度时,我得到的值为0。 在onResponse中,我尝试了设置温度,结果设置好了。我不知道问题出在哪里 private double temperature; public double getTemperature() { return temperature; } public JSONparser(Context context, String city) { RequestQueue queue = Volley.ne
onResponse
中,我尝试了设置温度,结果设置好了。我不知道问题出在哪里
private double temperature;
public double getTemperature() {
return temperature;
}
public JSONparser(Context context, String city) {
RequestQueue queue = Volley.newRequestQueue(context);
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + city;
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
try {
temperature = (response.getJSONObject("main")
.getDouble("temp"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);
}
私人双温;
公共双温度(){
返回温度;
}
公共JSONparser(上下文,字符串城市){
RequestQueue=Volley.newRequestQueue(上下文);
字符串url=”http://api.openweathermap.org/data/2.5/weather?q=“+城市;
JsonObjectRequest jsObjRequest=新的JsonObjectRequest(
Request.Method.GET,url,null,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
//TODO自动生成的方法存根
试一试{
温度=(response.getJSONObject(“main”)
.getDouble(“temp”);
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
//TODO自动生成的方法存根
}
});
add(jsObjRequest);
}
对类对象使用singleton,也可以使用setFunction,不要直接初始化该值,因为如果不使用同一对象,该值将为0
public void setTemperature(double mTemp) {
temperature = mTemp;
}
如果可以工作,请尝试将
温度更改为静态成员。然后实际上还有另一个实例正在被创建,其中JSONparser jsp=newjsonparser(这个,getCity());double temperature=jsp.getTemperature();tv.setText(“+Math.round(温度-272.5)+”°C”);