Saeed Hashemi
Saeed Hashemi

Reputation: 1024

Read data from webpage in Android

I use this code for read data from html page and put in to webview

public class MainActivity extends Activity {
public WebView objwebview ;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    objwebview = (WebView)findViewById(R.id.webView1);
          HttpClient client = new DefaultHttpClient();
          HttpGet request = new HttpGet("http://www.google.com");
          try
          {
              HttpResponse response = client.execute(request);
              BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
              String line;
              StringBuilder str = new StringBuilder();
              while((line = reader.readLine()) != null) {
                  str.append(line);
          }
              objwebview.loadData(str.toString(), "text/html", "UTF-8");
      }
      catch(Exception e)
      {
          e.printStackTrace();
          objwebview.loadData(e.toString(), "text/html", "UTF-8");
      }

but when I run that ,I give this error ("android.os.networkonmainthreadexception") how can I fix that?

Upvotes: 1

Views: 3062

Answers (2)

Riz Khan
Riz Khan

Reputation: 304

you are accessing network connection in main thread. paste the following lines beneath setContentView(your_layout);

// Allow network access in the main thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Upvotes: 2

Kristopher Micinski
Kristopher Micinski

Reputation: 7672

You are running your networking code on the main thread in Android. Read this to find some partial answers to your problem.

The basic idea is that if you perform synchronous reads that do not immediately return (i.e., things that take a long time, such as network operations), you need to do so on another thread, and then communicate the results back to the GUI.

You have a few options to do this: you can use an AsyncTask, which allows you to painlessly publish updates to the UI, or you can use a background Service along with an associated communication (either via AIDL or a simpler Message and Handler).

Upvotes: 3

Related Questions