2015-04-15 196 views
-2

我遇到了(在我看來)真的很奇怪的問題。我在Android Studio中有一個包含以下代碼的Android項目:Android跳過代碼

if(AppSettings.isNetworkAvailable(context, showDialog)) { 
return null; 
} 
else { 

    HttpResponse httpResponse = null; 
    AsyncHttpGet asyncHttpGet = new AsyncHttpGet(mHttpClient, mHttpContext); 

    String url = BASE_URI + atPath; 
    asyncHttpGet.execute(url); 

    try { 
     httpResponse = asyncHttpGet.get(); 
     System.out.println("Response: " + httpResponse); 
    } catch (InterruptedException | ExecutionException e) { 
     e.printStackTrace(); 
    } 

    if(isAccepted(httpResponse)) { 
     return httpResponse; 
    } else { 
     return null; 
    } 
} 

此代碼在運行時返回null,並且不提供輸出。調試器光標從第一個if子句(返回true)直接跳轉到最後一個return語句,而不聲明或初始化任何變量。

我也嘗試刪除其他,因爲它應該沒有它的工作,但這沒有什麼區別。有沒有人有一個想法可以解決問題?

編輯:我應該補充:代碼工作得很好,沒有初始的if-clause並返回一個有效的HttpResponse。

回答

2

如果AppSettings.isNetworkAvailable(context, showDialog)爲真,return null是正確的行爲。

如果你想進入其他部分,使用:

if(AppSettings.isNetworkAvailable(context, showDialog)) { 
    HttpResponse httpResponse = null; 
    AsyncHttpGet asyncHttpGet = new AsyncHttpGet(mHttpClient, mHttpContext); 

    String url = BASE_URI + atPath; 
    asyncHttpGet.execute(url); 

    try { 
     httpResponse = asyncHttpGet.get(); 
     System.out.println("Response: " + httpResponse); 
    } catch (InterruptedException | ExecutionException e) { 
     e.printStackTrace(); 
    } 

    if(isAccepted(httpResponse)) { 
     return httpResponse; 
    } else { 
     return null; 
    } 
} 
+1

你錯過了一個return語句 – Blackbelt

+1

謝謝,真有「問題」! 3個人,1小時的調試,沒有人看到......我猜測調試器跳躍只是由於一些優化返回語句。 –