How to get data from SOAP response in android? - android

What I am trying to do is create a simple Web Service in ASP.NET and get Data from MSSQL server through that web service and use that data in my android application. As a novice, I have tried out this Helpful link to follow. I have used the same architecture as this tutorial suggest. But getting error in parsing the result (Soap Response) in my result. It is as below.
<?xml version="1.0" encoding="utf-8"?> <soap:Envelope
> xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
> xmlns:xsd="http://www.w3.org/2001/XMLSchema">
> <soap:Body><findContactResponse xmlns="http://tempuri.org/" />
> </soap:Body> </soap:Envelope>
and the GetPropertyCount() method is returning 0, on the other hand, arrayindexoutofBound error is coming up with index 0.
Here is my activity code. Where I have implemented async task for easy handling.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private static final String SOAP_ACTION = "http://tempuri.org/findContact";
private static final String OPERATION_NAME = "findContact";// your webservice web method name
private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
private static final String SOAP_ADDRESS = "http://10.0.2.2:58497/WebService/Service.asmx?wsdl";//"http://127.0.0.1:58497/WebService/Service.asmx";
protected static final String TAG = null;
TextView tvData1;
EditText edata;
Button button;
String studentNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData1 = (TextView)findViewById(R.id.textView1);
edata =(EditText)findViewById(R.id.editText1);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
studentNo=edata.getText().toString();
new Submit().execute(studentNo);
}
});
}
private class Submit extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... arg) {
// TODO Auto-generated method stub
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
PropertyInfo propertyInfo = new PropertyInfo();
propertyInfo.type = PropertyInfo.STRING_CLASS;
propertyInfo.name = "eid";
Log.e("studentNo", studentNo);
request.addProperty(propertyInfo);
request.addProperty("eid", studentNo);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
httpTransport.debug = true;
try {
httpTransport.call(SOAP_ACTION, envelope);
Log.e("Dump", httpTransport.responseDump.toString());
SoapObject result=(SoapObject)envelope.bodyIn;
if(result!= null){
Log.e("response", result.toString());
//To get the data.
System.out.println("********Count : "+ result.getPropertyCount());
String resultData=result.getProperty(0).toString();
Log.e("Found", resultData);
}
else{
Log.e("Obj", result.toString());
}
}
catch (Exception exception) {
Log.e("Not Found", exception.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
}
Now can anyone just show me what went wrong for me? Or how can I get my response without exception? After debugging I came up with this line which is creating exceptions.
String resultData=result.getProperty(0).toString();
Thanks is advance for any kind of help.

Finally figured it out.
It was in adding property. And slightly changing the response parsing.
Here is the complete code which worked out for me.
Hope it helps others.
private static final String SOAP_ACTION = "http://tempuri.org/findContact";
private static final String OPERATION_NAME = "findContact";// your webservice web method name
private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
private static final String SOAP_ADDRESS = "http://10.0.2.2:58497/WebService/Service.asmx";
protected static final String TAG = null;
private static String fahren;
TextView tvData1;
EditText edata;
Button button;
String studentNo;
String state;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData1 = (TextView)findViewById(R.id.textView1);
edata =(EditText)findViewById(R.id.editText1);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
studentNo=edata.getText().toString();
new Submit().execute(studentNo);
}
});
}
private class Submit extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg) {
// TODO Auto-generated method stub
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
PropertyInfo propertyInfo = new PropertyInfo();
propertyInfo.type = PropertyInfo.STRING_CLASS;
propertyInfo.name = "eid";
propertyInfo.setValue(studentNo);
request.addProperty(propertyInfo);//problem was here
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
httpTransport.debug = true;
try{
httpTransport.call(SOAP_ACTION, envelope);
Log.e("RequestDump", httpTransport.requestDump.toString());
Log.e("ResponseDump", httpTransport.responseDump.toString());
SoapObject result=(SoapObject)envelope.bodyIn;
if(result!= null){
state = result.getProperty(0).toString();
Log.e("Found", state);
}
else{
Log.e("Obj", result.toString());
}
}
catch (Exception exception) {
Log.e("Exception", exception.toString());
}
return state;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData1.setText(result);
}
}
}
I have implemented an async task as well to get rid of run time exceptions on Main thread. Need to add the request.addProperty(propertyInfo) properly.

Related

HttpTransport.call(SOAP_ACTION1, envelope) not working?

