getting error on setAdapter in AsyncTAsk? - android

I added the Row_Cursor_Adapter globally and made changes after adding onPostExecute() method in the Service_ivr AsyncTask.This is the updated code.
class Service_ivr extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... param)
{
SoapObject request = new SoapObject(NAMESPACE ,METHOD_NAME);
request.addProperty("user_id",param[0]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
envelope.dotNet =true;
envelope.setOutputSoapObject(request);
try
{
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject obj2 = (SoapObject)envelope.getResponse();
int count = obj2.getPropertyCount();
index = count/7;
final lead_content_IVR [] total_ivr_data = new lead_content_IVR[index];
for(int i=0; i<index ;i++)
{
String call_duration;
String lead_id = obj2.getPropertyAsString(i*7+0);
String lead_call_from = obj2.getPropertyAsString(i*7+1);
String lead_call_to = obj2.getPropertyAsString(i*7+2);
String lead_date=obj2.getPropertyAsString(i*7+3);
String lead_audio=obj2.getPropertyAsString(i*7+4);
String assign_id = obj2.getPropertyAsString(i*7+5);
String time = obj2.getPropertyAsString(i*7+6);
if(lead_call_from.equals("Welcome Sound") || lead_call_from.equals("Call Missed") || lead_call_from.equals("User Disconnected") || lead_call_from.equals("Customer Missed"))
{
call_duration= "5 sec";
}
else
{
call_duration = time.toString().concat(" sec");
}
total_ivr_data[i] = new lead_content_IVR(lead_id,lead_call_from,lead_call_to,lead_date,lead_audio,assign_id,call_duration);
}
adapter = new RowCursorAdapter_IVR(Activity_IVR_Lead.this, R.layout.listview_layout_ivr,total_ivr_data);
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
listView.setAdapter(adapter);
}
}
As u suggest i update the code but error is same all the time.

Change your method like so
class service_ivr extends AsyncTask<String, Void, String>
{
#Override
protected lead_content_IVR[] doInBackground(String... param)
{
SoapObject request = new SoapObject(NAMESPACE ,METHOD_NAME);
request.addProperty("user_id",param[0]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
envelope.dotNet =true;
envelope.setOutputSoapObject(request);
lead_content_IVR [] total_ivr_data = null;
try
{
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject obj2 = (SoapObject)envelope.getResponse();
int count = obj2.getPropertyCount();
index = count/7;
total_ivr_data = new lead_content_IVR[index];
for(int i=0; i<index ;i++)
{
String call_duration;
String lead_id = obj2.getPropertyAsString(i*7+0);
String lead_call_from = obj2.getPropertyAsString(i*7+1);
String lead_call_to = obj2.getPropertyAsString(i*7+2);
String lead_date=obj2.getPropertyAsString(i*7+3);
String lead_audio=obj2.getPropertyAsString(i*7+4);
String assign_id = obj2.getPropertyAsString(i*7+5);
String time = obj2.getPropertyAsString(i*7+6);
if(lead_call_from.equals("Welcome Sound") || lead_call_from.equals("Call Missed") || lead_call_from.equals("User Disconnected") || lead_call_from.equals("Customer Missed"))
{
call_duration= "5 sec";
}
else
{
call_duration = time.toString().concat(" sec");
}
total_ivr_data[i] = new lead_content_IVR(lead_id,lead_call_from,lead_call_to,lead_date,lead_audio,assign_id,call_duration);
}
}catch(Exception e)
{
e.printStackTrace();
}
return total_ivr_data;
}
public void onPostExecute(lead_content_IVR [] total_ivr_data ) {
RowCursorAdapter_IVR adapter = new RowCursorAdapter_IVR(Activity_IVR_Lead.this, R.layout.listview_layout_ivr,total_ivr_data);
listView.setAdapter(adapter);
}
}

Related

I'm Unable to setText of a TextView in a class (Android)

I'm using SOAP, In AsyncTask classs I'm trtying to set text of driverIDText, shipmentIDText, freightShipment textviews but it's saying unable to resolve setText()
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_up);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView driverIDText = (TextView) findViewById(R.id.text_DriverID);
TextView shipmentIDText = (TextView) findViewById(R.id.text_ShipmentID);
TextView freightShipment = (TextView) findViewById(R.id.text_FreightShipment);
new RetrieveFeedTask(driverIDText.getText.toString(),
shipmentIDText.getText().toString(),
freightShipment.getText().toString()
).execute();
}
class RetrieveFeedTask extends AsyncTask<String, String, Void> {
private String driverIDText, shipmentIDText, freightShipment;
RetrieveFeedTask(String driverIDText, String shipmentIDText, String freightShipment) {
this.driverIDText = driverIDText;
this.shipmentIDText = shipmentIDText;
this.freightShipment = freightShipment;
}
protected Void doInBackground(String... urls) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("DriverID", driverIDText);
request.addProperty("ShipmentID", shipmentIDText);
request.addProperty("FreightShipment", freightShipment);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
if (result != null) {
// HERE IS PROBLEM IN SETTEXT()
driverIDText.setText(result.getProperty(0).toString());
} else {
Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Inside AsyncTask you declared driverIDText as String not TextView, So Create one more param for TextView and send driverIDText(TextView) from Oncreate and set the data in textView in onPostExecute.
Ex:
class RetrieveFeedTask extends AsyncTask<String, String, String> {
private String driverIDText, shipmentIDText, freightShipment;
private TextView driverIDTextTv;
RetrieveFeedTask(String driverIDText, String shipmentIDText, String freightShipment, TextView textView) {
this.driverIDText = driverIDText;
this.shipmentIDText = shipmentIDText;
this.freightShipment = freightShipment;
driverIDTextTv = textView;
}
#Override
protected void onPostExecute(String text) {
super.onPostExecute(text);
driverIDTextTv.setText(text);
}
protected String doInBackground(String... urls) {
String localDriverId = "";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("DriverID", driverIDText);
request.addProperty("ShipmentID", shipmentIDText);
request.addProperty("FreightShipment", freightShipment);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
if (result != null) {
// HERE IS PROBLEM IN SETTEXT()
// driverIDText.setText(result.getProperty(0).toString());
localDriverId = result.getProperty(0).toString();
} else {
Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return localDriverId;
}
}
and you can call AsyncTask like this,
new RetrieveFeedTask(driverIDText.getText.toString(),
shipmentIDText.getText().toString(),
freightShipment.getText().toString(), driverIDText
).execute();

Async Task with multiple requests in android

I am using this asynctask Class to update two different tables on Sql Server so far this code works fine i'm interested in more better and sufficient code structure of this class specially in doinbackground() Is it okay to call multiple webservices methods in a single thread? can any one suggest me?
private class Update extends AsyncTask<Void, Void, Integer> {
private final int FAILED_INVALID_RESPONSE = 0;
private final int SUCCESS_GET_DATA = 1;
ProgressDialog progress;
private String _phoneno;
private String _ticket;
UpdateTicket(String phoneno,String ticket){
_phoneno=phoneno;
_ticket=ticket;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(XYZ.this, "",
"In Progress...", false);
}
#Override
protected Integer doInBackground(Void... params) {
method1(_phoneno);
return method2(_phoneno,_ticket);
}
#Override
protected void onPostExecute(Integer result) {
progress.dismiss();
switch (result) {
case FAILED_INVALID_RESPONSE:
Toast.makeText(XYZ.this,"Please Check your Internet Connection.",Toast.LENGTH_SHORT).show();
break;
case SUCCESS_GET_DATA:
Toast.makeText(XYZ.this, "Success!", Toast.LENGTH_SHORT).show();
break;
}
}
int method1(String phoneno,String tickets)
{
final String methodname = "firstmethod";
final String NAMESPACE ="http://tempuri.org/";
final String URL="www.sampleurl.com";
final String SOAP_ACTION="http://tempuri.org/firstmethod";
int success=0;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SoapObject request = new SoapObject(NAMESPACE, methodname);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
request.addProperty("phoneno", phoneno);
request.addProperty("tickets", tickets);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION,envelope);
SoapObject response = (SoapObject) envelope.bodyIn;
if(response!=null){
success=1;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return success;
}
int method2(String Phone) {
final String methodname = "secondmethod";
final String NAMESPACE ="http://tempuri.org/";
final String URL="www.sampleurl.com";
final String SOAP_ACTION="http://tempuri.org/secondmethod";
int success=0;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SoapObject request = new SoapObject(NAMESPACE, methodname);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
request.addProperty("phoneno", phoneno);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION,envelope);
SoapObject response = (SoapObject) envelope.bodyIn;
if(response!=null){
success=1;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return success;
}
}
AsyncTask should only be used for tasks/operations that take quite few seconds.
AsyncTasks are executed serially on a single background thread (from API 11). So long running worker can block others.
Check some other gotchas.
Take a look at HeandlerThread.

How to use common methods in some other class and use that in another class android?

I am using soap in which the code is running fine but there are some common methods which I need to use in some other class and use it in all activities.
But I don't know how to separate the methods and use it. Please guide me to solve this. Here is my code..
class A extend Activity{
private String sessionId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.sortfilterclick);
new CommonElement().execute();
}
class CommonElement extends AsyncTask<String, String, String> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(CommonElement.this);
dialog.show();
dialog.setCancelable(false);
}
#Override
protected String doInBackground(String... args) {
try {
// these are all common
SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.API_URL);
sessionId = Utils.readPreferences(CommonElement.this,Constants.SESSION_ID, null);
if (sessionId == null) {
SoapObject request = new SoapObject(Constants.NAMESPACE, "login");
request.addProperty("username", "Clothing");
request.addProperty("apiKey", "Clothing");
env.setOutputSoapObject(request);
androidHttpTransport.call("", env);
Object result = env.getResponse();
sessionId = result.toString();
Utils.savePreferences(CommonElement.this,
Constants.SESSION_ID, sessionId);
}// till this it's common
//here json reuest datas varies in json.put()...
SoapObject requests = new SoapObject(Constants.NAMESPACE, "call");//these are common
requests.addProperty("sessionId", sessionId);//these are common
requests.addProperty("resourcePath","sortap.Action"); //this will change for every property
JSONObject json = new JSONObject();// these will change
json.put("page", "1");
json.put("limit", "10");
json.put("name", sortName);
json.put("order", sortOrder);
json.put("id", "3");
json.put("cate_id", "4");
String params = json.toString();
requests.addProperty("args", params);
env.setOutputSoapObject(requests);
androidHttpTransport.call("", env);
Object results = env.getResponse();
//based on various request and response this varies.
if (results.toString() != null) {
JSONObject jsono = new JSONObject(results.toString());
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
String id = object.getString("id");
String productName = object.getString("product_name");
String imageUrl = object.getString("image_url");
int productPrice = object.getInt("price");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.cancel();
}
==========================
this is my changes that I done..==============================
public final class SoapCommon {
public static String sessionId;
public static String id;
public static String SessionIdNull(){
try{
SoapSerializationEnvelope env = new SoapSerializationEnvelope(
SoapSerializationEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
HttpTransportSE androidHttpTransport = new HttpTransportSE(
Constants.API_URL);
SoapObject request = new SoapObject(
Constants.NAMESPACE, "login");
request.addProperty("username", "Clothing");
request.addProperty("apiKey", "Clothing");
env.setOutputSoapObject(request);
androidHttpTransport.call("", env);
Object result = env.getResponse();
sessionId = result.toString();
}
catch (Exception e) {
e.printStackTrace();
}
return sessionId;
}
public static final void noSession(){
try{
SoapSerializationEnvelope env = new SoapSerializationEnvelope(
SoapSerializationEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
HttpTransportSE androidHttpTransport = new HttpTransportSE(
Constants.API_URL);
SoapObject requests = new SoapObject(
Constants.NAMESPACE, "call");
requests.addProperty("sessionId", sessionId);
env.setOutputSoapObject(requests);
androidHttpTransport.call("", env);
Object results = env.getResponse();
androidHttpTransport.call("", env);
Object result = env.getResponse();
sessionId = result.toString();
}
catch (Exception e) {
e.printStackTrace();
}
}
and in another activity:
void doInBackground {
try {
// here
sessionId = Utils.readPreferences(
SortFilterPopupActivity.this,
Constants.SESSION_ID, null);
if (sessionId == null) {
// I splitted and used but don't know how to use here.
Utils.savePreferences(
CommonElement.this,
Constants.SESSION_ID, sessionId);
}
// same here too
env.setOutputSoapObject(requests);
androidHttpTransport.call("", env);
Object results = env.getResponse();
Log.e("Sort results", results.toString());
if (results.toString() != null) {
........
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
But strucked in this issue.
If the methods can be instanceless then create a utilytie class like so:
public Utils {
public static void doSomethingUsefull(Param p) {
}
}
Then you can use this method/s of this class without an instance in any other class like so:
...
Utils.doSomethingUfesul(p);
...
Other wise create a real class with an constructor and so on.
public StatefullUtils {
public StatefullUtils(Param p) {
this.p = p;
...
}
public void doSomethingUsefull() {
p++;
...
}
}
Then you can use this class everywhere else by:
StatefullUtils utils = new StatefullUtils(p);
utils.doSomethingUsefull();
Hope that helps.
Create a class and define a method within it..
Step 1 : Create Class & Define Methods..
Example :
public class CommonUtils {
// always create public method and define it a static method
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
Here, You can define public variables too, that can used all over the application..
Step 2 : Use it in another class..
Syntax : YOURCLASS.YOURMETHOD(PARAMETERS);
Example :
if (CommonUtils.isNetworkAvailable(mContext)) {
//do your code...
//i have defined it in IF condition because my method returns a value.. you can define it `void`...
}

result of web service?

i wrote a code using SOAP function to get from web service , the problem is that the response is not an xml string , what i need to know , the error from my android code SOAP function ? or from web service ?
why the result is liske this
public String SOAP_ACTION2 = "http://tempuri.org/GetDataTable";
public String OPERATION_NAME2 = "GetDataTable";
public String SOAP_ADDRESS2 = "http://192.168.0.15/EServicedesk/DesktopModules/EServiceDesk.Website/ESDWebService/Auth.asmx?WSDL";
Object response;
String XMLData = null;
SoapSerializationEnvelope envelope;
SoapRequestTask2 task;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
task = new SoapRequestTask2();
try {
XMLData = task.execute().get();
Log.i("task ", XMLData);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class SoapRequestTask2 extends AsyncTask<Void, Void, String> {
// runs on ui thread.
private String data;
protected void onPreExecute() {
}
// runs in the background thread. do not update ui from here
protected String doInBackground(Void... params) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME2);
PropertyInfo pi = new PropertyInfo();
pi.setName("UserID");
pi.setValue(193);
pi.setType(Integer.class);
request.addProperty(pi);
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS2);
response = null;
try {
// httpTransport.debug=true;
httpTransport.call(SOAP_ACTION2, envelope);
// String ss = httpTransport.requestDump;
response = envelope.getResponse();
data = response.toString();
// Log.i("respons", envelope.getResponse().toString());
} catch (Exception exception) {
response = exception.toString();
XMLData = response.toString();
}
return data;
}
here is the result :
task 2: anyType{schema=anyType{element=anyType{complexType=anyType{choice=anyType{element=anyType{complexType=anyType{sequence=anyType{element=anyType{}; element=anyType{}; }; }; }; }; }; }; }; diffgram=anyType{DocumentElement=anyType{TargetTable=anyType{RequestHotList=MyRequests; Count=927; }; TargetTable=anyType{RequestHotList=MyAssignedRequests; Count=603; }; TargetTable=anyType{RequestHotList=MyServiceDeskRequests; Count=969; }; TargetTable=anyType{RequestHotList=MyWorkGroupRequests; Count=770; }; TargetTable=anyType{RequestHotList=MyApproval; Count=82; }; }; }; }
you can do something like this
Web service returns array of object
you can get value for each value for each object by going to perticular node then use getProperty() method to get value for required object as follow.
//old web services.
public void getLocation()
{
OPERATION_NAME = "GetLd";
SOAP_ACTION = Constants.strNAMESPACE+""+OPERATION_NAME;
REQUST_ID=3;
final Responce responce=new Responce();
Thread thread=new Thread(new Runnable()
{
SoapObject response;
#Override
public void run()
{
try
{
SoapObject request=new SoapObject(Constants.strNAMESPACE, OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(Constants.strWEB_SERVICE_URL);
ht.call(SOAP_ACTION, envelope);
response = (SoapObject)envelope.bodyIn;
if(response!=null)
{
SoapObject str = null;
for(int i=0;i<response.getPropertyCount();i++)
str=(SoapObject) response.getProperty(i);
SoapObject str1 = (SoapObject) str.getProperty(0);
SoapObject str2 = null;
ArrayList<Location> arrData=new ArrayList<Location>();
for(int j=0;j<str1.getPropertyCount();j++)
{
str2 = (SoapObject) str1.getProperty(j);
Location location=new Location();
if(str2!=null)
{
responce.Result_Type=Constants.DataPresent;
if(isValidProperty(str2, "LocationName"))
{
location.setName(str2.getProperty("LocationName").toString());
}
if(isValidProperty(str2, "LocationId"))
{
location.setId(Integer.parseInt(str2.getProperty("LocationId").toString()));
}
arrData.add(location);
}
else
{
responce.Result_Type=Constants.NoDataPresent;
}
}
responce.ResponceData=arrData;
Log.d("Location", "------------------------");
for(int i=0;i<arrData.size();i++)
Log.d("Tag", arrData.get(i).toString());
}
}
catch (Exception e)
{
e.printStackTrace();
responce.Result_Type=Constants.Error;
}
finally
{
Message message=new Message();
message.what=REQUST_ID;
message.arg1=responce.Result_Type;
message.obj=responce;
handler.sendMessage(message);
}
}
});
thread.start();
}
boolean isValidProperty(SoapObject soapObject,String PropertyName)
{
if(soapObject!=null)
{
if(soapObject.hasProperty(PropertyName))
{
if(!soapObject.getProperty(PropertyName).toString().equalsIgnoreCase("")&&!soapObject.getProperty(PropertyName).toString().equalsIgnoreCase("anyType{}"))
return true;
else
return false;
}
return false;
}
else
return false;
}

Android Soap Web service Error behind Proxy Server

I have written a program for communicating with a web service and get response value. But when i debug the programme i end with requestDump=null at the line androidHttpTransport.call(SOAP_ACTION, envelope); Can some one tell me the reason for the error and what can i do for this
public class WebService extends Activity {
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
private final String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
private final String METHOD_NAME = "CelsiusToFahrenheit";
String celsius;
Button b;
TextView tv;
EditText et;
String res,resultval;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_service);
et=(EditText)findViewById(R.id.editText1);
tv=(TextView)findViewById(R.id.Result);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//String result=getFarenheit(et.getText().toString());
//tv.setText(result+"°F");
new service().execute();
}
});
}
private class service extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... arg0) {
celsius=et.getText().toString();
SoapObject request= new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo celsuiusPI= new PropertyInfo();
celsuiusPI.setName("Celsius");
celsuiusPI.setValue(celsius);
celsuiusPI.setType(String.class);
request.addProperty("XMLMarks",celsuiusPI);
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope (SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.implicitTypes = true;
envelope.enc = SoapSerializationEnvelope.ENC2003;
envelope.xsd = SoapEnvelope.XSD;
envelope.xsi = SoapEnvelope.XSI;
envelope.setOutputSoapObject(request);
envelope.setAddAdornments(false);
SoapPrimitive response;
HttpTransportSE androidHttpTransport=new HttpTransportSE(URL);
try{
androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);
String dump= androidHttpTransport.requestDump.toString();
response=(SoapPrimitive)envelope.getResponse();
Toast.makeText(WebService.this, response.toString(), 20).show();
Log.i("WebService output", response.toString());
System.out.println("WebService Response"+response.toString());
Object res= response.toString();
resultval=(String) res;
}
catch(Exception e){
e.printStackTrace();
}
return res;
}
protected void onPostExecute(String h){
String result=h;
tv.setText(result+"°F");
}
}
}
Just replace your service AsyncTask with this new one and see result:
code:
private class service extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... arg0) {
System.out.println("In DoIn Background");
// Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Use this to add parameters
request.addProperty("Celsius", txtCel.getText().toString());
// Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
// this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject) envelope.bodyIn;
if (result != null) {
// Get the first property and change the label text
// txtFar.setText(result.getProperty(0).toString());
res = result.getProperty(0).toString();
} else {
Toast.makeText(getApplicationContext(), "No Response",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
protected void onPostExecute(String h) {
String result = h;
tv.setText(result + "°F");
}
}

Categories

Resources