我有一個活動(RecipiesActivity),通過點擊我的應用程序的主要活動的「下一步」按鈕打開。onPostExecute不會被調用
在RecipiesActivity onCreate中,我想調用AsyncTask中的webservice。現在,因爲我還沒有實現web服務,所以我只是調用了一點點提供的web服務(但這與我的問題無關)。
問題是,雖然webservice被調用並且沒有引發異常,但結果是從doInBackground返回,但是我的onPostExecute未被調用。我做了一些研究,我發現可能的原因如下所列 - 但沒有似乎是我的情況:
- onPostExecute參數不匹配的AsyncTask參數 - 在我的情況,他們一致
- 中的錯誤Android不允許在UI線程中執行AsyncTask。它是通過supposadely使用Class.forName克服(「android.os.AsyncTask」) - 我想這並沒有什麼差別
- 的AsyncTask不從UI線程開始 - 在我的情況下,我相信這是
- doInBackground不回 - 在我的情況是這樣,我已經通過它加強與調試器
- @覆蓋不onPostExecute前使用 - 在我的情況,我使用@覆蓋
的代碼如下:
public class RecipiesActivity extends Activity {
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipies);
tv = (TextView) findViewById(R.id.Response);
//Start the WS call in an AsyncTask
new CallWS().doInBackground("https://api-ssl.bitly.com/v3/shorten?login=maskedLogin&apiKey=maskedKey&longUrl=http%3A%2F%2Fgoogle.com%2F");
}
private class CallWS extends AsyncTask<String, Integer, String>
{
@Override
protected String doInBackground(String... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet get_request = new HttpGet(params[0]);
try
{
HttpResponse httpResponse = httpClient.execute(get_request, localContext);
//int responseCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream istream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(istream));
try
{
result = br.readLine();
}
catch (Exception e)
{
//TODO Handle the IOException that the readline may throw
}
finally
{
istream.close();
}
}
}catch (Exception e)
{
//TODO Handle the IOException and the ClientProtocolException that the
// httpClient.execute can throw
}
finally
{
httpClient.getConnectionManager().shutdown();
}
return result;
}
@Override
protected void onPostExecute(String result)
{
if (result == null)
{
tv.setText("The result is NULL");
}
else
{
tv.setText(result);
}
}
}
}
你的幫助是appreceiated,
感謝
非常感謝你。這個(明顯的)錯誤導致了這個問題。 – Lefteris
將解決方案標記爲已接受... – Hades
我在發佈後立即這樣做,但要求我在等待大約7-10分鐘之後才能這樣做。無論如何,答案現在標記:) – Lefteris