private static String SOAP_ACTION1 = "http://www.w3schools.com/webservices/FahrenheitToCelsius";
private static String SOAP_ACTION2 = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
private static String NAMESPACE = "http://www.w3schools.com/webservices/";
private static String METHOD_NAME1 = "FahrenheitToCelsius";
private static String METHOD_NAME2 = "CelsiusToFahrenheit";
private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
Button btnFar,btnCel,btnClear;
EditText txtFar,txtCel;
int value;
SoapObject result;
My code look like below
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFar = (Button)findViewById(R.id.btnFar);
btnCel = (Button)findViewById(R.id.btnCel);
btnClear = (Button)findViewById(R.id.btnClear);
txtFar = (EditText)findViewById(R.id.txtFar);
txtCel = (EditText)findViewById(R.id.txtCel);
btnFar.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
value = Integer.parseInt(txtFar.getText().toString());
new soapFahrenheit().execute();
}
});
btnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
txtCel.setText("");
txtFar.setText("");
}
});
}
private class soapFahrenheit extends AsyncTask<String, Integer, String> {
protected void onPreExecute()
{
//
txtCel.setText(value);
}
#Override
protected String doInBackground(String... arg0){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//Use this to add parameters
request.addProperty("Fahrenheit",value);
//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);
androidHttpTransport.call(SOAP_ACTION1, envelope);
result = (SoapObject)envelope.bodyIn;
} catch (Exception e) {
e.printStackTrace();
}
return result.getProperty(0).toString();
}
protected void onPostExecute(SoapObject result)
{
if(result != null)
{
txtFar.setText(result.getProperty(0).toString());
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
}
}
}
did i miss anything here? this is killing my days.... please help
You are making a network communication on the main UI thread which not allowed Android 4.0+.
So, you need to create a background thread to make the request to the server.
AsyncTask is what you should be using.
The problem with the ACTION String
http://www.w3schools.com/webservices/tempconvert.asmx?op=FahrenheitToCelsius
And xml form
POST /webservices/tempconvert.asmx HTTP/1.1
Host: www.w3schools.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://www.w3schools.com/webservices/FahrenheitToCelsius" // ACTION
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<FahrenheitToCelsius xmlns="http://www.w3schools.com/webservices/">
<Fahrenheit>string</Fahrenheit>
</FahrenheitToCelsius>
</soap:Body>
</soap:Envelope>
So the ACTION name should like
private static String SOAP_ACTION1 = "http://www.w3schools.com/webservices/FahrenheitToCelsius";
and
private static String SOAP_ACTION2 = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
Hope this will solve your problem.
And use dont't do network operation on UI Thread. Use AsynTask
EDIT:
private void doNetwork() {
SoapObject resultRequestSOAP = new SoapObject(NAMESPACE1, METHOD_NAME1);
PropertyInfo pi1 = new PropertyInfo();
pi1.setName("Fahrenheit");
pi1.setValue(""+value);// Say value= 10
pi1.setType(PropertyInfo.STRING_CLASS);
resultRequestSOAP.addProperty(pi1);
SoapSerializationEnvelope envp = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envp.dotNet = true;
try {
envp.setOutputSoapObject(resultRequestSOAP);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION1, envp);
SoapObject response = (SoapObject) envp.bodyIn;
System.out.println("response"+response.toString() + " "+response.getProperty(0).toString());
} catch (Exception e) {
}
}
OUTPUT:
FahrenheitToCelsiusResponse{FahrenheitToCelsiusResult=-12.2222222222222; }

Android web service return array in List view

Hi I created a webservice that pulls a list of location names from the database in a array. I need to get this array in a listview on android. I am lost as I am new to android. Please help. Here is the code I have so far. Also I am using a fragment and webservice using soap. Thanks in advance.
public class LocationFragment extends Fragment {
/** Called when the activity is first created. */
TextView tv;
public LocationFragment(){}
private String TAG ="Vik";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_location, container, false);
tv =(TextView)rootView.findViewById(R.id.textView1);
AsyncCallWS task = new AsyncCallWS();
task.execute();
return rootView;
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
location();
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
public void location()
{
String SOAP_ACTION = "http://example.com/locations";
String METHOD_NAME = "locations";
String NAMESPACE = "http://example.com/";
String URL = "http://100.100.00.80/example/Service.asmx";
try {
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
Request.addProperty("getlocation", "null");
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport= new HttpTransportSE(URL);
transport.call(SOAP_ACTION, soapEnvelope);
SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
tv.setText("Status : " + resultString);
Log.i(TAG, "Result locations: " + resultString);
}
catch(Exception ex) {
Log.e(TAG, "Error: " + ex.getMessage());
}
}
}
Check this code for getting response from web service as array
call your web service in doinbackground() method assign response to list. When interacting with UI do that in op postexecute() method.
class addassdist extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
private final String SOAP_ACTION = "http://tempuri.org/GetDistrict";
private final String METHOD_NAME = "GetDistrict";
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://192.160.1.1/district/service.asmx";
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading data");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
System.out.println("response"+response);
int intPropertyCount = response.getPropertyCount();
list= new String[intPropertyCount];
for (int i = 0; i < intPropertyCount; i++)
{
list[i] = response.getPropertyAsString(i).toString();
}
}
catch (Exception e) {
exc=true;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if(exc)
{
Toast.makeText(MainActivity.this,"Error" , Toast.LENGTH_LONG).show();
}
else{
spinner();
exc=false;
}
}
}
public void spinner(){
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
// your code
}
});
}

