[英]Update Textview from internet with AsyncTask
我使用AsynTask从网上获取数据并在Textview中显示,这是我的代码
public class PatientAssistant extends Activity {
private TextView txtTemp,txtHuminity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patient_assistant);
AppPreferences pref=new AppPreferences(this);
TextView textCity=(TextView)findViewById(R.id.txtCity);
txtTemp=(TextView)findViewById(R.id.txtTemp);
txtHuminity=(TextView)findViewById(R.id.txtHumidity);
textCity.setText(pref.getCity());
String city=(String) textCity.getText();
CallWeatherAsync cwa=new CallWeatherAsync(this,txtTemp,txtHuminity);
cwa.execute(city);
Button btnSend=(Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//TODO send report
}
});
}
private class CallWeatherAsync extends AsyncTask<String, Void, WeatherInfo> {
private PatientAssistant _activity;
private TextView txtT,txtH;
public CallWeatherAsync(PatientAssistant activity,TextView txtTmp,TextView txthum)
{
_activity=activity;
txtT=txtTmp;
txthum=txtH;
}
@Override
protected WeatherInfo doInBackground(String... params) {
YahooWeatherUtils yahooWeatherUtils = YahooWeatherUtils.getInstance();
WeatherInfo weatherInfo = yahooWeatherUtils.queryYahooWeather(_activity.getApplicationContext(), params[0]);
return weatherInfo;
}
@Override
protected void onPostExecute(WeatherInfo result) {
txtT.setText(result.getCurrentTempC());
txtH.setText(result.getAtmosphereHumidity());
}
}
}
但这会引发Resources $ NotFoundException !!!
12-02 00:39:06.383: E/AndroidRuntime(4035): android.content.res.Resources$NotFoundException: String resource ID #0xc
12-02 00:39:06.383: E/AndroidRuntime(4035): at android.content.res.Resources.getText(Resources.java:247)
12-02 00:39:06.383: E/AndroidRuntime(4035): at android.widget.TextView.setText(TextView.java:3473)
12-02 00:39:06.383: E/AndroidRuntime(4035): at com.assitant.patient.PatientAssistant$CallWeatherAsync.onPostExecute(PatientAssistant.java:116)
12-02 00:39:06.383: E/AndroidRuntime(4035): at com.assitant.patient.PatientAssistant$CallWeatherAsync.onPostExecute
我该怎么做?
盲目的猜测是:
txtT.setText(result.getCurrentTempC());
txtH.setText(result.getAtmosphereHumidity());
返回int
而不是string
。 如果它是int
则将其视为资源ID。 这将起作用:
txtT.setText( "" + result.getCurrentTempC());
txtH.setText( "" + result.getAtmosphereHumidity());
干杯! ,您的问题应该出在txthum = txtH;上。 它应该是txtH = txthum;
您不要在私有类中设置TextView。 由于您将2个TextViews设置为PatientAssistant类的全局变量,因此您应该直接在私有AsyncClass中使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.