Showing ProgressDialog on AsyncThread Android - java

I want to show a ProgressDialog when a call to a Web Service call is made, this is my code:
public class penAPIController extends AsyncTask<Object, Void, Object>{
private View view;
private ProgressDialog dialog;
public penAPIController(View v)
{
view = v;
}
protected void onPreExecute()
{
this.dialog = new ProgressDialog(view.getContext());
this.dialog.setMessage("Loading, Please Wait..");
this.dialog.setCancelable(false);
this.dialog.show();
}
The dialog shows indeed but only after doInBackground is finished, I want to be able to show it while doInBackground is doing its job. And then hide it on PostExecute
onPostExecute:
#Override
protected void onPostExecute(Object obj)
{
//dialog.dismiss();
myMethod(obj);
}
private Object myMethod(Object myValue)
{
//handle value
return myValue;
}
doInBackground:
#Override
protected Object doInBackground(Object... objects)
{
if(objects.length < minNumberOfParams)
{
return null;
}
Object finalObject = null;
// TODO Auto-generated method stub
String NAMESPACE = "http://...";
String METHOD_LOGIN_NAME = "Login";
String SOAP_LOGIN_ACTION = "http://...";
String METHOD_RUNACTION_NAME = "RunAction";
String SOAP_RUNACTION_ACTION = "http://...";
String CLIENT = (String)objects[0];
String APPLICATION = (String)objects[1];
String USERNAME = (String)objects[2];
String PASSWORD = (String)objects[3];
String URL = (String)objects[4];
String ACTION_NAME = (String)objects[5];
ArrayList arrayParams = null;
if(objects.length == (minNumberOfParams + 1))
{
arrayParams = (ArrayList)objects[6];//Build parameters xml from ActionParam array
}
String PARAMETERS = buildParametersXML(arrayParams);
SoapObject Request = new SoapObject(NAMESPACE, METHOD_LOGIN_NAME);
//Client
PropertyInfo propertyClient = new PropertyInfo();
propertyClient.setName("client");
propertyClient.setValue(CLIENT);
propertyClient.setType(CLIENT.getClass());
Request.addProperty(propertyClient);
//Application
PropertyInfo propertyApplication = new PropertyInfo();
propertyApplication.setName("application");
propertyApplication.setValue(APPLICATION);
propertyApplication.setType(APPLICATION.getClass());
Request.addProperty(propertyApplication);
//Username
PropertyInfo propertyUsername = new PropertyInfo();
propertyUsername.setName("username");
propertyUsername.setValue(USERNAME);
propertyUsername.setType(USERNAME.getClass());
Request.addProperty(propertyUsername);
//Password
PropertyInfo propertyPassword = new PropertyInfo();
propertyPassword.setName("password");
propertyPassword.setValue(PASSWORD);
propertyPassword.setType(PASSWORD.getClass());
Request.addProperty(propertyPassword);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try
{
androidHttpTransport.call(SOAP_LOGIN_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
String token = response.toString();
SoapObject RequestRun = new SoapObject(NAMESPACE, METHOD_RUNACTION_NAME);
//Token
PropertyInfo propertyToken = new PropertyInfo();
propertyToken.setName("token");
propertyToken.setValue(token);
propertyToken.setType(token.getClass());
RequestRun.addProperty(propertyToken);
//Action Name
PropertyInfo propertyAction = new PropertyInfo();
propertyAction.setName("actionName");
propertyAction.setValue(ACTION_NAME);
propertyAction.setType(ACTION_NAME.getClass());
RequestRun.addProperty(propertyAction);
//Parameters
PropertyInfo propertyParams = new PropertyInfo();
propertyParams.setName("parameters");
propertyParams.setValue(PARAMETERS);
propertyParams.setType(PARAMETERS.getClass());
RequestRun.addProperty(propertyParams);
SoapSerializationEnvelope envelopeRun = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelopeRun.dotNet = true;
envelopeRun.setOutputSoapObject(RequestRun);
HttpTransportSE androidHttpTransportRun = new HttpTransportSE(URL);
androidHttpTransportRun.call(SOAP_RUNACTION_ACTION, envelopeRun);
SoapPrimitive responseRun = (SoapPrimitive)envelopeRun.getResponse();
String result = responseRun.toString();
finalObject = parseOutputXML(result);
}
catch(Exception e)
{
e.printStackTrace();
}
return finalObject;
}

Based on the comments, you are calling get() on the AsyncTask. This will block the submitting thread (main UI thread in your case) until the async task result is available, that is, doInBackground() returns.
Remove the call to get() and handle the completion e.g. in onPostExecute() or using a callback function.

private ProgressDialog progressDialog; // class variable
private void showProgressDialog(String title, String message)
{
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(""); //title
progressDialog.setMessage(""); // message
progressDialog.setCancelable(false);
progressDialog.show();
}
onPreExecute()
protected void onPreExecute()
{
showProgressDialog("Please wait...", "Your message");
}
Check and dismiss onPostExecute() -
protected void onPostExecute()
{
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
}

Related

org.ksoap2.serialization.SoapObject cannot be cast to org.ksoap2.serialization.SoapPrimitive

I'm trying to display a Listview by getting date from SOAP Web Service but every time i get an exception :
org.ksoap2.serialization.SoapObject cannot be cast to org.ksoap2.serialization.SoapPrimitive
code :-
public class ClientsReclamations extends Activity {
public final String NAMESPACE = "http://tempuri.org/";
public final String SOAP_ACTION = "http://tempuri.org/GetReclamations";
public final String METHOD_NAME = "GetReclamations";
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clients_reclamations);
lv=(ListView)findViewById(R.id.listViewRec);
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
public class AsyncCallWS extends AsyncTask<String, String,ArrayList>{
ArrayList<Reclamation> resultats=new ArrayList<Reclamation>();
protected void onPostExecute(ArrayList<Reclamation> resultats) {
lv.setAdapter(new CustomListAdapterRec(getApplicationContext(), resultats));
super.onPostExecute(resultats);
}
protected ArrayList doInBackground(String... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(getURL());
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
final SoapObject response = (SoapObject)envelope.getResponse();
Log.i("Liste Rec:----", response.toString());
runOnUiThread(new Runnable() {
#Override
public void run() {
Reclamation reclamation;
SoapObject GetReclamationsResponse=new SoapObject();
SoapObject GetReclamationsResult=new SoapObject();
SoapObject Reclamations=new SoapObject();
SoapObject REC=new SoapObject();
GetReclamationsResponse=(SoapObject) response.getProperty(0);
GetReclamationsResult=(SoapObject) GetReclamationsResponse.getProperty(0);
Reclamations=(SoapObject) GetReclamationsResult.getProperty(0);
for(int i=0;i<Reclamations.getPropertyCount();i++){
REC=(SoapObject) Reclamations.getProperty("Reclamation");
SoapObject DateRec=new SoapObject();
SoapObject Objet=new SoapObject();
SoapObject Details=new SoapObject();
SoapObject Traitee=new SoapObject();
DateRec=(SoapObject) REC.getProperty("DateRec");
Objet=(SoapObject) REC.getProperty("Objet");
Details=(SoapObject) REC.getProperty("Details");
Traitee=(SoapObject) REC.getProperty("Traitee");
reclamation = new Reclamation();
reclamation.setDET_REC(Details.toString());
reclamation.setOBJET_REC(Objet.toString());
reclamation.setDate(DateRec.toString());
reclamation.setIcon(getResources().getDrawable(R.id.btn_yearly));
resultats.add(reclamation);
Log.i("Resultat Size : ------",resultats.size()+"");
}
}
});
}
catch(Exception e){
e.printStackTrace();
}
return resultats;
}
}
public void AfficheToast(){
Toast t=Toast.makeText(this, "Aucune reclamation trouvée.", Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
public String getURL()
{
String URL=null;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
URL=sp.getString("serveur", "");
return URL;
}
}
Change this:
final SoapObject response = (SoapObject)envelope.getResponse();
to
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();

Call WebService Asp.Net sending a parameter JSON

I'm trying to send a json String but when I call the WebService he send a null parameter instead of my string.
When I go to Debug I can see on the soapObject Propertis my json. but in my webService i've put and when I call from my andoid app he always return null
if (json.Equals(null)) {
return "null";
}
try {
return json;
root = JObject.Parse(json);
} catch (Exception e) {
return e.StackTrace;
}
return "parseok";
Here is the code that I'm using.
public class OpcoesActivity extends Activity implements OnClickListener {
private String cpf;
private String senha;
private PontosUsuarioDAO pdao = new PontosUsuarioDAO(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.opcoeslayout);
cpf = getIntent().getStringExtra("cpf");
senha = getIntent().getStringExtra("senha");
Button importar = (Button) findViewById(R.id.bt_importar);
importar.setOnClickListener(this);
Button exportar = (Button) findViewById(R.id.bt_exportar);
exportar.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_importar:
Intent i = new Intent(this, SincronizarActivity.class);
i.putExtra("cpf", cpf);
i.putExtra("senha", senha);
startActivity(i);
break;
case R.id.bt_exportar:
new Thread(new Runnable() {
public void run() {
Gson gson = new Gson();
final String json = gson.toJson(pdao.exportaPontosUsuario(cpf));
ExportarDados exp = new ExportarDados("{\"teste\":\"java\"}");
String b = exp.ExportaDadosUser();
}
}).start();
break;
}
}
}
And here is the class to Export
public class ExportarDados {
private static final String SOAP_ACTION = "http://serv.lageo.ufpr.br/EnviaPontosUsuario";
private static final String METHOD_NAME = "EnviaPontosUsuario";
private static final String NAMESPACE = "http://serv.lageo.ufpr.br/";
private static final String URL = "http://200.17.203.150/Caderneta/Sincronizar.asmx";
private String json;
private SoapObject soapObject;
private String result = "";
public ExportarDados(String json) {
this.json = json;
}
public String ExportaDadosUser() {
String e2;
try {
soapObject = new SoapObject(NAMESPACE, METHOD_NAME);
soapObject.addProperty("json", json);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(soapObject);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION, soapEnvelope);
SoapPrimitive resultString = (SoapPrimitive) soapEnvelope.getResponse();
result = resultString.toString();
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
}
It was the NAMESPACE. It was not suposed to have an / in the end. so the Namespace is http://serv.lageo.ufpr.br instead of http://serv.lageo.ufpr.br/...

Serialization DataTable (WCF) to Android project

I connected Android java with WCF Service. Now I am trying to get data from WCF Service into my project.
I have problem with DataTable type from C# which I have to parse into my Class called Groups
Now I have error with serialization:
java.lang.ClassCastException: org.ksoap2.serialization.SoapObject
cannot be cast to org.ksoap2.serialization.SoapPrimitive
WebService (WCF)
var sp = new StoreProcEgzequtor("[dbo].GetAddonsTypes");
string a = sp.SqlCommand.Connection.Database;
DataTable dt = sp.ExecuteDataTable("Tabela");
return dt;
Class Groups
public class Groups {
private long id;
private long ID2;
private int flgW;
private int flgO;
private String Name;
Activity
public class AndroidWSClientActivity extends Activity {
private static final String METHOD_NAME = "GetAddonsTypes";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:53432/Service1.svc?wsdl";
final String SOAP_ACTION = "http://tempuri.org/IService1/GetAddonsTypes";
TextView textView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wsclient_page);
textView = (TextView) findViewById(R.id.textView2);
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();
final String str = response.toString();
runOnUiThread (new Runnable(){
public void run() {
Log.e("OK",str.toString());
}
});
}
catch (Exception e) {
Log.e("WS", e.toString());
}
}
};
networkThread.start();
}
}
Your error is with the below line. Its clear in the exception. Please check it
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
envelope.getResponse() returns the SoapObject and your are casting it to SoapPrimitive.

