I'm Unable to setText of a TextView in a class (Android) - 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();

Related

Response from SOAP webservice always returns null Android studio

Im trying to get some response from several SOAP webservices at last i tried to run a code that is a well very known example on the internet. But i realized that even this doesnt run on my project. I hardly tried to understand what the error could be but i dont know why its not working with soap.
I would really appriacate your help.
Downloaded new version of KSOAP2 and also permission for internet is given.
public class WEBSERVİCE extends AppCompatActivity {
Button btn;
EditText et;
TextView txv;
String celcius="21";
String fahren;
private String NAMESPACE = "https://www.w3schools.com/xml/";
private String METHOD_NAME = "CelsiusToFahrenheit";
private String SOAP_ACTİON = "https://www.w3schools.com/xml/CelsiusToFahrenheit";
private String URL = "https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit?WSDL";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.button);
txv = findViewById(R.id.textView);
et = findViewById(R.id.editText1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
});
}
private class AsyncCallWS extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
txv.setText("calculating");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... objects) {
return getBolum(celcius);
}
#Override
protected void onPostExecute(String o) {
txv.setText(fahren + "F");
super.onPostExecute(o);
}
}
public String getBolum(String celsius) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("Celcius");
pi.setValue(celsius);
pi.setType(double.class);
request.addProperty(pi);
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHTTPTransport = new HttpTransportSE(URL);
try {
androidHTTPTransport.call(SOAP_ACTİON, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
fahren = response.toString();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return fahren;
}
}
No Error Messages but the value it turns back is always "null"
EDIT:posted changed code again
There isn't anything wrong with SOAP Api. The problem is your AsyncTask class. Read the documentation for AsyncTask first. Please do proper research before you use any code from internet. Always read about the components that are used snippets on internet otherwise you are going to have hard time figuring out problems.
Your AsyncTask class is declared as:
private class AsyncCallWS extends AsyncTask<String,Void,Void>
Change it to
private class AsyncCallWS extends AsyncTask<String,Void,String>
Third generic parameter in your Void which is supposed to be result type. So in your case your async task won't return any data once it is finished.
//CHANGE TYPE TO STRING
public String getBolum(String celsius) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi=new PropertyInfo();
pi.setName("Celcius");
pi.setValue(celsius);
pi.setType(double.class);
request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHTTPTransport = new HttpTransportSE(URL);
try {
androidHTTPTransport.call(SOAP_ACTİON, envelope);
SoapPrimitive response= (SoapPrimitive) envelope.getResponse();
//RETURN RESULT
return response.toString();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
//I forgot this line previously:
return "";
}}
In your async task, you need to change return type of doInBackground and paramter of onPostExecute to String:
#Override
protected String doInBackground(String... objects) {
return getBolum(celcius); //RETURN RESULT
}
#Override
protected void onPostExecute(String result) {
txv.setText(result+"F");
fahren = result;
super.onPostExecute(result);
}
It should work now.

Image loading using picasso library from url

initially, I am fetching image URL from server to a string then using Picasso library I am trying to load the image
I am able to get image URL from the server like thislogcat
but image not loaded in the image view. when tried placing direct URL it works.
public class MainActivity extends AppCompatActivity {
ImageView im;
Button bm;
String str ;
private static String NAMESPACE = "http://telview360/";
private static String URL = "http://54.179.134.139/viView360Service/WebService.asmx?WSDL";
private static String SOAP_ACTION = "http://telview360/ImageDetails";
private static String METHOD_NAME = "ImageDetails";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_image);
final Thread networkThread = new Thread() {
#Override
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
str = response.toString();
Log.d("Webservice", " response " + str);
} catch (Exception e) {
e.printStackTrace();
}
}
};
networkThread.start();
bm = (Button) findViewById(R.id.btn_load_image);
bm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
im = (ImageView) findViewById(R.id.image);
Picasso.with(getApplicationContext()).load(str).into(im);
}
});
}
}
add this to your code
final Thread networkThread = new Thread() {
#Override
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
str = response.toString();
Log.d("Webservice", " response " + str);
} catch (Exception e) {
e.printStackTrace();
}
}
};
networkThread.start();
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
it will work

getting error on setAdapter in AsyncTAsk?

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);
}
}

Android:unable to get data from webservice using kSoap

