-2

试图读取网页作为一个字符串,这是我的代码:阅读网页的字符串,但出现错误

public class ReadWebPage extends Activity { 
private EditText url_text; 
private TextView textView; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    url_text = (EditText) findViewById(R.id.address); 
    textView = (TextView) findViewById(R.id.tv); 
} 
public void myButtonClickHandler(View view) { 
    switch (view.getId()) { 
    case R.id.ReadWebPage: 
     try { 
      if (!url_text.getText().toString().trim().equalsIgnoreCase("")) { 
       textView.setText(""); 
       HttpClient client = new DefaultHttpClient(); 
       HttpGet request = new HttpGet(url_text.getText().toString()); 
       // Get the response 
       ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
       String response_str = client.execute(request, 
         responseHandler); 
       textView.setText(response_str); 
      } else { 
       Toast.makeText(getApplicationContext(), 
         "URL String empty.", Toast.LENGTH_LONG).show(); 
      } 
     } catch (Exception e) { 
      System.out.println("Some error occured."); 
      textView.setText(e.getMessage()); 
     } 
     break; 
    } 
} 
    } 

正如上面我显示了使用这些代码,并试图读一些网页作为字符串我的代码,但它是显示那个错误。

03-03 22:37:45.088: I/System.out(1233): Some error occured. 
    03-03 22:37:45.088: W/System.err(1233): android.os.NetworkOnMainThreadException 
    03-03 22:37:45.138: W/System.err(1233): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 
-03 22:37:45.148: W/System.err(1233): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
    03-03 22:37:45.158: W/System.err(1233): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
+0

粘贴logcat的和精确,重点突出信息提高你的问题。 – 2013-03-03 17:05:33

+0

我已经粘贴@codingcrow – 2013-03-03 17:23:55

回答

0

Android告诉你,你不应该在UI线程上进行网络操作。它不希望你阻止线程,并有充分的理由。

尝试使用AsyncTask代替。将您的HTTP请求代码放在doInBackground()方法中,并在onPostExecute()方法中更新TextView。您不能从doInBackground()方法访问UI线程。

这里是一个非常简单的例子:

class MyAsyncTask extends AsyncTask<String, String, String> 
{ 
    private TextView textView; 

    public MyAsyncTask(TextView textView) 
    { 
     this.textView = textView; 
    } 

    protected Long doInBackground(String... params) 
    { 
     String url = params[0]; 
     // your HTTP request code goes here 
     return response; 
    } 

    protected void onPostExecute(String result) 
    { 
     textView.setText(result); 
    } 
} 

使用类,像这样:

new MyAsyncTask(myTextView).execute(myUrl); 
+0

你会请给我一个例子,因为我是Android开发的新人@Tyler M. – 2013-03-03 17:21:28

+0

@RajatTrivedi谷歌它,所以你的问题充满了解决方案。 – 2013-03-03 17:40:51

+0

谢谢你的好友... @Tyler M. – 2013-03-04 11:22:11