Using AsyncTask and returning values to the UI main thread

I have an Android activity to display the output of a web service. I've called the web service inside another private class which extends AsyncTask, and want to return a value to the main UI thread.
This is my activity.
public class CallCalcService extends Activity {
private String METHOD_NAME = "sum"; // our webservice method name
private String NAMESPACE = "http://backend.android.web.org";
private String SOAP_ACTION = NAMESPACE + METHOD_NAME;
private static final String URL = "http://192.168.1.14:8080/AndroidBackend1/services/Calculate?wsdl";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_calc_service);
//TextView tv = (TextView) findViewById(R.id.textView1);
//Object res=new HardWorkThread().execute();
//tv.setText("Addition : "+ res.toString());
new HardWorkThread()
{
public void onPostExecute(String result)
{
TextView txt = (TextView) findViewById(R.id.textView1);
txt.setText("Addition : "+result);
}
}.execute("");
}
private class HardWorkThread extends AsyncTask{
#Override
protected String doInBackground(Object... params) {
// TODO Auto-generated method stub
String result=null;
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("i", 5);
request.addProperty("j", 15);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION,envelope);
result = envelope.getResponse().toString();
System.out.println("Result : " + result);
//((TextView) findViewById(R.id.textView1)).setText("Addition : "+ result.toString());
} catch (Exception E) {
E.printStackTrace();
//((TextView) findViewById(R.id.textView1)).setText("ERROR:"
// + E.getClass().getName() + ":" + E.getMessage());
}
return result;
}
}
}
What I want to do is return the String result value to the main UI, so that I can set that value to the textview.
String result;
TextView tv=findViewById(R.id.textView1);
tv.setText(result);
How might I do this?
You should Override the onPostExecute() method.
Something like this :
#Override
protected void onPostExecute(String result) {
TextView tv = findViewById(R.id.textView1);
tv.setText(result);
}

