0

I am making an app that will download a string from a website and display it. I tried many examples online and I've literally been searching for days for this, but I can't find a single solution.

From what I have read, I know I have to get the content of the url from another thread, but no tutorial showed me how to do this.

I have a textview on the layout and that will be where the html content will have to show up.

Can anybody show me an example of how this is done?

C Knife
  • 1
  • 3
  • Follow this link please : http://stackoverflow.com/questions/2376471/how-do-i-get-the-web-page-contents-from-a-webview – Farouk Touzi Oct 10 '14 at 23:17
  • I do not want to have any WebView in my app, so this is not the solution – C Knife Oct 10 '14 at 23:19
  • Sorry I misunderstand your question. – Farouk Touzi Oct 10 '14 at 23:22
  • http://stackoverflow.com/questions/11590899/downloading-a-website-to-a-string includes the case of reading text from a remote site. Displaying a string can then be done using standard android UI elements. – andy Oct 10 '14 at 23:26
  • Sorry, but I've already seen that site about 13 times. This example does not work in android 4.0, as this requires it to be executed from another thread. As I mentioned in the question. – C Knife Oct 10 '14 at 23:30

1 Answers1

0

What about something like this?

public class MyAsyncTask extends AsyncTask<String, Void, String>
{
    @Override
    protected String doInBackground(String... requestUrl) 
    {
        String result = null;

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(requestUrl[0]);

        try
        {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            result = httpClient.execute(request, responseHandler);
        }
        catch (IOException e)
        {
            Log.e("requestStringFromWebServer", "Whoops!", e);
        }

        httpClient.getConnectionManager().shutdown();

        return result;
    }

    @Override
    protected void onPostExecute(String result)
    {
        if (result != null)
        {
            // Handle the result from your request here...
        }
    }
}

And kick it off with

String myUrlStr; // Initialize this to your url
new MyAsyncTask().execute(myUrlStr);
Michael Krause
  • 4,689
  • 1
  • 21
  • 25
  • This code does not work in android 4, as we have to do it with an asynctask. – C Knife Oct 10 '14 at 23:34
  • It works fine in Android 4. It's easy enough to call this method from the doInBackground of an AsyncTask and deliver the result as a String to be consumed by onPostExecute. – Michael Krause Oct 10 '14 at 23:36
  • Mind giving me a full example of this? I've been searching for that for days – C Knife Oct 10 '14 at 23:39