web services - WSDL calling from Android causes NetworkOnMainThreadException -
here sample code (mainactivity):
private static final string soap_action = "http://tempuri.org/celsiustofahrenheit"; private static final string method_name = "celsiustofahrenheit"; private static final string namespace = "http://tempuri.org/"; private static final string url = "http://www.w3schools.com/webservices/tempconvert.asmx"; textview tv; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); tv = (textview)findviewbyid(r.id.text1); soapobject request = new soapobject(namespace, method_name); request.addproperty("celsius", "32"); soapserializationenvelope soapenvelope = new soapserializationenvelope(soapserializationenvelope.ver11); soapenvelope.dotnet = true; soapenvelope.setoutputsoapobject(request); httptransportse aht = new httptransportse(url); try { aht.call(soap_action, soapenvelope); soapprimitive resultstring = (soapprimitive)soapenvelope.getresponse(); tv.settext("status: " + resultstring); } catch (exception e) { tv.settext("problem: " + e.tostring()); } } @override public boolean oncreateoptionsmenu(menu menu) { ...
when run code got message problem: android.os.networkonmainthreadexception. in manifest.xml added
<uses-permission android:name="android.permission.internet" /> line. here whole android project.
does have idea how change code? thank in advance can provide.
try this..
networkonmainthreadexception throws when performing network operation on main thread.
so have run network operations in asynctask
you can call asynctask below
new serializationconnection().execute(url); then serializationconnection class
class serializationconnection extends asynctask<string, void, string> { protected string doinbackground(string... urls) { try { soapobject request = new soapobject(namespace, method_name); request.addproperty("celsius", "32"); soapserializationenvelope soapenvelope = new soapserializationenvelope(soapserializationenvelope.ver11); soapenvelope.dotnet = true; soapenvelope.setoutputsoapobject(request); httptransportse aht = new httptransportse(urls[0]); aht.call(soap_action, soapenvelope); soapprimitive resultstring = (soapprimitive)soapenvelope.getresponse(); return "status: " + resultstring; } catch (exception e) { return "problem: " + e.tostring(); } } protected void onpostexecute(string result) { tv.settext(result); } }
Comments
Post a Comment