Response received from web service is null

I am sending details to be stored in a database using a web service using KSOAP. I have used visual studio to create the web service. The web service works fine. A string will be returned when the details have been inserted into the database. The problem is that this string is empty, maybe something is wrong in the way that i am getting the response. I have been trying to find out whats wrong for a long time. please help
public class Registration extends Activity{
private static final String SOAP_ACTION = "http://tempuri.org/register";
private static final String OPERATION_NAME = "register";
private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
private static final String SOAP_ADDRESS = "http://10.0.2.2:58076/WebSite1/Service.asmx";
Button sqlRegister, sqlView;
EditText sqlFirstName,sqlLastName,sqlEmail,sqlMobileNumber,sqlCurrentLocation,sqlUsername,sqlPassword;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
sqlFirstName = (EditText) findViewById(R.id.etFname);
sqlLastName = (EditText) findViewById(R.id.etLname);
sqlEmail = (EditText) findViewById(R.id.etEmail);
sqlMobileNumber = (EditText) findViewById(R.id.etPhone);
sqlCurrentLocation = (EditText) findViewById(R.id.etCurrentLoc);
sqlUsername = (EditText) findViewById(R.id.etUsername);
sqlPassword = (EditText) findViewById(R.id.etPwd);
sqlRegister = (Button) findViewById(R.id.bRegister);
sqlRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()){
case R.id.bRegister:
new LongOperation().execute("");
break;
}
}
});
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String firstname = sqlFirstName.getText().toString();
String lastname = sqlLastName.getText().toString();
String emailadd = sqlEmail.getText().toString();
String number = sqlMobileNumber.getText().toString();
String loc = sqlCurrentLocation.getText().toString();
String uname = sqlUsername.getText().toString();
String pwd = sqlPassword.getText().toString();
SoapObject Request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
Request.addProperty("fname", String.valueOf(firstname));
Request.addProperty("lname", String.valueOf(lastname));
Request.addProperty("email", String.valueOf(emailadd));
Request.addProperty("num", String.valueOf(number));
Request.addProperty("loc", String.valueOf(loc));
Request.addProperty("username", String.valueOf(uname));
Request.addProperty("password", String.valueOf(pwd));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
Log.d("work","work");
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
String result = response.getProperty(0).toString();
Log.d("res",result);
if(result.equals("reg"))
{
Log.d("reg","reg");
return "Registered";
}
else
{
Log.d("no","no");
return "Not Registered";
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("tag","onpost");
if(result!=null)
{
if(result.equals("Registered"))
{
Toast.makeText(Registration.this, "You have been registered Successfully", Toast.LENGTH_LONG).show();
}
else if(result.equals("Not Registered"))
{
Toast.makeText(Registration.this, "Try Again", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(Registration.this, "Somethings wrong", Toast.LENGTH_LONG).show(); ///This is what gets printed on screen
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
Your webservice is returning a String.
Try using this to solve your problem
Object result = envelope.getResponse();
when your webservice return values of type byte[] ,you can do this:
SoapObject response=(SoapObject)envelope.bodyIn;
Hope it helps

Categories

Resources