Ksoap2 Android adding Attributes to a simple property - android

I am trying to create a new property inside a SoapObject that will contain simple string properties with attributes to them like this:
<Power Unit="kw">1500</Power>
here is the code i am using for my samples below.
final SoapObject powerObject= new SoapObject(namespace, "Power");
powerObject.addAttribute("Unit", getPowerUnit());
PropertyInfo powerObjectProperty = new PropertyInfo();
powerObjectProperty .setName("");
powerObjectProperty .type = String.class;
powerObjectProperty .setValue(getPower());
powerObjectProperty .addProperty(powerObjectProperty);
root.addSoapObject(powerObject); // this is my root for the hierarchy
The best that i could reach is the following:
<Power Unit="kw"><>1500</></Power>
i even tried to add everything as a string but that encodes the <> tags.
&ltPower Unit"kw"&gt1500&lt/Power&gt
I am using:
ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar on android.

Ok i have solved this issue, here is how:
I have created a new soap object called TextSoapObject
public class TextSoapObject extends SoapObject {
public static final String TAG = TextSoapObject.class.getSimpleName();
public TextSoapObject(String namespace, String name) {
super(namespace, name);
}
public String text;
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
Next i overrided SoapSerialization envelope like this:
public class ValueSerializationEnvelope extends SoapSerializationEnvelope {
public ValueSerializationEnvelope(int version) {
super(version);
}
public static final String TAG = ValueSerializationEnvelope.class.getSimpleName();
#Override
public void writeObjectBody(XmlSerializer writer, KvmSerializable obj) throws IOException {
if (obj instanceof TextSoapObject) {
writer.text(((TextSoapObject) obj).getText());
}
super.writeObjectBody(writer, obj);
}
}
And that's it.
To use this you would do the following:
final TextSoapObject costOfRepairs = new TextSoapObject(namespace, "CostOfRepairs");
costOfRepairs.addAttribute("Currency", getCurrency());
costOfRepairs.setText(getRepairCosts() + "");
root.addSoapObject(costOfRepairs);
EDIT:
This issue has been recognized for the ksoap2 library and addressed here:
http://code.google.com/p/ksoap2-android/issues/detail?id=112
Should be fixed in the next ksoap2 Release.

Try the following code
SoapObject soOriginDestInfo = new SoapObject(namespace_ns, "OriginDestinationInformation");
SoapPrimitive spDeptDtTm = new SoapPrimitive(namespace_ns, "DepartureDateTime", "asdadsad");
spDeptDtTm.addAttribute("Unit", "kw");
soOriginDestInfo.addProperty("DepartureDateTime", spDeptDtTm);
request.addSoapObject(soOriginDestInfo);

You can add property in your soap object and pass any value you want.
SoapObject request = new SoapObject(NAMESPACE, NAME);
request.addProperty("powerInKw", 1500);
like a key value pair.

I'm consuming some .NET web services and need to addAttribute to an addProperty while using ksoap for this xml:
<Element FirstAttribute="int" SecondAttribute="double" />
Here's what I did (including some extra help looping and passing in a double) to pass in this request:
String xml = null;
final String NAMESPACE = "http://yournamespace.org/";
final String SOAP_ACTION = "http://yournamespace.org/NameOfYourOperation";
final String METHOD_NAME = "NameOfYourOperation";
final String URL = "http://whereyourserviceis.com/Service.asmx";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
for (int i=0; i < anArray.size(); i++)
{
Some_obj obj = anArray.get(i);
SoapObject attributes = new SoapObject(NAMESPACE, "Element");
int a = Integer.parseInt(obj.someIntString);
attributes.addAttribute("FirstAttribute", a);
Double v = Double.parseDouble(obj.someDoubleString);
attributes.addAttribute("Value", v);
request.addProperty("SecondAttribute", attributes);
//request.addSoapObject(request);
Log.d(TAG,"=======obj.someIntString======: " + a + "=======obj.someDoubleString========: " + v);
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
MarshalFloat md = new MarshalFloat();
md.register(envelope);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
envelope.implicitTypes = true;
envelope.setAddAdornments(false);
try
{
HttpTransportSE transport = new HttpTransportSE(URL, 60000);
transport.debug = true;
transport.call(SOAP_ACTION, envelope);
xml = transport.responseDump.toString();
Log.d(TAG, "getUpdates===============" + xml);
}
catch(SocketException ex)
{
Log.e("SocketException : " , "Error on getUpdates() " + ex.getMessage());
}
catch (Exception e)
{
Log.e("Exception : " , "Error on getUpdates() " + e.getMessage());
}
Take note of the MarshalFloat part...this is there if you're passing in a double value so the soap can serialize properly.

Related

Display data with the same title but different content

Let's say if I have a database which contain:
ID: 1 | Name: hello | Content1: sample1 | Content2: sample2
And I have developed a WSDL webservice which have the result like this:
<name> hello </name>
<content1> sample1 </content1>
<content2> sample2 </content2>
I have used KSOAP2 to read the data from the webservice.
String NAMESPACE = "blablabla";
String METHOD_NAME = "RequestDetails";
String SOAP_ACTION = NAMESPACE + METHOD_NAME;
String URL = "blablabla";
try {
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = false;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport = new HttpTransportSE(URL, 1000000);
Log.i(TAG, "transport started and completed! ");
transport.call(SOAP_ACTION, soapEnvelope);
SoapObject resultString = (SoapObject) soapEnvelope.getResponse();
constructor.setName(resultString.get("name").toString());
constructor.setContent1(resultString.get("content1").toString());
constructor.setContent2(resultString.get("content2").toString());
} catch(Exception e) {
e.printStackTrace();
}
list.add(construct);
And now I put this list into a customAdapter. Then, the result will be like:
Name
Content1
Content2
Is there anywhere for me to make the result be like?
Name
Content1
Name
Content2
As it is a listview, so i wish to have
Name
Content1 is position 0.
Name
Content2 is position 1.
all you need to do is make listview_item_row as
name
content1
name
content2
and while adding data to listview just check name and content,
ex:
if(content2 == null)
do not add name for content 2
if(content2 != null)
then jsonparsing be like
constructor.setName(resultString.get("name").toString());
constructor.setContent1(resultString.get("content1").toString());
constructor.setName(resultString.get("name").toString());
constructor.setContent2(resultString.get("content2").toString());
try following apprach
create model class
public class SampleModel {
String title;
String content;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
public class SampleClass extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String NAMESPACE = "blablabla";
String METHOD_NAME = "RequestDetails";
String SOAP_ACTION = NAMESPACE + METHOD_NAME;
String URL = "blablabla";
List<SampleModel> arrayList = new ArrayList<>();
try {
SampleModel model;
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = false;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport = new HttpTransportSE(URL, 1000000);
transport.call(SOAP_ACTION, soapEnvelope);
SoapObject resultString = (SoapObject) soapEnvelope.getResponse();
model = new SampleModel();
model.setTitle(resultString.get("name").toString());
model.setContent(resultString.get("content1").toString());
arrayList.add(model);
if (resultString.get("content2").toString() != null) {
model = new SampleModel();
model.setTitle(resultString.get("name").toString());
model.setContent(resultString.get("content2").toString());
arrayList.add(model);
}
} catch (Exception e) {
e.printStackTrace();
}
// here pass this arraylist to customListAdapeter
//list.add(construct);
}
}

org.xmlpull.v1.xmlpullparserexception expected start_tag error when using ksoap2

I use ksoap2 to connect .NET by web service.
This is my Dataset
public DataSet getphimall()
{
DataSet ds1 = new DataSet();
try
{
SqlConnection cnn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=EMHAUI;Integrated Security=True");
SqlCommand cmd = new SqlCommand("sp_GetAllSemester_ad", cnn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds1);
return ds1;
}
catch (Exception e)
{
return null;
}
}
And this is my webservice
[WebMethod]
public DataSet getSM()
{
Class1 phim1 = new Class1();
return phim1.getphimall();
}
And this is my javaconnector class
public class getSM {
String tenphim;
String daodien;
private static final String SOAP_ACTION = "http://tempuri.org/getSM";
private static final String METHOD_NAME = "getSM";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:50532/wsAndroid.asmx";
public getSM getallphim()
{
SoapObject table = null;
SoapObject client = null;
SoapObject tableRow = null;
SoapObject responseBody = null;
AndroidHttpTransport transport = null;
SoapSerializationEnvelope sse = null;
//cái này trong tut viết thế, mình lười đổi tên
sse = new SoapSerializationEnvelope(SoapEnvelope.VER11);
sse.addMapping(NAMESPACE, "getSM", this.getClass());
sse.dotNet = true;
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
getSM setphim = new getSM();
try
{
client = new SoapObject(NAMESPACE, METHOD_NAME);
sse.setOutputSoapObject(client);
sse.bodyOut = client;
androidHttpTransport.call(SOAP_ACTION, sse);
responseBody = (SoapObject) sse.getResponse();
responseBody = (SoapObject) responseBody.getProperty(1);
table = (SoapObject) responseBody.getProperty(0);
tableRow = (SoapObject) table.getProperty(0);
setphim.daodien = tableRow.getProperty("ID").toString();
setphim.tenphim = tableRow.getProperty("SemesterName").toString();
return setphim;
} catch (Exception e)
{
setphim.daodien = e.toString();
setphim.tenphim = e.toString();
return setphim;
}
}}
But When I run my emulator, I have an error
org.xmlpull.v1.xmlpullparserexception expected start_tag error
Please help me! Thanks
There might be a few reasons for the exception that you are getting.
Wrong Parameters for the SOAP call : try to confirm if the values of NAMESPACE, ACTION, METHOD and URL are correct or not, by looking at the WSDL file
Invalid response from server : try to log the response that the server sends to you and check if you are getting correct well-structured XML or not
androidHttpTransport.debug = true;
//execute request
androidHttpTransport.responseDump; //response string from server
dotNet attribute of the envelope : try using soapEnvelope.dotNet=true

How to pass Custom Arraylist to Soap web service?

thanks for reading my problem,
i am trying to pass Custom ArrayList to SOAP service which gives me cannot serialize exception,
here is my code
// Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_CALL);
UserInfo userInfo = new UserInfo();
userInfo.name = "xyz";
userInfo.keyName = "name";
userInfoList.add(userInfo);
UserInfo userInfo1 = new UserInfo();
userInfo1.email = "xcv#gmail.com";
userInfo1.keyEmail = "email_id";
userInfoList.add(userInfo1);
UserInfo userInfo2 = new UserInfo();
userInfo2.mobile = "9876543210";
userInfo2.keyMob = "mobileno";
userInfoList.add(userInfo2);
UserInfo userInfo3 = new UserInfo();
userInfo3.regId = "xyz";
userInfo3.keyRegId = "registrationid";
userInfoList.add(userInfo3);
UserInfo userInfo4 = new UserInfo();
userInfo4.appVersion = "1.0";
userInfo4.keyAppVersion = "appversion";
userInfoList.add(userInfo4);
UserInfo userInfo5 = new UserInfo();
userInfo5.xmlString =
"<?xml version=\"1.0\" encoding=\"UTF- 8\"standalone=\"no\"?>"
+ "<a><s><s>"
+ "<d>d</d>"
+ "<f>f</f>"
+ "</a>"
userInfo5.keyXmlString = "xml_string";
userInfoList.add(userInfo5);
request.addProperty("method", "addDeviceInfo");
request.addProperty("parameter", userInfoList);
Log.e("request", "--->>> " + request);
// Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
Log.e("1111", "1111");
envelope.setOutputSoapObject(request);
Log.e("222", "222");
envelope.dotNet = false;
envelope.bodyOut = request;
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
Log.e("333", "3333");
// Needed to make the internet call
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
Log.e("44444", "44444");
androidHttpTransport.debug = true;
try {
Log.e("55555", "55555");
// this is the actual part that will call the webservice
androidHttpTransport.call(MainActivity.SOAP_ACTION, envelope);
Log.e("Request", androidHttpTransport.requestDump);
Log.e("Response", androidHttpTransport.responseDump);
} catch (Exception e) {
e.printStackTrace();
}
try {
SoapObject result = (SoapObject) envelope.bodyIn;
Log.e("result", "--->> " + result);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
problem is i get everything proper but when it comes to androidHttpTransport.call(MainActivity.SOAP_ACTION, envelope);
is says java.lang.RuntimeException: Cannot serialize: [com.example.soapdemo.UserInfo#40da80a8]
here is my user info class
package com.example.soapdemo;
import java.io.Serializable;
import java.util.Hashtable;
import org.apache.http.entity.SerializableEntity;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
public class UserInfo implements Serializable {
public String keyName;// = "name";
public String name;
public String keyEmail;// = "email_id";
public String email;
public String keyMob;// = "mobile_no";
public String mobile;
public String keyRegId;// = "registration_id";
public String regId;
public String appVersion;
public String keyAppVersion;
public String xmlString;
public String keyXmlString;
}
help me resolving this is, any reply is very appreciable
Thanks in advance
i have already gone through many pages but could not solve this issue
i will really appreciate if any one can solve this issue and help me out
thank you very much

kSoap, when I get my parameters on my webservice their values are null, why?

I'm trying to make a webservice in Java (Tomcat) and I'm calling it from Android with kSoap. The parameters when my webService is called are null. I don't know why.
Data of my WebService
Punto Final Información
Nombre de Servicio\: {http://serv.trivial.com/}UsuariosWebServiceImplService
Nombre de Puerto\: {http://serv.trivial.com/}UsuariosWebServiceImplPort
Dirección\: .../UsuariosWebService/usuarios
Clase de Implantación\: com.trivial.serv.UsuariosWebServiceImpl
And my code is:
private void registroServidor(String usuario, String regId)
{
//http://localhost:8080/UsuariosWebService/usuarios?wsdl
final String NAMESPACE = "http://serv.trivial.com/"; //Buscar namespace en el wsdl
final String URL="http://10.0.2.2:8080/UsuariosWebService/usuarios";
final String METHOD_NAME = "createUser";
//final String SOAP_ACTION = "http://serv.trivial.com/createUser";
final String SOAP_ACTION = "";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("usuario", usuario);
request.addProperty("regGCM", regId);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
//envelope.doNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try
{
transporte.call(SOAP_ACTION, envelope);
SoapPrimitive resultado_xml =(SoapPrimitive)envelope.getResponse();
String res = resultado_xml.toString();
if(res.equals("true"))
Log.d("GCMTest", "Registro WS: OK.");
}
catch (Exception e)
{
System.out.println("EXCEPTION!!!!!!" + e);
e.printStackTrace();
Log.d("GCMTest", "Registro WS: NOK. " + e.getCause() + " || " + e.getMessage());
}
}
My WebService:
#Override
#WebMethod
public boolean createUser(#QueryParam("usuario") String usuario,#QueryParam("regGCM") String regGCM) {
System.out.println("2222");
boolean result = false;
UsuarioDTO dto = new UsuarioDTO();
//!!!!!! regGCM and usuario are null!!!!!!
dto = new UsuarioDTO(regGCM, usuario);
if (dao.findUserByUsuario(usuario) != null){
result = dao.update(dto);
}else{
result = dao.insert(dto);
}
System.out.println("New User info: " + dto.toString());
return result;
}
#WebMethod
public abstract boolean createUser(#QueryParam("usuario") String usuario,#QueryParam("regGCM") String regGCM);
Personally I've successfully used ksoap to connect to a .NET web service, so I am not sure what your parameter names should look like when using Tomcat. I have noticed however that you do not specify the data type for your parameters - could this be the problem? Here's an example:
// ## init request parameters
PropertyInfo pi = new PropertyInfo();
// ## usuario
pi.setName("usuario");
pi.setValue(usuario);
pi.setType(String.class);
request.addProperty(pi);

Web Service Issue

I am using Soap WEb service but I am facing one problem like this soap:Server' faultstring: 'Server was unable to process request. ---> There is no row at position 0.' faultactor: 'null
My Code is
public class GetData extends Activity {
private static final String SOAP_ACTION="http://xxx.mobi/GetMobileContentMetaData";
private static final String METHOD_NAME="GetMobileContentMetaData";
private static final String NAMESPACE ="http://xxx.mobi/";
private static final String URL = "http://webservices.xxx.mobi/MobileLMSServices.asmx";
SoapObject request;
Button submit;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getdata);
submit=(Button)findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("SiteURL","http://heaklthcare.xxx.mobi/");
request.addProperty("ContentID","62b90739-57b9-47cc-884a-8be2ef265304");
request.addProperty("UserID",809);
request.addProperty("DelivoryMode",2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
SoapObject result = null;
envelope.setOutputSoapObject(request);
AndroidHttpTransport sab = new AndroidHttpTransport(URL);
sab.debug = true;
try {
sab.call(SOAP_ACTION, envelope);
if (envelope.getResponse() != null)
{
result = (SoapObject) envelope.bodyIn;
for (int i1 = 0; i1 < 1; i1++) {
Object property = result.getProperty(i1);
if (property instanceof SoapObject) {
SoapObject countryObj = (SoapObject) property;
Log.d("country" ,"object"+countryObj);
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Should be an error returned by the server. If you can, call the web method from .net (or if you have a localhost copy of the webservice, input parameters in the browser) .
I struggled with this error this morning, then I did a small (5 lines) .net app to call the web method. then i got a clearer error message. Also turned out my java code had no problems the whole time.

Categories

Resources