m非常新的android,这是我在Stackoverflow上的第一个查询。 这是我在使用AsyncTask时获得空指针异常。 我正在使用ProgressDialog,因为我创建了一个(单独的(新))类,它扩展了AsynchTask。当我从我的主类中将参数传递给我想要显示ProgressDialog的类时,它给了我一个nullpointer异常.. 可以任何人告诉我该怎么做.. 这是代码
class Loader extends AsyncTask<Object, Object, Object> {
ProgressDialog dialog;
public void setDialog(ProgressDialog dialog){
this.dialog = dialog;
//here i get the reference of dialog from the caller class
}
提前致谢.. MAHAVEER
答案 0 :(得分:1)
无需将对话框作为参数发送到AsyncTask
,这可能会导致您的错误。您可以在ProgressDialog
中创建新的AsyncTask
并在onPreExecute
方法中显示,因为此方法在UI线程上运行。希望这会有所帮助。
P.S。如果有错误,请尽量发布错误的logcat,这样可以让人们更容易提供帮助。祝贺你的第一篇文章!
答案 1 :(得分:0)
使用重写的onPreExecute方法而不是setDialog
答案 2 :(得分:0)
private class LocationControl extends AsyncTask<Context, Void, Void>
{
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute()
{
this.dialog.setMessage("Tap outside dialog to close");
this.dialog.setTitle("Searching your current location...");
//this.dialog.setTitle(R.string.hello);
this.dialog.setCanceledOnTouchOutside(true);
this.dialog.show();
}
protected Void doInBackground(Context... params)
{
//Wait 40 seconds to see if we can get a location from either network or GPS, otherwise stop
Long t = Calendar.getInstance().getTimeInMillis();
while (!hasLocation && Calendar.getInstance().getTimeInMillis() - t < 40000) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
return null;
}
protected void onPostExecute(final Void unused)
{
if(this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (currentLocation != null)
{
GeoPoint startPoint = new GeoPoint((int)(currentLocation.getLatitude()*1E6),(int)(currentLocation.getLongitude()*1E6));
final MapController mc = mapView.getController();
mc.animateTo(startPoint);
mc.setZoom(16);
}
else
{
/*
Toast.makeText(MainActivity.this, "Location could not be found\nusing default location", Toast.LENGTH_SHORT).show();
GeoPoint startPoint = new GeoPoint((int)(43.332628*1E6),(int)(5.353128*1E6));
final MapController mc = mapView.getController();
mc.animateTo(startPoint);
mc.setZoom(16);
*/
}
}
}
从onCreate()
:
locationControlTask = new LocationControl();
locationControlTask.execute(this);