开发者

Async Task returning int value after network working

I have my Asyntask structure as:

private class GetMyFlights extends AsyncTask<String, Void, Integer> {       
    private ProgressDialog dialog;  

    public GetMyFlights(ListActivity activity) {}

    protected void onPreExecute() {
        if(mFirstOpen){
            mFirstOpen = false;
            dialog = new ProgressDialog(mCtx);
            this.dialog.setMessage(getResources().getString(R.string.common_getting_data));
            this.dialog.show();
        }
        }       

    @Override
    protected Integer doIn开发者_如何学GoBackground(String... params) {
        return getData();
    }       

    @Override
    protected void onPostExecute(Integer result) {  
        super.onPostExecute(result);    
        //if(mFinishGettingData){  //global variable 
            mFinishGettingData = false;
            switch(result){
                case 0:
                    //...                   
                break;
                case 1:
                    //...
                break;
                case 2:             
                    //...
                break;

            }
        //}         
    }
}

And my method getData:

private int getData() {     
    try{
        myFlightsA = new FlightAdapter(this, R.layout.row_myflight, WithingsAPI.getInstance().getFutureFlights());
        //mFinishGettingData = true;
        if(myFlightsA != null)
            return 0;
    }catch(NetworkConnetionException e){
        if(e.getMessage().equals(NetworkConnetionException.ERROR_CONNECTION))
            return 1;
        else if(e.getMessage().equals(NetworkConnetionException.NOT_LOGGED)){
            Log.d(TAG, "Not Logged");
            return 2;
        }
    }catch(Exception e){
        Log.d(TAG, e.toString());
    }       
    return 3;
}

But I dont know if I am doing something wrong, as sometimes the Task work as expected but sometimes appears the dialog as getData returns 3 and afterwards 1.

I have thought about using a global variable mFinishGettingData to notify the ending of the network working. And also return 4 instead of 3 so then afterwards the switch doesnt match none.


There is only one way this AsyncTask can return 3.

Your FlightAdapter throws an error and the exception type does not match any of the if..else if inside the catch block.

if(e.getMessage().equals(NetworkConnetionException.ERROR_CONNECTION))
        return 1;
    else if(e.getMessage().equals(NetworkConnetionException.NOT_LOGGED)){
        Log.d(TAG, "Not Logged");
        return 2;
    }

I suggest you log the exception

i:e Log.e(TAG, e.getMessage().toString);

right before your if block starts inside you catch block and check to see what kind of exception is it throwing.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