在代码中,我尝试使用 http 客户端从 Web 服务中读取数据。然后我想将http响应的响应短语写入文本视图。UI 是通过 onPostExecute() 访问的,所以我不知道为什么会出现这个异常。
这是代码:
public class CustomersScreen extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customersscreen);
}
public void LoginClicked(View view) {
new Get_data().execute("http://localhost:51982/WcfDataService1.svc/Genre");
}
private class Get_data extends AsyncTask <String, Void, String> {
@Override
protected String doInBackground(String... url) {
//InputStream instream = null;
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(url[0]);
HttpResponse response = null;
try {
response = httpclient.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String phrase = response.getStatusLine().getReasonPhrase();
return phrase;
}
@Override
protected void onPostExecute(String phrase) {
TextView t = (TextView) findViewById(R.id.textView3);
t.setText(phrase);
}
}
}
和日志猫:
09-28 09:43:34.239: E/AndroidRuntime(679): FATAL EXCEPTION: AsyncTask #1
09-28 09:43:34.239: E/AndroidRuntime(679): java.lang.RuntimeException: An error occured while executing doInBackground()
09-28 09:43:34.239: E/AndroidRuntime(679): at android.os.AsyncTask$3.done(AsyncTask.java:278)
09-28 09:43:34.239: E/AndroidRuntime(679): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
09-28 09:43:34.239: E/AndroidRuntime(679): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
09-28 09:43:34.239: E/AndroidRuntime(679): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
09-28 09:43:34.239: E/AndroidRuntime(679): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-28 09:43:34.239: E/AndroidRuntime(679): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
09-28 09:43:34.239: E/AndroidRuntime(679): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-28 09:43:34.239: E/AndroidRuntime(679): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-28 09:43:34.239: E/AndroidRuntime(679): at java.lang.Thread.run(Thread.java:856)
09-28 09:43:34.239: E/AndroidRuntime(679): Caused by: java.lang.NullPointerException
09-28 09:43:34.239: E/AndroidRuntime(679): at com.test.CustomersScreen$Get_data.doInBackground(CustomersScreen.java:46)
09-28 09:43:34.239: E/AndroidRuntime(679): at com.test.CustomersScreen$Get_data.doInBackground(CustomersScreen.java:1)
09-28 09:43:34.239: E/AndroidRuntime(679): at android.os.AsyncTask$2.call(AsyncTask.java:264)
09-28 09:43:34.239: E/AndroidRuntime(679): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-28 09:43:34.239: E/AndroidRuntime(679): ... 5 more