编辑:
我知道它返回空指针,但是它的原因是,它是某些Web服务还是代码问题?
我正在从Android调用外部WebService(celcius到Farenheit Demo)。
它给了我以下错误
Attempt to invoke virtual method 'java.lang.String org.ksoap2.serialization.SoapPrimitive.toString()' on a null object reference
我没有太多的代码,只有MainActivity类和异步类
public class MainActivity extends AppCompatActivity {
String TAG = "Response";
Button bt;
EditText celcius;
String getCel;
SoapPrimitive resultString;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.bt);
celcius = (EditText) findViewById(R.id.cel);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getCel = celcius.getText().toString();
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
});
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
@Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
calculate();
return null;
}
public void calculate() {
String SOAP_ACTION = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
String METHOD_NAME = "CelsiusToFahrenheit";
String NAMESPACE = "http://www.w3schools.com/webservices/";
String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
try {
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
Request.addProperty("Celsius", getCel);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport = new HttpTransportSE(URL);
transport.call(SOAP_ACTION, soapEnvelope);
resultString = (SoapPrimitive) soapEnvelope.getResponse();
Log.i(TAG, "Result Celsius: " + resultString);
} catch (Exception ex) {
Log.e(TAG, "Error: " + ex.getMessage());
}
}
@Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
Toast.makeText(MainActivity.this, "Response" + resultString.toString(), Toast.LENGTH_LONG).show();
}
}
Logcat显示
Attempt to invoke virtual method 'java.lang.String
org.ksoap2.serialization.SoapPrimitive.toString()' on a null object
reference at testproject.example.com.sensor_new.MainActivity$AsyncCallWS.onPostExecute(MainActivity.java:89)
我看到一些解决方案在清单中应用Internet设置并在DoBackGround中进行计算。但这并没有解决任何问题,
任何帮助将不胜感激