今天照《第一行代碼》第10章敲出來的HttpURLConnection測試程序運行之後一直閃退,求大神指點,小白拜謝!
錯誤日志如下:
代碼如下:
package com.example.networktest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity implements OnClickListener {
public static final int SHOW_RESPONSE = 0;
private TextView textView;
private Button button;
private Handler handler = new Handler() {
public void handlerMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
// 更新UI操作
textView.setText(response);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
textView = (TextView) findViewById(R.id.sendRequest);
button = (Button) findViewById(R.id.responseText);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.sendRequest) {
sendRequsetWithHttpURLConnection();
}
}
private void sendRequsetWithHttpURLConnection() {
// 開啟線程來發起網絡請求
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
// 對獲取到的輸入流進行解析
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line ;
while ((line=reader.readLine()) != null) {
response.append(line);
}
// 發送返回結果
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
看你的日志你好像是把textview設置到button中了,就是你findviewbyid獲取的是textview但是賦值給button了,