【发布时间】:2017-05-11 19:36:13
【问题描述】:
已阅读所有集合并从 UI 线程调用,在 stackoverflow 上,但似乎没有一个相关的。此代码在 2 年前有效,最近打开它。它显示了这个错误。 “必须从 UI 线程调用 setText 方法”。
这是什么更新?
用 cmets 标记 setText 行以使其更清晰。有什么建议吗?
public class MainActivity extends Activity {
static final String baseURL = "http://api.yr.no/weatherapi/locationforecast/1.9/?lat=";
TextView dato, grader, vindhastighet, vindretning;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .detectAll().penaltyLog().build(); StrictMode.setThreadPolicy(policy);
SmartLocation.with(this).location()
.oneFix()
.start(new OnLocationUpdatedListener() {
@Override
public void onLocationUpdated(Location location) {
dato = (TextView)findViewById(R.id.gpsbydato_txt);
grader = (TextView)findViewById(R.id.gpsbygrader_txt);
vindhastighet = (TextView)findViewById(R.id.gpsbyvindhastighet_txt);
vindretning = (TextView)findViewById(R.id.gpsbyvindretning_txt);
Double latitude = location.getLatitude();
Double longtitude = location.getLongitude();
StringBuilder Url = new StringBuilder(baseURL);
Url.append(latitude + ";lon=" + longtitude);
final String fullUrl = Url.toString();
class Read extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... arg0) {
try {
URL website = new URL(fullUrl);
//xmlreader parser data
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(website.openStream()));
String informationTemp = doingWork.getInformationTemp();
String informationVindretning = doingWork.getInformationVindretning();
String informationVindhastighet = doingWork.getInformationVindhastighet();
//grader.setText is causing the error.
grader.setText(informationTemp);
//vindhastighet.setText is causing the error.
vindhastighet.setText(informationVindhastighet);
//vindretning.setText is causing the error.
vindretning.setText(informationVindretning);
} catch (Exception e) {
Log.e("URL:", fullUrl);
dato.setText("erroorrr"); //also this setText
System.out.println(e);
}
return null;
}
@Override
protected void onPostExecute(String result) {
dato.setText(result);
super.onPostExecute(result);
}
}
}
});
}
}
【问题讨论】:
标签: android multithreading android-asynctask background