大家好我正在使用天气API来获取天气数据
public class Weather extends Activity {
String city;
public TextView t,tmin,tmax;
ImageView icon;
String img;
private static final String API_URL = "http://api.openweathermap.org/data/2.5/weather?q=";
private static final String MAIN = "main";
private static final String TEMP = "temp";
private static final String TEMP_MIN = "pressure";
private static final String TEMP_MAX = "temp_max";
JSONObject data = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather);
t = (TextView) findViewById(R.id.temp);
tmin = (TextView) findViewById(R.id.minTemp);
tmax = (TextView) findViewById(R.id.maxTemp);
icon=(ImageView)findViewById(R.id.imageView);
city = getIntent().getExtras().getString("city_name");
new JSONParse().execute();
}
@Override
public void onBackPressed() {
super.onBackPressed();
t.setText("N/A");
tmin.setText("N/A");
tmax.setText("N/A");
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog progressDialog;
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(Weather.this);
progressDialog.setMessage("Getting Data...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
}
@Override
protected JSONObject doInBackground(String... strings) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(API_URL + city);
return json;
}
protected void onPostExecute(JSONObject json) {
progressDialog.dismiss();
try {
JSONArray arr=null;
data = json.getJSONObject(MAIN);
arr=json.getJSONArray("weather");
JSONObject obj=arr.getJSONObject(0);
String conditon=obj.getString("description");
double tmp = data.getDouble(TEMP);
double tmn = data.getDouble(TEMP_MIN);
double tmx = data.getDouble(TEMP_MAX);
img=obj.getString("icon");
// int resource=getResources().getIdentifier("@drawable/icons/"+img,null,null);
// Drawable drw=getResources().getDrawable(resource);
// icon.setImageDrawable(drw);
t.setText("" +Math.floor(tmp-273.15)+"°C");
tmax.setText("" + img);
tmin.setText("" + conditon);
} catch (Exception e) {
Log.i("Inside Weather :",""+e);
e.printStackTrace();
}
我评论过的部分无效,请提出解决方案。 感谢
答案 0 :(得分:2)
要为imageView设置图片,请尝试此icon.setImageResource(R.drawable.icons);
答案 1 :(得分:0)
在getResources().getDrawable(resource)
,您应该使用aapt工具生成的资源标识符(如R.drawable.app_icon
),这更容易由R资源定义。而这种方法也让人厌倦了,所以我建议使用:
ContextCompat.getDrawable(getApplicationContext(), R.drawable.[your_image_path])
比如this帖子
或icon.setImageResource(R.drawable.[your_image_path])
答案 2 :(得分:0)
您可以使用以下名称设置drawable
Resources res = getResources();
String mDrawableName = "your_drawable_name";// i.e. icon
int resID = res.getIdentifier(mDrawableName , "drawable", getPackageName());
Drawable drawable = res.getDrawable(resID );
icon.setImageDrawable(drawable );