Android, Read timed auto and soap

Ksoap2 trying to connect to the web service. However, the "read timed out" error getting. I do not know what to do.
Ksoap2 'There is an error too? where is the error
Ksoaps libs version: 3.0.1
Emulator 2.2
MainActivity.java
public class MainActivity extends Activity {
static final String METHOD_NAME = "GetTableUpdateVersionByTableName";
static final String NAMESPACE = "http://tempuri.org/";
static final String URL = "https://app.xxx.com/IntSecureFlight/SFInternal.svc";
static final String DOMAIN = "app.xxx.com";
static final String SOAP_ACTION = "http://tempuri.org/IOperationSvc/GetTableUpdateVersionByTableName";
TextView sonuc;
EditText tableName;
String message;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sonuc = (TextView) findViewById(R.id.textView1);
tableName = (EditText) findViewById(R.id.editText1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), tableName.getText(),
Toast.LENGTH_LONG).show();
new AsyncTaskClass().execute();
}
});
}
class AsyncTaskClass extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
// uzun islem oncesi yapilacaklar
}
#Override
protected String doInBackground(String... strings) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("tableName", tableName.getText().toString());
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER12);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(request);
soapEnvelope.headerOut = new Element[1];
soapEnvelope.headerOut[0] = buildAuthHeader();
try {
HttpsTransportSE transportSE = new HttpsTransportSE(DOMAIN,
443, "/IntSecureFlight/SFInternal.svc", 2000);
transportSE.call(SOAP_ACTION, soapEnvelope);
Object result = soapEnvelope.getResponse();
if (result instanceof SoapFault12) {
SoapFault12 soapResult = (SoapFault12) result;
message = soapResult.getLocalizedMessage();
} else if (result instanceof SoapObject) {
SoapObject soapResult = (SoapObject) result;
message = soapResult.getProperty(0).toString();
}
} catch (SoapFault12 e) {
message = e.getMessage();
} catch (XmlPullParserException e) {
message = e.getMessage();
} catch (Exception e) {
message = e.getMessage();
}
return message;
}
#Override
protected void onPostExecute(String result) {
sonuc.setText(message);
super.onPostExecute(result);
}
}
public Element buildAuthHeader() {
Element h = new Element().createElement(NAMESPACE, "UsernameToken");
Element username = new Element().createElement(NAMESPACE, "Username");
username.addChild(Node.TEXT, "genel");
h.addChild(Node.ELEMENT, username);
Element pass = new Element().createElement(NAMESPACE, "KurumKod");
pass.addChild(Node.TEXT, "050");
h.addChild(Node.ELEMENT, pass);
return h;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
HttpTransportSEImpl
public class HttpTransportSEImpl extends HttpTransportSE {
public HttpTransportSEImpl(String url) {
super(url);
}
#Override
public ServiceConnection getServiceConnection() throws IOException {
ServiceConnection connection = super.getServiceConnection();
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
return connection;
}
}
AndroidManifest add <uses-permission android:name="android.permission.INTERNET"/>
read timed out error and socket time out errors will come on low internet connections
check your internet connection strength
or check the server response string, you may mismatch the data-type on reading.
and add permissions to listen network_state and
access_fine_location
edit your code:
HttpsTransportSE transportSE = new HttpsTransportSE(DOMAIN,
443, "/IntSecureFlight/SFInternal.svc", 60000);

TextView Not Displayed in Inner Class

I have a main class extend with activity and inside it a inner class is define which is extends with asynctask but in inner class i used TextView.setText("Hi) but it is not displayed.AnyOne can suggest me?
public class MainActivity extends Activity
{
TextView tv;
String s;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mytask m=new mytask(s);
//Log.d("String1",s);
//tv.setText("Hi");
m.execute();
}
public class mytask extends AsyncTask<String, Void, String>
{
private static final String SOAP_ACTION = "http://tempuri.org/HelloWorld";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String METHOD_NAME = "HelloWorld";
private static final String URL = "http://10.0.2.2:1070/HelloWorld/WebService.asmx?wsdl";
String k;
public mytask(String s)
{
k=s;
}
// #SuppressWarnings("unused")
protected String doInBackground(String... params)
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
tv=(TextView)findViewById(R.id.text_view);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
Log.d("Envelope", envelope.toString());
try
{
Log.d("res", "entered");
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part thnteredat will call the webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
//responce=
Log.d("res1", result.toString());
if(result != null)
{
s=result.getPropertyAsString(0).toString();
Log.d("string", s);
tv.setText("Hi");
//Get the first property and change the label text
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
}
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Move your initialization onCreate
tv=(TextView)findViewById(R.id.text_view);
You cannot update ui from doInBackground(). Move the below to onPostExecute(param).
tv.setText("Hi");
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
http://developer.android.com/reference/android/os/AsyncTask.html
Check the link and the topic under the section The 4 steps.
You can return the result in doInBackground(). The result of doInBackground() computation is a parameter to onPostExecute(param). So return result in doInBackground() and update ui in onPostExecute().
In doInBackgrounnd() return result and change the return type to SoapObject. Declare result as a class variable.
Then
#Override
protected void onPostExecute(SoapObject result)
{
super.onPostExecute(result);
if(result!=null)
{
tv.setText("Sucess...");
Toast.makeText(getApplicationContext(), "Sucess",Toast.LENGTH_LONG).show();
}
}
You can also use runOnUiThread. But i would suggest you update ui in onPostExecute.
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
}
});
put
tv.setText("Hi");
just below
tv=(TextView)findViewById(R.id.text_view); and write this code in onCreate method

Android, AsyncTask with kSoap2

I'm coding an app that primarily uses data gotten from a web service, and I want to use AsyncTask to run the SOAP calls in the background... I'm fairly new to Android(being an iOS programmer), so I'm a bit new at this...
Now, I have a login screen, where I take a user-provided login and check it against information on a server...
So in my login activity:
loginBtn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//Run the connection to authenticate the user
AuthenticateConnection mAuth = new AuthenticateConnection();
mAuth.mNumber = number;
mAuth.mPassword = pass;
mAuth.connection();
}
}
and my soap class is this:
public class AuthenticateConnection
{
private static final String SOAP_ACTION = "http://tempuri.org/Authenticate";
private static final String METHOD_NAME = "Authenticate";
private static final String NAMESPACE = "http://tempuri.org/";
private String URL;
public Boolean userOK;
public String mNumber;
public String mPassword;
public AuthenticateConnection()
{
}
public void connection()
{
Singleton service = Singleton.getInstance();
String firstURL = service.getURL();
URL = firstURL + "Parent.svc";
System.out.println("Connection to: " + URL);
//Initialize soap request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Add parameters
request.addProperty("login", mNumber);
request.addProperty("password", mPassword);
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.implicitTypes=true;
envelope.setAddAdornments(false);
//Prepare request
envelope.setOutputSoapObject(request);
//Needed to make the internet call
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//Allow for debugging - needed to output the request
androidHttpTransport.debug = true;
try
{
//this is the actual part that will call the web service
androidHttpTransport.call(SOAP_ACTION, envelope);
//Get the SoapResult from the envelope body.
//Object result = envelope.getResponse();
//Object result = envelope.bodyIn;
SoapObject sResult = (SoapObject)envelope.bodyIn;
String tempID = sResult.getProperty("AuthenticateResult").toString();
//Check if the user exists and has the correct password
if(tempID != "-1")
{
userOK = true;
//Store the values in the singleton class
service.parentID = sResult.getProperty("AuthenticateResult").toString();
service.parentToken = sResult.getProperty("token").toString();
}
//If -1 is returned, then either the number or the password is incorrect
else
{
userOK = false;
}
} catch(org.xmlpull.v1.XmlPullParserException ex2)
{
//System.out.println(androidHttpTransport.requestDump.toString());
} catch (Exception e)
{
e.printStackTrace();
System.out.println(androidHttpTransport.requestDump.toString());
}
}
}
So my question is, how would I do this with AsyncTask?
I've been looking at some tutorial on AsyncTask, but haven't really "gotten it" so far...
You can do:
private class ConnectionTask extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(ACTIVITY_NAME.this);
protected void onPreExecute() {
dialog.setMessage("Connecting...");
dialog.show();
}
protected void doInBackground(String... args) {
AuthenticateConnection mAuth = new AuthenticateConnection();
mAuth.mNumber = args[0];
mAuth.mPassword = args[1];
mAuth.connection();
}
protected void onPostExecute(Void v) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
And then call it:
loginBtn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//Run the connection to authenticate the user
new ConnectionTask().execute(number, pass);
}
}
Your connection method in AuthenticateConnection should return something to ensure the user has been authenticated. Then you can use that value in the onPostExecute, something like this:
protected void onPostExecute(Integer res) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (res.intValue() == OK) {
/* Maybe start a new Activity ...*/
} else {
/* Maybe show a Toast with an error message ...*/
}
}
In this case the signature of the asynctask will change:
private class ConnectionTask extends AsyncTask<String, Void, Integer>
and the doInBackground should return an Integer.
Hope it helps.

Categories

Resources