首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AsyncTask崩溃应用程序

AsyncTask崩溃应用程序
EN

Stack Overflow用户
提问于 2012-04-13 00:26:12
回答 2查看 184关注 0票数 0

有人知道为什么AsyncTask总是崩溃吗?基本上,在我的应用程序中,我希望获得GPS坐标,并让它动画到我在mapview中的位置。然后我想使用GeoCode来显示我当前的职位地址。

在我开始尝试AsyncTask之前,这个应用程序完美地显示了一切(显示地图上的当前位置,告诉我离我最近的地址,并将其显示在文本视图中)然而,由于我没有实现AsyncTask,它非常慢和滞后。现在我已经实现了AsyncTask,它给了我错误。有人能帮上忙吗?

下面是我的代码:

代码语言:javascript
复制
public class statuspage extends MapActivity {

private MapController mapController;
private MyLocationOverlay myLocation;
Location location;


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.statuspage);

    new MapOverlay().execute(); 

    // Get Mapping Controllers etc
    MapView mapView = (MapView) findViewById(R.id.mapView);
    mapController = mapView.getController();
    mapController.setZoom(14);
    mapView.setBuiltInZoomControls(true);

    // Add the MyLocationOverlay
    myLocation = new MyLocationOverlay(this, mapView);
    mapView.getOverlays().add(myLocation);
    myLocation.enableMyLocation();
    myLocation.runOnFirstFix(new Runnable() {

        public void run() {
            mapController.animateTo(myLocation.getMyLocation());

        }
    });
}



class MapOverlay extends AsyncTask<Void,Long,DataPackage> {


    @Override
    protected DataPackage doInBackground(Void... arg0) {
        return new DataPackage(); 
    }
}

class DataPackage { 

    public String addressString = null; 
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();

    public DataPackage(addressString, latitude, longitude) { 
        statuspage.this.addressString = addressString; 
        statuspage.this.latitude = location.getLatitude();
        statuspage.this.longitude = location.getLongitude();

    } 
} 


protected boolean isRouteDisplayed() {

    // Location Manager Intiation
    LocationManager locationManager;
    String bestProvider;
    String LOCATION_SERVICE = "location";
    locationManager = (LocationManager) statuspage.this
            .getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    // More accurate, GPS fix.
    criteria.setAccuracy(Criteria.ACCURACY_FINE); // More accurate, GPS fix.
    bestProvider = locationManager.getBestProvider(criteria, true);
    location = locationManager.getLastKnownLocation(bestProvider);
    if (location != null) {

        // Latitude and Longitude TextView
        TextView etlongitude = (TextView) findViewById(R.id.etlongitude);
        TextView etlatitude = (TextView) findViewById(R.id.etlatitude);

        // Disables longitude textview Keyboard Popup.
        //InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //imm.hideSoftInputFromWindow(etlongitude.getWindowToken(), 0);

        // Disables latitude textview Keyboard Popup.
        //InputMethodManager imm2 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //imm2.hideSoftInputFromWindow(etlatitude.getWindowToken(), 0);



        // Latitude and Longitude TextView Display Coordinates
        etlongitude.setText("Longitude:" + "\n" + (longitude)); 
        /** longitude textview */
        etlatitude.setText("Latitude:" + "\n" + (latitude));
        /** latitude textview */

        addressString = "No address found";

        Geocoder gc = new Geocoder(statuspage.this, Locale.getDefault());
        try {
            List<Address> addresses = gc.getFromLocation(latitude,
                    longitude, 1);
            StringBuilder sb = new StringBuilder();
            if (addresses.size() > 0) {
                Address address = addresses.get(0);

                for (int i = 0; i < address.getMaxAddressLineIndex(); i++)


                sb.append(address.getAddressLine(i)).append("\n");
                //sb.append(address.getFeatureName()).append("\n");
                //sb.append(address.getPhone()).append("\n");
                //sb.append(address.getLocality()).append("\n");
                //sb.append(address.getPostalCode()).append("\n");
                //sb.append(address.getCountryName());
            }
            addressString = sb.toString();


            TextView scrollview = (TextView) findViewById(R.id.scrollview);
            scrollview.setText("Your location:" + "\n" + "(Accurate to 500 meters)" +"\n" +(addressString));

        } catch (IOException e) {
        }

        // locationManager.removeUpdates((LocationListener) location);
        locationManager = null;

    } else {

    }

    return false;
}