hi in my app i am trying to check the username and password in database from webservice and if its true will show success message or failed message, but unable to show the status message
public class AndroidLoginExampleActivity extends Activity {
private final String NAMESPACE = "http://ws.userlogin.com";
private final String URL = "http://localhost:8080/Androidlogin/services/Login?wsdl";
private final String SOAP_ACTION = "http://ws.userlogin.com/authentication";
private final String METHOD_NAME = "authentication";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
loginAction();
}
});
}
#SuppressLint("NewApi") private void loginAction(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
EditText userName = (EditText) findViewById(R.id.tf_userName);
String user_Name = userName.getText().toString();
EditText userPassword = (EditText) findViewById(R.id.tf_password);
String user_Password = userPassword.getText().toString();
//Pass value for userName variable of the web service
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("userName");//Define the variable name in the web service method
unameProp.setValue(user_Name);//set value for userName variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);//Pass properties to the variable
//Pass value for Password variable of the web service
PropertyInfo passwordProp =new PropertyInfo();
passwordProp.setName("password");
passwordProp.setValue(user_Password);
passwordProp.setType(String.class);
request.addProperty(passwordProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
TextView result = (TextView) findViewById(R.id.tv_status);
result.setText(response.toString());
Log.d("resp:",response.toString() );
}
catch(Exception e){
}
}
below is my webservice call
public class Login {
public String authentication(String userName,String password){
String retrievedUserName = "";
String retrievedPassword = "";
String status = "";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","root");
PreparedStatement statement = con.prepareStatement("SELECT * FROM user WHERE username = '"+userName+"'");
ResultSet result = statement.executeQuery();
while(result.next()){
retrievedUserName = result.getString("username");
retrievedPassword = result.getString("password");
}
if(retrievedUserName.equals(userName)&&retrievedPassword.equals(password)){
status = "Success!";
}
else{
status = "Login fail!!!";
}
}
catch(Exception e){
e.printStackTrace();
}
return status;
}
}
not sure were iam doing wrong.Any help is appreciated.
You should do network realted operation on a thread. You can use a thread or AsyncTask.
Move your loginAction() inside a thread or inside doInbackground of AsyncTask.
Remember not to update ui from the back ground thread.
new TheTask().execute();
AsyncTask
public class TheTask extends AsyncTask <Void,Void,Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
// display a dialog
}
#Override
protected Void doInBackground(Void... params) {
// your login authentcation
// remove updation of textview.
// do not update ui here
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// dismiss the dialog
// update textview
}
}
AsyncTask docs
http://developer.android.com/reference/android/os/AsyncTask.html
Edit:
public class MainActivity extends Activity {
private final String NAMESPACE = "http://ws.userlogin.com";
private final String URL = "http://localhost:8080/Androidlogin/services/Login?wsdl";
private final String SOAP_ACTION = "http://ws.userlogin.com/authentication";
private final String METHOD_NAME = "authentication";
/** Called when the activity is first created. */
EditText ed1,ed2;
TextView tv;
String user_Name,user_Password;
SoapPrimitive response ;
ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1 = (EditText) findViewById(R.id.editText1);
ed2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView1);
user_Name = ed1.getText().toString();
user_Password = ed2.getText().toString();
pd = new ProgressDialog(this);
Button login = (Button) findViewById(R.id.button1);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new TheTask().execute();
}
});
}
class TheTask extends AsyncTask<Void,Void,SoapPrimitive>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.show();
}
#Override
protected SoapPrimitive doInBackground(Void... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("userName");//Define the variable name in the web service method
unameProp.setValue(user_Name);//set value for userName variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);//Pass properties to the variable
PropertyInfo passwordProp =new PropertyInfo();
passwordProp.setName("password");
passwordProp.setValue(user_Password);
passwordProp.setType(String.class);
request.addProperty(passwordProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
response = (SoapPrimitive) envelope.bodyIn;
Log.i("Response",""+response);
// response = (SoapPrimitive)envelope.getResponse();
}
catch(Exception e){
}
return response;
}
#Override
protected void onPostExecute(SoapPrimitive result) {
super.onPostExecute(result);
pd.dismiss();
if(result!=null)
tv.setText(result.toString());
}
}
}
public static String ValidateSalesOfficerLogin(Context c, String userName,
String passWord) throws IOException, XmlPullParserException {
String METHOD_NAME = "ValidateSalesOfficerLogin";
String SOAP_ACTION = "http://tempuri.org/authentication/";
SOAP_ACTION = SOAP_ACTION + METHOD_NAME;
SoapObject request = new SoapObject(CommonVariable.NAMESPACE,
METHOD_NAME);
// Use this to add parameters
request.addProperty("Username", userName);
request.addProperty("Password", passWord);
// Declare the version of the SOAP request
return WebCalls.call(c, request, CommonVariable.NAMESPACE, METHOD_NAME,
SOAP_ACTION);
}
//////////////////////////////////////////////////////////////////////////////
public static String call(Context c,SoapObject request ,String NAMESPACE,String METHOD_NAME,String SOAP_ACTION) throws IOException, XmlPullParserException{
Log.i(WebCalls,"URL: "+ CommonVariable.URL);
Log.i(WebCalls,"Method Name: "+ METHOD_NAME);
Log.i(WebCalls,"Parameters: "+request.toString());
String SoapResult = null;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(CommonVariable.URL);
// this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
if (envelope.bodyIn instanceof SoapFault) {
SoapResult = ((SoapFault) envelope.bodyIn).faultstring;
} else {
SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
SoapResult = resultsRequestSOAP.getProperty(0).toString();
}
Log.i(WebCalls,"Response: "+ SoapResult);
return SoapResult;
}
call above method....
public static void Setusernamepassword(Context context, String user ,string pass)
throws JSONException, IOException, XmlPullParserException {
String Response = SoaplCalls.ValidateSalesOfficerLogin(context, user,pass);
Log.i("SetTokenId", Response);
}
/////////////////////////////////////////////////////////////////////////////////////
new Thread(new Runnable() {
#Override
public void run() {
try {
Setusernamepassword(viewCompetitor,user,pass);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
mHandler.post(new Runnable() {
#Override
public void run() {
}
});
}
}
}).start();
}

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