我試圖從servlet獲取響應並將其顯示在模擬器上。能夠獲得響應,但是當我試圖在屏幕上顯示響應時,setText正在拋出空指針異常。無法找出原因。我很新的android,請幫助我。setText在嘗試在onPostExecute方法中顯示數據時拋出nullpointerexception
package com.example.httptest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.demo.parser.XmlParser;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final String url = "http://192.168.3.140:8080/HttpServlet/TestServlet";
//public static final String url = "http://192.168.3.228/capture/employeeList.xml";
String output = null;
TextView outpuText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void invokeServlet(View view){
AsyncTest test = new AsyncTest();
System.out.println("URL--------------"+url);
setContentView(R.layout.activity_main);
test.execute(new String[] { url });
}
private class AsyncTest extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
String output = null;
for(String url :urls){
System.out.println("url1 "+url);
output = getOutputFromUrl(url);
System.out.println("output----------"+output);
/*EditText text = (EditText) findViewById(R.id.output);
text.setText(output);
*/
}
return output;
}
private String getOutputFromUrl(String url) {
System.out.println("in hereeeeeeeeeee");
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
System.out.println("output1 "+output);
// XmlParser.XMLfromString(output);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
protected void onPostExecute(String output){
setContentView(R.layout.activity_main);
outpuText.setText(output);
setContentView(outpuText);
}
}
}
告訴我們logcat ... –
向我們展示Log.d(「output」,output)的結果; ..... 你可以嗎? –