protected void onResume() {
    myLocation.enableMyLocation();
}

protected void onPause() {
    myLocation.disableMyLocation();
}

public void onBackPressed() {

    // Button OnClick Vibrating Service
    Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    // Vibrate Service
    vib.vibrate(50);

    startActivity(new Intent(statuspage.this, AgentPortalActivity.class));
    statuspage.this.finish();

    /** Fading Transition Effect */
    overridePendingTransition(R.anim.fadein, R.anim.fadeout);

    return;

}
 }

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;

}
}

以下是我的日志:

代码语言:javascript
复制
 04-12 09:14:15.682: W/dalvikvm(13103): threadid=11: thread exiting with uncaught exception    (group=0x40015578)
 04-12 09:14:15.686: E/AndroidRuntime(13103): FATAL EXCEPTION: AsyncTask #1
 04-12 09:14:15.686: E/AndroidRuntime(13103): java.lang.RuntimeException: An error occured while  executing doInBackground()
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at android.os.AsyncTask$3.done(AsyncTask.java:200)
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at  java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at java.util.concurrent.FutureTask.run(FutureTask.java:138)
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at java.lang.Thread.run(Thread.java:1019)
 04-12 09:14:15.686: E/AndroidRuntime(13103): Caused by: java.lang.NullPointerException
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at com.jetdelivery.mobile.statuspage$MapOverlay.doInBackground(statuspage.java:119)
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at com.jetdelivery.mobile.statuspage$MapOverlay.doInBackground(statuspage.java:1)
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at android.os.AsyncTask$2.call(AsyncTask.java:185)
 04-12 09:14:15.686: E/AndroidRuntime(13103):   at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
 04-12 09:14:15.686: E/AndroidRuntime(13103):   ... 4 more

谢谢你们。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-13 00:29:56

您的代码正在使应用程序崩溃,因为您试图在没有处理程序的情况下访问UI线程上的控件,并将其放在错误的执行区域中。

您应该阅读AsyncTask以及如何正确处理与UI的交互。在那个页面上有非常好的信息。

要更新您的UI,您应该实现onPostExecute(),它提供来自doInBackground()的结果并在UI线程中运行,因此您可以安全地更新UI。

中需要移至onPostExecute()的相关中断代码

代码语言:javascript
复制
            // Latitude and Longitude TextView Display Coordinates
            etlongitude.setText("Longitude:" + "\n" + (longitude));
            /** longitude textview */
            etlatitude.setText("Latitude:" + "\n" + (latitude));
            /** latitude textview */


            TextView scrollview = (TextView) findViewById(R.id.scrollview);
            scrollview.setText("Your location:" + "\n"
                    + "(Accurate to 500 meters)" + "\n" + (addressString));

编辑:从评论讨论中添加示例。

代码语言:javascript
复制
class DataPackage {
    public String Address = null;
    public double Latitude = 0.0;
    public double Longitude = 0.0;

    public DataPackage(address, lat, lon) {
        this.Address = address;
        this.Latitude = lat;
        this.Longitude = lon;
    }
}

..。

代码语言:javascript
复制
class MapOverlay extends AsyncTask<Void,Void,DataPackage> {

    @Override
    protected Void doInBackground(Void... arg0) {  
        // ... Conditions and logic TRUNCATED for Clarity!
        // This would exist inside of your try block
        return new DataPackage(addressString, latitude, longitude);
        // ... Rest of code
    }

    //...

    protected void onPostExecute(DataPackage result) {
        //Logic that updates the UI based on information in DataPackage object.
    }
}
票数 1
EN

Stack Overflow用户

发布于 2012-04-13 00:29:47

代码语言:javascript
复制
 TextView scrollview = (TextView) findViewById(R.id.scrollview);
 scrollview.setText("Your location:" + "\n"
                        + "(Accurate to 500 meters)" + "\n" + (addressString));

用onPostExecute()而不是doInBackground()编写上面的代码。在doInbackground()中,我们只执行与网络相关的任务,所有与UI相关的任务都必须在onPostExecute()中。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10127708

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档