开发者

Try/Catch in Async Tasks

I implemented an Async task which should fetch data from a webservice - however if the device has no active InternetConnection - or if anything happens in the "try" block I get an exception and my app crashes ... I tried to hinder that behaviour with a "finally" clause .. but the debugger is not entering the finally clause

            try{
                this.kantinen = new KantinenListe();
                Gson gson = new Gson();             
                // SOAP Test
                String NAMESPACE = "http://tempuri.org/";
                String METHOD_NAME = "fullSyncGPS";
                String SOAP_ACTION = "http://tempuri.org/IDatenService/fullSyncGPS";
                String URL = 开发者_如何学编程"Currywurst.svc?wsdl";

                SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);

                PropertyInfo pi = new PropertyInfo();
                request.addProperty("radius",10);
                request.addProperty("lat", Double.toString(currentLocation.getLatitude()));
                request.addProperty("lng", Double.toString(currentLocation.getLongitude()));
                request.addProperty("von", "01.09.2011");
                request.addProperty("bis", "05.09.2011");

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);        

                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.call(SOAP_ACTION, envelope);
                SoapPrimitive result = (SoapPrimitive)envelope.getResponse();

                String resultData = result.toString(); 


                resultData = "{\"meineKantinen\":"+resultData+"}";
                this.kantinen = gson.fromJson(resultData, KantinenListe.class);
            }
            catch(Exception e)
            {
          //todo: implement
            }
            finally
            {
                return this.kantinen;
            }


catch(Exception e)
{
     return this.kantinen;
{

Might be a possible solution? However I wouldn't know why your finally is not executing


You'd get a crash if this.kantinen is not initialized when you return from this method. Make sure you at least have something like:

 KantinenListe kantinen = null;


** You can check for network connectivity and then do your processing **

public static boolean isNetworkAvailable(Context context) { boolean outcome = false;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo[] networkInfos = cm.getAllNetworkInfo();

    for (NetworkInfo tempNetworkInfo : networkInfos) {

        if (tempNetworkInfo.isConnected()) {
            outcome = true;
            break;
        }
    }


    return outcome;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