Pergunta

Ok, what I want is to ask to my server for an url, and load that url on a WebView, but a problem appears: when you run a http request you need to do it in a separate thread, and loadUrl() needs to be runned in the UI thread. So, how can I do to first make the request and then load the url?

The code isn't inside an Activity, so I can't call runOnUiThread(Runnable).

How can I do it?

EDIT: As Alécio suggested, it's better to not have too much code inside custom views, so what I want to do is to create a method that allows me to pass the url when the app has received the response from the server. The code that I'm using for the request is:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://requesturl.com");
try {
    HttpResponse response = client.execute(post);
    InputStream content = response.getEntity().getContent();
    String url = getStringFromInputStream(content);
    //web.loadUrl(url);     
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

So, it's possible to know when a response has been received?

Foi útil?

Solução

WebView is a UI component it must be in the context of an Activity or Fragment, so loadUrl() from the UI thread is OK.

If you want to make a server call, process the response before displaying something on the UI, then you might just use the conventional options to connect to a server URL using the HttpURLConnection. See the sample code below:

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
 readStream(in);
finally {
 urlConnection.disconnect();
}
}

In this example, you really need to execute it in a background Thread. Never from the UI Thread.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top