This is the function which is to call the function in the server to perform some task. But i have to pass in a ArrayList and a String value. I have trouble passing the ArrayList to the server. Can anyone tell me what i should do?
public void findLocation(ArrayList<APData> apdatalist, String profilename){
SoapObject request = new SoapObject(NAMESPACE, "FindLocation");
PropertyInfo quotesProperty = new PropertyInfo();
quotesProperty.setName("profileName");
quotesProperty.setValue(profilename);
quotesProperty.setType(String.class);
request.addProperty(quotesProperty);
request.addProperty("AP_List", APData.class);
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpRequest = new HttpTransportSE(URL);
httpRequest.debug = true;
String result = "";
try
{
httpRequest.call(SOAP_ACTION, envelope);
Log.e("Request",httpRequest.requestDump.toString());
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.e("Response",httpRequest.responseDump.toString());
result = response.toString();
if(result == null){
Log.e("AndroidRuntime", "No location result is return!");
}
}
catch(Exception e)
{
e.printStackTrace();
}
//return temp;
}
I've found a possible solution. I've modified the SoapSerializationEnvelope class to deal with ArrayList.
I modified the method
public void writeObjectBody(XmlSerializer writer, KvmSerializable obj)
public void writeObjectBody(XmlSerializer writer, KvmSerializable obj) throws IOException
{
// Added this code for parsing attributes of KvmSerializable objects
int cnt = obj.getPropertyCount();
PropertyInfo info = new PropertyInfo();
for (int i = 0; i < cnt; i++)
{
Object prop = obj.getProperty(i);
if(!(prop instanceof SoapObject)) {
// prop is a PropertyInfo
obj.getPropertyInfo(i, properties, info);
// Added this code to parse ArrayList objects in requests
if(prop instanceof ArrayList<?>){
ArrayList<?> values = (ArrayList<?>)prop;
for(Object o : values){
writer.startTag(info.namespace, info.name);
writeProperty(writer, o, info);
writer.endTag(info.namespace, info.name);
}
}else if ((info.flags & PropertyInfo.TRANSIENT) == 0)
{
writer.startTag(info.namespace, info.name);
writeProperty(writer, obj.getProperty(i), info);
writer.endTag(info.namespace, info.name);
}
} else {
// prop is a SoapObject
SoapObject nestedSoap = (SoapObject)prop;
writer.startTag(nestedSoap.getNamespace(), nestedSoap.getName());
writeObjectBody(writer, nestedSoap);
writer.endTag(nestedSoap.getNamespace(), nestedSoap.getName());
}
}
}
This seems to work for me
Related
This is my web service code.I don't know how to parse soap response.what should i do? i don't even know it is json or Xml.So please tell me which type of response it is?
my response like this
anyType{Product_Details=anyType{P_id=129;p_name=ffff;C_name=gggg;};}
public class MyAsyncTask extends AsyncTask<String, String , String>
{
#Override
protected void onPostExecute(String arrPersons )
{
uid.setText(arrPersons);
}
#Override
protected void onProgressUpdate(String... text)
{
uid.setText(text[0]);
}
#Override
protected String doInBackground(String... arg0)
{
SOAP_ADDRESS="";
request=new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
publishProgress("Loading contents...");
PropertyInfo pi=new PropertyInfo();
pi.setName("PID");
pi.setValue(Integer.parseInt(arg0[1]));
pi.setType(String.class);
request.addProperty(pi);
pi=new PropertyInfo();
envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
httpTransport=new HttpTransportSE(SOAP_ADDRESS);
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
for (int i = 0; i < response.getPropertyCount(); i++)
{
Object property = response.getProperty(i);
if (property instanceof SoapObject)
{
SoapObject category_list = (SoapObject) property;
String returnString1 = category_list.getProperty(0).toString();
}
}
}
catch (Exception e)
{
returnString1 = e.getMessage();
}
return returnString1;
}
}
The format might in data table return format. you better show your web services code which you created on asp.net
This is my asp code for Web service
public class qr : System.Web.Services.WebService {
[WebMethod]
public DataTable findData(String PID)
{
String constr = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Product_Details WHERE P_id = #P_id"))
{
cmd.Parameters.AddWithValue("#P_id", PID);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
dt.TableName = "Product_Details";
sda.Fill(dt);
return dt;
}
}
}
}
}
I have a web service made in asp.net which returns a list of String .
here is the code :
<WebMethod()> Public Function HelloWorld() As List(Of String)
Dim a As New List(Of String)
a.Add("2")
a.Add("2")
a.Add("2")
a.Add("2")
a.Add("2")
Return a
End Function
and this is the coding in android app :
SoapObject request = new SoapObject(wsdl_target_namespace,operation_name);
SoapSerializationEnvelope envelope= new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(soap_address);
Log.d("test", "test");
try{
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
txt.setText(String.valueOf(response));
Log.d("test", String.valueOf(response));
} catch(Exception exception){
txt.setText(exception.toString());
Log.d("error_mine", exception.toString());
}
this code returns me this in text box :
anyType {
string=2;
string=2;
string=2;
string=2;
string=2
}
but i want this as a list to populate a list view .
how can i do this ?
Try Following code :
// ArrayList to store the data from web service :
// **You can initialize this string globally**
ArrayList<String> mArrayList = new ArrayList<String>();
-----------------------------------------------
Object response = envelope.getResponse();
// need to replace this line with the following
-----------------------------------------------
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject) envelope.bodyIn;
if (result != null) {
for (int i = 0; i < result.getPropertyCount(); i++) {
mArrayList.add(result.getProperty(i));
}
}
I've a .net webservice, where I have to send a param (type of dateTime), as You can see:
<startDateTime>dateTime</startDateTime>
In Android client, I use ksoap2, and I don't know , How to send that type of data?
Please help with setting this type - code below not works.
PropertyInfo propInfo3 = new PropertyInfo();
propInfo3.name="startDateTime";
propInfo3.value="2012-02-01";
Here is how I call web service methods in my application. Note the method I used to convert java dates. You require an ISO date format.
protected static Object callMethod(String method, Map<String, Object> parameters) throws IOException, XmlPullParserException {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, method);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.headerOut = new Element[1];
envelope.headerOut[0] = buildAuthHeader();
envelope.setOutputSoapObject(request);
if (parameters != null) {
for (String item : parameters.keySet()) {
Object itemValue = parameters.get(item);
if (itemValue.getClass().getName().equals("java.util.Date")) {
// If it's a date then we have to format it because ksoap
// does not know how to do this.
request.addProperty(item, getSOAPDateString((java.util.Date) itemValue));
} else {
request.addProperty(item, itemValue);
}
}
}
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS, 10000);
httpTransport.debug = true;
httpTransport.call(WSDL_TARGET_NAMESPACE + "/" + method, envelope);
String soapString = httpTransport.requestDump;
System.out.println(soapString);
return envelope.getResponse();
}
Here is the method that returns the actual string:
private static Object getSOAPDateString(java.util.Date itemValue) {
String lFormatTemplate = "yyyy-MM-dd'T'hh:mm:ss'Z'";
DateFormat lDateFormat = new SimpleDateFormat(lFormatTemplate);
String lDate = lDateFormat.format(itemValue);
return lDate;
}
In your server, what's the return from the client?
When I have a problem like this, I show in the Logcat on Android what I'm sending and in the server side what I'm getting.
I had a little problem with date too (I'm using ksoap2 and webservices), I solve my problem sending the date in the util.Date, then I use SimpleDateFormat with a pattern date in my project and convert that string to what I want.
cya,
Bertan
Here is my code that sends to the WS:
public static byte[] send(String... param) throws SocketTimeoutException, IOException, XmlPullParserException, Exception{
//First I send the WS Name
String ws = param[0];
//Second is the operationName
SoapObject soap = new SoapObject(URL_SOAP, param[1]);
Object retorno = null;
int tamParam = param.length;
//The 3 parameter for the infinity its the properties, name and the next it's the value...
if (tamParam > 0) {
for (int i = 2; i < tamParam; i++) {
soap.addProperty(param[i], param[++i]);
}
}
// create a envelope for the soap object
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(soap);
// create a HttpTransport to send the object soap with 15s delay
MyHttpTransport httpTransport = new MyHttpTransport(URL + ws, 15000);
// send the req
Long tempo1 = 0l;
tempo1 = System.currentTimeMillis();
httpTransport.call("", envelope);
retorno = envelope.getResponse();
Long tempo2 = System.currentTimeMillis();
httpTransport.reset();
//I ever get byte[] from the WS...
if (retorno != null) {
byte[] bloc = Base64.decode(retorno.toString(), Base64.DEFAULT);
return bloc;
} else {
return null;
}
}
I've follow the code for parsing the value with JSON from here, but I get the problem in my return statement. I want to put the parsing result into my return statement. How to do that?
Here is my code:
public String MASUK(String user, String password)
{
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("ccduser");
pi.setValue(user);
pi.setType(String.class);
request.addProperty(pi);
PropertyInfo pi2 = new PropertyInfo();
pi2.setName("password");
pi2.setValue(password);
pi2.setType(String.class);
request.addProperty(pi2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject resultSOAP = (SoapObject) envelope.bodyIn;
/* gets our result in JSON String */
String ResultObject = resultSOAP.getProperty(0).toString();
resultSOAP = (SoapObject) envelope.bodyIn;
ResultObject = resultSOAP.getProperty(0).toString();
if (ResultObject.startsWith("{")) { // if JSON string is an object
JSONObj = new JSONObject(ResultObject);
Iterator<String> itr = JSONObj.keys();
while (itr.hasNext()) {
String Key = (String) itr.next();
String Value = JSONObj.getString(Key);
BundleResult.putString(Key, Value);
// System.out.println(bundleResult.getString(Key));
}
}
else if (ResultObject.startsWith("[")) { // if JSON string is an array
JSONArr = new JSONArray(ResultObject);
System.out.println("length" + JSONArr.length());
for (int i = 0; i < JSONArr.length(); i++) {
JSONObj = (JSONObject) JSONArr.get(i);
BundleResult.putString(String.valueOf(i), JSONObj.toString());
// System.out.println(bundleResult.getString(i));
}
}
}
catch (Exception exception)
{
}
return null;
}
If you have JSON array object:
JSONObject jObject = new JSONObject(***JSON String you have ***);
JSONArray contestantObjects = jObject.getJSONArray("*** Array Name ***");
for(int i=0; i<contestantObjects.length(); i++) {
mChannels.setId(contestantObjects.getJSONObject(i).getString("id").toString());
mChannels.setName(contestantObjects.getJSONObject(i).getString("name").toString());
}
If you have just one item:
JSONObject jObject = new JSONObject(***JSON String you have ***);
mPreview.setBody(jObject.getString("*** Item Name ***").toString());
mPreview.setPublishedDate(jObject.getString("publishedDate").toString());
mPreview.setRefKey(jObject.getString("refKey").toString());
mPreview.setTitle(jObject.getString("title").toString());
http://jsonviewer.stack.hu/ is online tool for parsing JSON. its awesome you can use it.
JSONObject prefsJson = new JSONObject(prefsJsonString);
String str = prefsJson.has("str") == true ? prefsJson.getString("str") : "";
Is that ok?
Referring to the link which you have used to parse the JSON String, I would suggest that you return the object bundleResult from your function. Change the return value for your method as public Bundle MASUK(String user, String password).
EDIT
Don't forget to initialize the Bundle object:
private Bundle bundleResult=new Bundle();
And take care not to change the case (upper/lower case) for the variable being used. I could see in your code BundleResult.putString(Key, Value); and the reference link uses bundleResult.putString(Key, Value);
I'm using webservices for an application to get the data from external servers. I'm able to connect to the server, send my SOAP request and able get the data back to my android class as SoapObject.
Here I'm having trouble parsing this SoapObject to retrieve the values (as strings) coming from the webservice.
My code is here:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
mInflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
System.out.println("Entered "+getClass().getSimpleName());
//Calling the web service to get the documents list
callService("getDocumentsList","http://wservice.friedmaggy.com/getDocumentsList");
-- I have created callService method to call the webservice.:
public void callService(String operation, String soapaction)
{
try {
String SOAP_ACTION = soapaction;
String OPERATION_NAME = operation;
String WSDL_TARGET_NAMESPACE = getString(R.string.targetNamespace);
String SOAP_ADDRESS = getString(R.string.soapAddress);
SoapObject request = new SoapObject(
WSDL_TARGET_NAMESPACE, OPERATION_NAME);
System.out.println("SOAP_ACTION "+SOAP_ACTION);
System.out.println("OPERATION_NAME "+OPERATION_NAME);
System.out.println("WSDL_TARGET_NAMESPACE "+WSDL_TARGET_NAMESPACE);
System.out.println("SOAP_ADDRESS "+SOAP_ADDRESS);
// System.out.println("SOAP_ACTION "+SOAP_ACTION);
PropertyInfo propInfo = new PropertyInfo();
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
HttpTransportSE httpTransport = new HttpTransportSE(
SOAP_ADDRESS);
envelope.setOutputSoapObject(request);
httpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject) envelope.bodyIn;
if(response.getPropertyCount()>0){
data=new StringBuilder();
for (int i = 0; i < response.getPropertyCount(); i++) {
Course c = new Course((SoapObject) response.getProperty(i));
courseList.add(c);
}
for (Course c : courseList) {
data.append("CourseName :" + c.getName());
results.add(c.getName());
}
-- As seen above, i'm passing the whole response object to another bean class to fetch the values.(Course c = new Course((SoapObject) response.getProperty(i));)
Can you help me how to parse this response object to fetch the required String values out.?
androidHttpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
Vector<SoapObject> res= null;
if (response instanceof SoapObject) {
res = new Vector();
res.add((SoapObject) response);
} else if (response instanceof Vector) {
res = (Vector<SoapObject>) response;
}
for(SoapObject so1: res){
//retrieve String here from soap object using this
so1.getProperty(0).toString();
//then so1.getProperty(1).toString and likewise
}