Lef*_*ris 5 android android-asynctask
我有一个Activity(RecipiesActivity),它通过单击我的应用程序的Main Activitiy的"Next"按钮打开.
在RecipiesActivity onCreate中,我想在AsyncTask中调用Web服务.现在,既然我还没有实现web服务,我只是调用了一点点提供的web服务(但这与我的问题无关).
问题是虽然调用webservice并且没有抛出异常,但结果是从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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
你的帮助是值得的,
谢谢
而不是doInBackground()简单地调用execute()AsyncTask 的方法.调用doInBackground()就像在tin上调用的那样:调用doInBackground()(在同一个线程中)并返回.它不会叫onPostExecute()你.execute()将启动后台线程,调用doInBackground()后台线程,然后将结果发布doInBackground()到onPostExecute()UI线程上.
| 归档时间: |
|
| 查看次数: |
1306 次 |
| 最近记录: |