问题描述
所以我使用的是Android与AsyncTask的类的工作我的第一个多线程应用程序。我试图用它来火了一个地理codeR在第二个线程,然后更新与onPostExecute用户界面,但我依然会碰到一个问题,正确的上下文。
So I'm working out my first multi-threaded application using Android with the AsyncTask class. I'm trying to use it to fire off a Geocoder in a second thread, then update the UI with onPostExecute, but I keep running into an issue with the proper Context.
我通过使用上下文在主线程中步履蹒跚我的路,但我不完全确定的上下文是什么或如何使用它在后台线程,而我还没有找到任何很好的例子。任何帮助吗?这里是我想要做的摘录:
I kind of hobbled my way through using Contexts on the main thread, but I'm not exactly sure what the Context is or how to use it on background threads, and I haven't found any good examples on it. Any help? Here is an excerpt of what I'm trying to do:
public class GeoCode extends AsyncTask<GeoThread, Void, GeoThread> {
@Override
protected GeoThread doInBackground(GeoThread... i) {
List<Address> addresses = null;
Geocoder geoCode = null;
geoCode = new Geocoder(null); //Expects at minimum Geocoder(Context context);
addresses = geoCode.getFromLocation(GoldenHour.lat, GoldenHour.lng, 1);
}
}
它不断失败,因为不正确的语境中,在第六行那里。
It keeps failing at the sixth line there, because of the improper Context.
推荐答案
@Eugene的van der Merwe的
@Eugene van der Merwe
下面这段code对我的作品:) - >
The following piece of code works for me : ) -->
public class ApplicationLauncher extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.applicationlauncher);
LoadApplication loadApplication = new LoadApplication(this);
loadApplication.execute(null);
}
private class LoadApplication extends AsyncTask {
Context context;
ProgressDialog waitSpinner;
ConfigurationContainer configuration = ConfigurationContainer.getInstance();
public LoadApplication(Context context) {
this.context = context;
waitSpinner = new ProgressDialog(this.context);
}
@Override
protected Object doInBackground(Object... args) {
publishProgress(null);
//Parsing some stuff - not relevant
configuration.initialize(context);
return null;
}
@Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
// Only purpose of this method is to show our wait spinner, we dont
// (and can't) show detailed progress updates
waitSpinner = ProgressDialog.show(context, "Please Wait ...", "Initializing the application ...", true);
}
@Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
waitSpinner.cancel();
}
}
}
干杯,
Ready4Android
Ready4Android
这篇关于AsyncTask的和上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!