package com.example.exhttpclient; import java.io.BufferedReader; import java.io.Closeable; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.sql.Connection; import org.apache.http.client.HttpClient; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { final String TAG = "ExHttpClinet"; EditText eText; TextView tView; Button button; private Handler handler; private NetThread thread; class NetThread extends Thread{ @Override public void run(){ HttpURLConnection connection = null; try { URL url = new URL("http://www.baidu.com"); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(8000); int code = connection.getResponseCode(); System.out.println(code + ""); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuffer response = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { response.append(line); } Message lmsg = new Message(); lmsg.obj = response; lmsg.what=0; handler.sendMessage(lmsg); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } }; class MyHandler extends Handler{ public void handleMessage(Message msg){ switch (msg.what) { case 0: tView.setText(msg.obj.toString()); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); eText = (EditText) findViewById(R.id.address); tView = (TextView) findViewById(R.id.pagetext); button = (Button) findViewById(R.id.ButtonGo); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub thread = new NetThread(); thread.start(); } }); } }
错如大致在43行左右,什么东西一直是null导致错误, while循环没进。
10-18 06:50:15.470: W/System.err(4134): java.lang.NullPointerException: Attempt to invoke virtual method “boolean android.os.Handler.sendMessage(android.os.Message)” on a null object reference
10-18 06:50:15.470: W/System.err(4134): at com.example.exhttpclient.MainActivity$NetThread.run(MainActivity.java:52)
解决方案
5
MyHandler handler=new MyHandler();
Message lmsg = new Message();
lmsg.obj = response;
lmsg.what=0;
handler.sendMessage(lmsg);
这样就可以了
Message lmsg = new Message();
lmsg.obj = response;
lmsg.what=0;
handler.sendMessage(lmsg);
这样就可以了
35
本人私信给你了,你看看,你换一个Url看看