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
Related
I am new to android. This question is a phase from my steps in experimenting with android apps and web service. I have asked a question before, which is in here: Fail to connect android to web service.
Below is my Updated code,
my code in MainActivity:
public class MainActivity extends AppCompatActivity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
Mytask mt = new Mytask();
mt.execute();
}
}
my code in Mytask:
public class Mytask extends AsyncTask<String, Integer, String> {
private static final String SOAP_ACTION = "http://services.aonaware.com/webservices/Define";
private static final String URL = "http://services.aonaware.com/DictService/DictService.asmx";
private static final String METHOD_NAME = "Define";
private static final String NAMESPACE = "http://services.aonaware.com/webservices/";
String resultData=null;
#Override
protected String doInBackground(String... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo property = new PropertyInfo();
property.setName("word");
property.setType(String.class);
property.setValue("computer");
request.addProperty(property);
Log.i("soap tobe", "----");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
Object response = null;
try {
androidHttpTransport.getServiceConnection();
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
Log.i("soap passed", "----"+response);
response = envelope.getResponse();
resultData= response.toString();
} catch (Exception e) {
e.printStackTrace();
}
Log.i("result passed", "----"+response.toString());
return resultData;
}
protected void onPostExecute(String result) {
Log.i("onPost passed", "----"+result);
}
}
I got the result right in the "onPost passed" log. From here, how can I put the result into TextView in MainActivity?
You need to use interface
1.) Create interface class in your asyncTask class.
public interface AsyncResponse {
void processFinish(String output);
}
2.) And declare interface AsyncResponse as a field in asyncTask class:
public class MyAsyncTask extends AsyncTask{
public AsyncResponse delegate = null;
#Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
}
3.) In your main Activity you need to implements interface AsyncResponse.
public class MainActivity implements AsyncResponse{
MyAsyncTask asyncTask =new MyAsyncTask();
#Override
public void onCreate(Bundle savedInstanceState) {
//this to set delegate/listener back to this class
asyncTask.delegate = (MyAsyncTask)this;
//execute the async task
asyncTask.execute();
}
//this override the implemented method from asyncTask
void processFinish(String output){
//Here you will receive the result fired from async class
//of onPostExecute(result) method.
}
}
Edit
public class Mytask extends AsyncTask<String, Integer, String> {
private static final String SOAP_ACTION = "http://services.aonaware.com/webservices/Define";
private static final String URL = "http://services.aonaware.com/DictService/DictService.asmx";
private static final String METHOD_NAME = "Define";
private static final String NAMESPACE = "http://services.aonaware.com/webservices/";
String resultData=null;
public AsyncResponse delegate = null;
#Override
protected String doInBackground(String... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo property = new PropertyInfo();
property.setName("word");
property.setType(String.class);
property.setValue("computer");
request.addProperty(property);
Log.i("soap tobe", "----");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
Object response = null;
try {
androidHttpTransport.getServiceConnection();
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
Log.i("soap passed", "----"+response);
response = envelope.getResponse();
resultData= response.toString();
} catch (Exception e) {
e.printStackTrace();
}
Log.i("result passed", "----"+response.toString());
return resultData;
}
protected void onPostExecute(String result) {
Log.i("onPost passed", "----"+result);
delegate.processFinish(result);
}
public interface AsyncResponse {
void processFinish(String output);
}
}
And activity code
public class MainActivity extends AppCompatActivity implements AsyncResponse{
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
Mytask mt = new Mytask();
mt.delegate = this;
mt.execute();
}
void processFinish(String output){
tv.setText(output);
}
}
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.
What i have is an asynctask that i use it to send data to web service which work just fine , and here is my web service code :
public class WebServiceDetails {
//Namespace of the Webservice - can be found in WSDL
private static String NAMESPACE = "http://tempuri.org/";
//Webservice URL - WSDL File location
//URL = "http://80.90.161.246:70/erP_Reporting/OrderAndroid.asmx";
private static String URL = "http://192.168.1.124/alibabanewwebservice/AliBabaWebService.asmx";//Make sure you changed IP address
//private static String URL = "http://192.168.1.103/webservicejal6ah/OrderAndroid.asmx";//Make sure you changed IP address
//SOAP Action URI again Namespace + Web method name
private static String SOAP_ACTION = "http://tempuri.org/InsertOrderDetails";
public static boolean invokeLoginWS(String DeviceId, String Item_id, String Item_Quantity,String Bounce,String webMethName)
{
boolean loginStatus = false;
// Create request
SoapObject request = new SoapObject(NAMESPACE, webMethName);
// Property which holds input parameters
PropertyInfo deviceid = new PropertyInfo();
PropertyInfo itemid = new PropertyInfo();
PropertyInfo quantity = new PropertyInfo();
PropertyInfo bounce= new PropertyInfo();
deviceid.setName("DeviceId");
deviceid.setValue(DeviceId);
deviceid.setType(String.class);
request.addProperty(deviceid);
itemid.setName("Item_id");
itemid.setValue(Item_id);
itemid.setType(String.class);
request.addProperty(itemid);
quantity.setName("Item_Quantity");
quantity.setValue(Item_Quantity);
quantity.setType(String.class);
request.addProperty(quantity);
bounce.setName("Bounce");
bounce.setValue(Bounce);
bounce.setType(String.class);
request.addProperty(bounce);
// extra.setName("Extra");
// extra.setValue(Extra);
// extra.setType(String.class);
// request.addProperty(extra);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(1);
envelope.dotNet = true;
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
// Invoke web service
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the response
// SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
Object response = (Object) envelope.getResponse();
// Assign it to boolean variable variable
loginStatus = Boolean.parseBoolean(response.toString());
} catch (Exception e) {
//Assign Error Status true in static variable 'errored'
e.printStackTrace();
}
//Return booleam to calling object
return loginStatus;
}
}
And here is my asynctask :
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.e("Customer_Name","sereen");
//Make Progress Bar invisible
//AddToCart.cartlist.clear();
try{
//Log.e(" Customer_Id=masterrs.get(m).getCustomerId()", rs.get(m).getCustomerId());
Toast.makeText(CartList.this, "order has been send ", Toast.LENGTH_LONG).show();
}
catch(Exception e){
e.printStackTrace();
}
}
//Make Progress Bar visible
protected void onPreExecute() {
super.onPreExecute();
pd.setTitle("sending");
pd.setMessage("waiting...");
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
loginStatus2 = WebServiceDetails.invokeLoginWS(Device_ID,Item_Id,Quantity,Bounce,"InsertOrderDetails");
Log.e("Device_ID details",Device_ID+"");
// try{
//Log.e(" Customer_Id=masterrs.get(m).getCustomerId()", rs.get(m).getCustomerId());
// }
// catch(Exception e){
// e.printStackTrace();
// }
//
// }
}
return null;
}
}
well , the problem is as you can see my asynctask return null value and i want it after i send value to return true for (loginStatus2) but the thing is when i tried to do it , it didn't work .. can anyone help me , what shall i change to get the value true when success post on web service and false when it fails?
Try this code for AsyncTask. Use result and check if it is null or not.
If null, there is no response else you can have response in form of result from Asynctask() method.
private class AsyncCallWS extends AsyncTask<Void, Void, String> {
String response;
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result==null){
Toast.makeText(CartList.this, "result is null", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(CartList.this, "Result is: "+ result, Toast.LENGTH_LONG).show();
}
try{ //Your code here
//Log.e(" Customer_Id=masterrs.get(m).getCustomerId()", rs.get(m).getCustomerId());
Toast.makeText(CartList.this, "order has been send ", Toast.LENGTH_LONG).show();
}
catch(Exception e){
e.printStackTrace();
}
}
//Make Progress Bar visible
protected void onPreExecute() {
super.onPreExecute();
pd.setTitle("sending");
pd.setMessage("waiting...");
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
loginStatus2 = WebServiceDetails.invokeLoginWS(Device_ID,Item_Id,Quantity,Bounce,"InsertOrderDetails");
response = loginStatus2;
Log.e("Device_ID details",Device_ID+"");
}
return response;
}
}
Tried using Async but got can't handler even there is no toast in it,
also tried call calling method runUIThread but no luck ,
Async method works but it also gets run time exception
when i use Async method data gets on the Textview too late (5-10 mins) , but when i use it in debuggers it gets instantly ,
below webservice is test using wizdl application and response is instant
i'm confused please help
private final String NAMESPACE = "http://????????.com/EventGetter/";
private final String URL = "http://?????????.com/EventGetter.asmx";
private final String SOAP_ACTION = "http://????????.com/EventGetter/GetTimeTable";
private final String METHOD_NAME = "GetTimeTable";
private class TPaccessData extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
GetData();
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(LogStr, "onPostExecute");
}
#Override
protected void onPreExecute() {
GetData();
Log.i(LogStr, "onPreExecute");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(LogStr, "onProgressUpdate");
}
}
public void GetData(){
//Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//set properties aka param
request.addProperty("stream","where ttBatch = 'F.Y.J.C'");
//Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
//Set output SOAP object
envelope.setOutputSoapObject(request);
//Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.debug = true;
//Invole web service
androidHttpTransport.call(SOAP_ACTION, envelope);
//Get the response
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
//Assign it to Text static variable
text.setText(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
also tried calling get data in oncreate method
NotifyList.this.runOnUiThread(new Runnable() {
#Override
public void run() {
GetData();
// TPaccessData task = new TPaccessData();
// task.execute();
}
});
Remove youe GetData() method from onPreExecute()
and call this line inside onPost
text.setText(response.toString());
I have the following problem. After I got the android.os.NetworkOnMainThreadException I went looking for a solution, and as it seems, AsyncTask is the best way to handle this.
But after I read several pages I still don't know how to implement AsyncTask.
First I will tell you what i know so far together with my questions:
Here I would try to call the webservice.
package net.frontend.androidapp.statusrequest;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class PurchaseRequisitionRequest extends Activity {
private String METHOD_NAME = "parser" ;
private String NAMESPACE = "http://statusrequest.androidapp.webservice.backend.net";
private String SOAP_ACTION = NAMESPACE + METHOD_NAME;
private static final String URL = "http://10.35.105.31:8080/SAPInterfaceWebservice/services/XMLTransfromer?wsdl";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.purchase_requisition_request_activity);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.purchase_requisition_request, menu);
return true;
}
public void checkStatus (View view) {
try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
EditText edit = (EditText) findViewById (R.id.prRequest);
String s= edit.getText().toString();
long lineNr=Long.parseLong(s);
request.addProperty("lineNr", lineNr);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION,envelope);
Object result = envelope.getResponse();
String hString = result.toString();
String[] details = hString.split(",");
((TextView) findViewById (R.id.request_detail1)).setText("PR_Number: " +details[0].substring(1));
((TextView) findViewById (R.id.request_detail2)).setText("Result1: " +details[1]);
((TextView) findViewById (R.id.request_detail3)).setText("Result2: " +details[2]);
((TextView) findViewById (R.id.request_detail4)).setText("Result3: " +details[3]);
((TextView) findViewById (R.id.request_detail5)).setText("Entered Number: " + lineNr);
} catch (Exception E) {
E.printStackTrace();
((TextView) findViewById (R.id.request_detail1)).setText("ERROR: " + E.getClass().getName() + " : " + E.getMessage());
}
}
}
As far as I understand, the only thing I have to put here is
new MyClassName().execute(a, b, c);
right in my CheckStatus method. (This method is called, when a button is pressed)
So where does this line go?
private class MyClassName extends AsyncTask
I would now create a new class, give it a nice name and then put this line next
protected Long doInBackground(Params... params)
and then the code part of my CheckStatus .
Is this right so far?
The next thing is that I don't know, which parameters so you have to give the execute(a,b,c) call?
Can someone please give me some code example, using my code? I would really appreciate.
I am sorry for asking so basic questions, but I don't understand how it works.
Thank you a lot for your help!
public class PurchaseRequisitionRequest extends Activity {
private String METHOD_NAME = "parser" ;
private String NAMESPACE = "http://statusrequest.androidapp.webservice.backend.net";
private String SOAP_ACTION = NAMESPACE + METHOD_NAME;
private static final String URL = "http://10.35.105.31:8080/SAPInterfaceWebservice/services/XMLTransfromer?wsdl";
String Error_Msg = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.purchase_requisition_request_activity);
new asyncTask().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.purchase_requisition_request, menu);
return true;
}
private class asyncTask extends AsyncTask<Void, Void, Boolean>
{
ProgressDialog pd;
protected void onPreExecute()
{
pd.setTitle("Please Wait...");
pd.setMessage("Saving...");
pd.setCancelable(false);
pd.show();
}
protected void onPostExecute(Boolean result)
{
if(result)
{
((TextView) findViewById (R.id.request_detail1)).setText("PR_Number: " +details[0].substring(1));
((TextView) findViewById (R.id.request_detail2)).setText("Result1: " +details[1]);
((TextView) findViewById (R.id.request_detail3)).setText("Result2: " +details[2]);
((TextView) findViewById (R.id.request_detail4)).setText("Result3: " +details[3]);
((TextView) findViewById (R.id.request_detail5)).setText("Entered Number: " + lineNr);
}
else
{
((TextView) findViewById (R.id.request_detail1)).setText(Error_Msg);
}
if(pd.isShowing()) pd.dismiss();
}
#Override
protected Boolean doInBackground(Void... params)
{
try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
EditText edit = (EditText) findViewById (R.id.prRequest);
String s= edit.getText().toString();
long lineNr=Long.parseLong(s);
request.addProperty("lineNr", lineNr);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION,envelope);
Object result = envelope.getResponse();
String hString = result.toString();
String[] details = hString.split(",");
Error_Msg = hString;
} catch (Exception E)
{
E.printStackTrace();
Error_Msg = "ERROR: " + E.getClass().getName() + " : " + E.getMessage();
}
return true;
}
else
{
return false;
}
}
}
}
First, take a look here and then this example here.
The so called "slow" code goen in the doInBackground() part of the newly created class.
Why not use Google Volley (introduced in this year's I/O).
It has a simple interface for networking and remote image loading.
Check it out here.
http://developer.android.com/reference/android/os/AsyncTask.html
An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
AsyncTask's generic types :
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
Create a Class and use this
public class RequestClient extends AsyncTask<String, Void, String>{
Context context;
CallBack callBack;
public RequestClient(CallBack callBack) {
this.callBack = callBack;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String responseString="";
HttpClient client = null;
try {
client = new DefaultHttpClient();
HttpGet get = new HttpGet(LoginPage.url);
client.getParams().setParameter("http.socket.timeout", 6000);
client.getParams().setParameter("http.connection.timeout", 6000);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString.trim());
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
client.getConnectionManager().shutdown();
return responseString.trim();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
callBack.run(result);
}
}
And the main class
public void postHttpRequest(final String userId,final String pass,final TextView error){
url = "";
Log.d("URL", url);
RequestClient reqClient = new RequestClient(new CallBack() {
#Override
public void run(Object result) {
try {
AppResponse =(String)result;
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}
});
reqClient.execute(url);
}
Create a interface Like this
public interface CallBack {
void run(Object result);
}