Android, Read timed auto and soap - android

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

Related

android - connect to web service

I'm try to connect android application to a web service uploaded on somee.
I have the following problem :
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NullPointerException
the web service code :
[WebService(Namespace = "http://www.n-m.somee.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
SqlConnection con = new SqlConnection(#"workstation id=WSDatabase.mssql.somee.com;packet size=4096;user id=***;pwd=***;data source=WSDatabase.mssql.somee.com;persist security info=False;initial catalog=WSDatabase ");
[WebMethod]
public string get_name(String pssw)
{
con.Open();
SqlCommand cmd = new SqlCommand("select username from users where pssw="+pssw, con);
string rd =(string) cmd.ExecuteScalar();
con.Close();
return rd;
}
}
I added the following line to manifest file:
** MainActivity.java file**
public class MainActivity extends AppCompatActivity {
protected String namespace="http://www.n-m.somee.com/";
protected String url="http://www.n-m.somee.com/WebService1.asmx";
protected String SOAPAction="http://www.n-m.somee.com/get_name";
protected String method_name= "get_name";
TextView user_name;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void goButton(View v)
{
user_name=(TextView)findViewById(R.id.textView1);
//allow internet
if(Build.VERSION.SDK_INT>9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//create soap object
SoapObject soapObject=new SoapObject(namespace,method_name);
soapObject.addProperty("pssw", "1234");
//create envelop
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(soapObject);
//Rrquest get data from webservice and set it into soapobject
HttpTransportSE transport = new HttpTransportSE(url);
try {
transport.call(SOAPAction, envelope);
// get data
SoapPrimitive output=(SoapPrimitive) envelope.getResponse();
//set data into control
user_name.setText("pssw: "+output.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
I appreciate any help
thank you
Your urls were a bit wrong. This is what I used,
protected String namespace = "http://www.nourhan-m.somee.com/";
protected String url = "http://www.nourhan-m.somee.com/WebService1.asmx";
protected String SOAPAction = "http://www.nourhan-m.somee.com/get_name";
protected String method_name = "get_name";
I made some modification to your code to make it work.
public String callService(String username) {
//create soap object and add params to it
SoapObject request = new SoapObject(namespace, method_name);
request.addProperty("pssw", username);
//create envelop
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
//set request to envelope
envelope.bodyOut = request;
HttpTransportSE transport = new HttpTransportSE(url);
transport.debug = true;
try {
transport.call(SOAPAction, envelope);
Log.e("OUT", transport.requestDump);
return transport.responseDump;
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return "";
}
This is how I invoked the method,
You can invoke it as follows,
final String username = (TextView) findViewById(R.id.textView1)
new Thread(new Runnable() {
#Override
public void run() {
Log.e("OUT", callService(username));
}
}).start();
I got an empty response, maybe it's because I didn't give a valid username. Have a look at it. Cheers :)

How to get data from SOAP response in 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.

how to call a web service in android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i need to call a web service from the url. wen i entered the no in the text box i should the output which i entered in text box. pls help me fixing the errors. here is my java code.
MainActivity.java
public class MainActivity extends Activity {
Button b;
TextView tv;
EditText et;
String editText;
String displayText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.tv_result);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (et.getText().length() != 0 && et.getText().toString() != "") {
editText = et.getText().toString();
AsyncCallWS task = new AsyncCallWS();
task.execute();
} else {
tv.setText("Please enter number");
}
}
});
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
displayText = ser.invokeiop(editText,"hello");
return null;
}
}
}
ser.java
public class ser {
private static String NAMESPACE = "http://tempuri.org/";
private static String URL = "http://my url";
private static String SOAP_ACTION = "srvice";
public static String invokeiop(String name, String webMethName) {
String resTxt = null;
SoapObject request = new SoapObject(NAMESPACE, webMethName);
PropertyInfo iop = new PropertyInfo();
iop.setName("name");
iop.setValue(name);
//iop.setType(String.class);
request.addProperty(iop);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION+webMethName, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
resTxt = response.toString();
} catch (Exception e) {
e.printStackTrace();
resTxt = "Error occured";
}
This might help you!!
public class MainActivity extends Activity {
Button b;
EditText et;
String editText;
String displayText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (et.getText().length() != 0 && et.getText().toString() != "") {
editText = et.getText().toString();
AsyncCallWS();
} else {
// declare a toast
}
}
});
}
public void AsyncCallWS(final String q)
{
class HttpGetAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
String txtSearch = params[0];
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("URL"+editText);
try
{
HttpResponse httpResponse = httpClient.execute(httpGet);
inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder strB = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null)
{
strB.append(bufferedStrChunk);
}
return strB.toString();
}
catch (ClientProtocolException cpe)
{
cpe.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try {
// Parse your data here
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
}
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
httpGetAsyncTask.execute(editText);
}

Error to connect with a web service in android.. HTTP reqest failed,HTTP status 400

I have this code to call a donNet web servise on localhost. The web service take 5 values and return a string.. I took this error: Error HTTP request failed, HTTP status 400.. What is the problem here?
public class MainActivity extends Activity {
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://10.0.2.2:6371/Service1.asmx";
int IDocID;
String SName,SDate,STime,SReason;
TextView txt;
private PropertyInfo AppDoctor,AppDate,AppTime,AppName,AppReason;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sent=(Button)findViewById(R.id.button1);
txt=(TextView)findViewById(R.id.textView6);
sent.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
EditText DocID=(EditText)findViewById(R.id.editTextDoc);
IDocID = Integer.parseInt(DocID.getText().toString());
EditText Date= (EditText)findViewById(R.id.editTextDate);
SDate = Date.getText().toString();
EditText Time=(EditText)findViewById(R.id.editTextTime);
STime = Time.getText().toString();
EditText Name=(EditText)findViewById(R.id.editTextName);
SName = Name.getText().toString();
EditText Reason=(EditText)findViewById(R.id.editTextReason);
SReason = Reason.getText().toString();
new InsertTask().execute();
}
});
}
private String doInsert(String SName,String SDate,String STime,String SReason, int IDocID ) {
String result="";
final String SOAP_ACTION = "http://tempuri.org/InsertAppointment";
final String METHOD_NAME = "InsertAppointment";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("AppDoctor",IDocID);
request.addProperty("AppDate",SDate);
request.addProperty("AppTime",STime);
request.addProperty("AppName",SName);
request.addProperty("AppReason",SReason);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
System.out.println(request);
System.out.println(envelope.toString());
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.i("myApp", response.toString());
/
if(response != null)
{
String resp= response.toString();
result = resp;
txt.setText(resp);
}
}catch(SocketException ex)
{
Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
ex.printStackTrace();
txt.setText(ex.toString());
}
catch (Exception e) {
Log.e("Error : " , "Error on soapPrimitiveData() " + e.getMessage());
e.printStackTrace();
}
return result;
}
private class InsertTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
this.dialog.setMessage("Logging in...");
this.dialog.show();
}
protected Void doInBackground(final Void... unused) {
String auth=doInsert( SName, SDate, STime, SReason, IDocID);
System.out.println(auth);
return null;// don't interact with the ui!
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
Try to add "" to your SOAP_ACTION:
final String SOAP_ACTION = "\"http://tempuri.org/InsertAppointment\"";

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