In my case, I have a soap response which has an "ArrayOfArrayOfString" type of values stored in it.
It is like an Array A[4][4].
A[0][0] -> ServiceId
A[0][1] -> ServiceName
A[0][2] -> ServiceImageURL
A[0][3] -> ServiceDecription
A[0][4] -> ServiceIconURL
and its all same upto A[4][4].
How can I handle this type of response in android?
Code is something like:
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transportSE = new HttpTransportSE(URL);
transportSE.debug = true;
Log.i("WebService", "msg:try_out");
String[] columns = null;
ArrayList<String> rows = new ArrayList<String>();
try
{
Log.i("WebService", "msg:try+in");
transportSE.call(SOAP_ACTION, envelope);
Log.i("WebService", "msg:SoapObject");
SoapObject response = (SoapObject)envelope.getResponse();
Log.i("WebService", "Response");
try
{
// WhaT SHOULD I USE HERE to convert it to 2D Array//
}
catch (Exception e)
{
e.printStackTrace();
Log.v("CATCH BLOCK", e.getMessage());
}
}
catch (Exception e)
{
e.printStackTrace();
Log.i("WebService", "msg:Exception error");
Log.i("WebSerivce", e.getMessage());
return e.getMessage();
}
Please help me regarding this.
This is the perfect working code to parse the complex data...
I am only doing this for A[0][1-4] and according to my soap response modify the code according to ur soap response.
SoapObject result = (SoapObject)enevlop.getResponse();
String str = result.getProperty(0).toString();
// add a for loop for ur code and iterate it according to ur soap response and get all the node using getProperty(i);
String str1 = lameParser(str);
textView.setText(""+str1);
Now define lameParser() method:-
public String lameParser(String input){
String sName=input.substring(input.indexOf("sName=")+6, input.indexOf(";", input.indexOf("sName=")));
int IGoals=Integer.valueOf(input.substring(input.indexOf("iGoals=")+7, input.indexOf(";", input.indexOf("iGoals="))));
String sCountry=input.substring(input.indexOf("sCountry=")+9, input.indexOf(";", input.indexOf("sCountry=")));
String sFlag=input.substring(input.indexOf("sFlag=")+6, input.indexOf(";", input.indexOf("sFlag=")));
return sName+"\n"+Integer.toString(IGoals)+"\n"+sCountry+"\n"+sFlag;
}
Here's code to parse multiple child node of xml data...
public static void parseBusinessObject(String input, Object output) throws NumberFormatException, IllegalArgumentException, IllegalAccessException, InstantiationException{
Class theClass = output.getClass();
Field[] fields = theClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Type type=fields[i].getType();
fields[i].setAccessible(true);
//detect String
if (fields[i].getType().equals(String.class)) {
String tag = "s" + fields[i].getName() + "="; //"s" is for String in the above soap response example + field name for example Name = "sName"
if(input.contains(tag)){
String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag)));
if(strValue.length()!=0){
fields[i].set(output, strValue);
}
}
}
//detect int or Integer
if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
String tag = "i" + fields[i].getName() + "="; //"i" is for Integer or int in the above soap response example+ field name for example Goals = "iGoals"
if(input.contains(tag)){
String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag)));
if(strValue.length()!=0){
fields[i].setInt(output, Integer.valueOf(strValue));
}
}
}
//detect float or Float
if (type.equals(Float.TYPE) || type.equals(Float.class)) {
String tag = "f" + fields[i].getName() + "=";
if(input.contains(tag)){
String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag)));
if(strValue.length()!=0){
fields[i].setFloat(output, Float.valueOf(strValue));
}
}
}
}
}
If you will like the post give me the up vote so that visitors find it easily....
try
{
Log.i("WebService", "Try Block");
transportSE.call(SOAP_ACTION, envelope);
Log.i("WebService", "msg:SoapObject");
SoapObject response = (SoapObject)envelope.getResponse();
Log.i("WebService", "Response on");
int totalService = response.getPropertyCount();
int i;
String str ;
String str1;
for (i = 0; i < totalService; i++)
{
str = response.getProperty(i).toString();
Log.i("WebService", "ForLoop "+ Integer.toString(i));
str1 = lameParser(str, i);
Log.i("WebService", "ForLoop: lameParser done");
Log.i("WebService", "Value Stored:: "+ str1);
}
}
catch (Exception e)
{
e.printStackTrace();
Log.i("WebService", "msg:Exception error");
Log.i("WebSerivce", e.getMessage());
}
}
private String lameParser(String input, int I)
{
int i = I;
Log.i("WebService", "LameParse()" );
try
{
String SId = input.substring(input.indexOf("{string=")+8, input.indexOf(";", input.indexOf("{string=")));
String SName = input.substring(input.indexOf(" string=")+8, input.indexOf(";", input.indexOf(" string=")));
String SIurl = input.substring(input.indexOf("http"), input.indexOf(";", input.indexOf("http")));
String SIcon = input.substring(input.indexOf("jpg; string=")+12, input.indexOf("; }", input.indexOf("jpg; string=")));
// String[][] arr = new String[x][y]; is already initialized as local var of class.
arr[i][0] = SId;
arr[i][1] = SName;
arr[i][2] = SIurl;
arr[i][3] = SIcon;
return SId + "\n" + SName + "\n" + SIurl + "\n" + SIcon + "\n" ;
}
catch (Exception e)
{
Log.i("WebService", "catch exception" );
Log.i("WebService", e.getMessage());
return null;
}
}
Here's how I processed ArrayOfArrayOfString objects.
SoapObject result = (SoapObject)envelope.bodyIn;
if (result.getPropertyCount() > 0) {
SoapObject Rows = (SoapObject)result.getProperty(0);
int nRows = Rows.getPropertyCount();
for (int nRow=0; nRow<nRows; nRow++) {
SoapObject Cols = (SoapObject)Rows.getProperty(nRow);
int nCols = Cols.getPropertyCount();
for (int nCol=0; nCol<nCols; nCol++) {
String sCol = Cols.getProperty(nCol).toString();
// Process sCol with nRow and nCol as array indexes
}
}
}
Related
I'trying to Parsing JSOn object but sometime it runs properly sometime getting followoing error:
org.json.JSONException: Value null at VesselList of type
org.json.JSONObject$1 cannot be converted to JSONArray
public void getCompanyDeatails()
{
String strUrl_companyDeatls = "http://103.24.4.60/CLASSNK1/MobileService.svc/Get_Company/Sync_Time/"+strSync_Time+"/Authentication_Token/"+str_Authentication_Token;
Log.e("strUrl_companyDeatls ", " = " + strUrl_companyDeatls);
InputStream inputStream = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(strUrl_companyDeatls));
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
strResult = convertInputStreamToString(inputStream);
else
strResult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
String jsonStr = strResult;
Log.e("jsonStr ", " = " + jsonStr);
if (jsonStr != null)
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = jsonObj.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString());
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
str_CompanyId = jobCompanyDetails.getString("Company_ID");
str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
if (dbhelper.isTitleExist(str_CompanyId)) {
//Upadte
dbhelper.updatedetails(str_CompanyId, str_CompanyName);
Log.e("Data updated in ", "Company Table !!");
} else {
//insert
dbhelper.insertCompany(str_CompanyId, str_CompanyName);
Log.e("Data inserted in ", "Company Table !!");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
this is my JSON String
{"Get_CompanyResult":{"CompanylList":[{"Company_ID":93,"Company_Name":"SeaChange"},{"Company_ID":97,"Company_Name":"VM 2"}],"Sync_Time":"2015-09-11 12:44:17.533"}}
Is this code is right?
Here:
JSONArray jarr = jsonObj.getJSONArray("CompanylList");
line causing issue because CompanylList JSONArray is inside Get_CompanyResult JSONObject instead of main which is jsonObj.
Get CompanylList JSONArray from companyList JSONObject:
JSONArray jarr = companyList.getJSONArray("CompanylList");
Change your code according to here :
public void getCompanyDeatails() {
String strUrl_companyDeatls = "http://103.24.4.60/CLASSNK1/MobileService.svc/Get_Company/Sync_Time/" + strSync_Time + "/Authentication_Token/" + str_Authentication_Token;
Log.e("strUrl_companyDeatls ", " = " + strUrl_companyDeatls);
InputStream inputStream = null;
String strResult = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet("strUrl_companyDeatls"));
inputStream = httpResponse.getEntity().getContent();
// strResult = "{\\\"Get_CompanyResult\\\":{\\\"CompanylList\\\":[{\\\"Company_ID\\\":93,\\\"Company_Name\\\":\\\"SeaChange\\\"},{\\\"Company_ID\\\":97,\\\"Company_Name\\\":\\\"VM 2\\\"}],\\\"Sync_Time\\\":\\\"2015-09-11 12:44:17.533\\\"}}";
String jsonStr=null;
if (inputStream != null) {
strResult = convertInputStreamToString(inputStream);
jsonStr = strResult;
}
Log.e("jsonStr ", " = " + jsonStr);
if (jsonStr != null) {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = companyList.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString()); // error was here. You need to use companyList json object because it contains company list.
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
String str_CompanyId = jobCompanyDetails.getString("Company_ID");
String str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
// if (dbhelper.isTitleExist(str_CompanyId)) {
// //Upadte
// dbhelper.updatedetails(str_CompanyId, str_CompanyName);
// Log.e("Data updated in ", "Company Table !!");
// } else {
//
// //insert
// dbhelper.insertCompany(str_CompanyId, str_CompanyName);
// Log.e("Data inserted in ", "Company Table !!");
// }
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
}
Note :
There is no need to use nested try and catch.
For 'strResult = "Did not work!";', always make sure that every
exception handled well (at checkpoint of jsonstr is null or not you
can not identify error occurred at parsing input stream can lead to
serious bugs).
HttpClient is deprecated so make sure you use latest version of any
third party library like Volley or Retrofit for network
operation and GSON for parsing response. It will minimize your
efforts.
Thanks.
My webservice;
[WebMethod]
public int insertNhanVien(string[] arr)
{
SqlConnection con = new SqlConnection();
// con.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=Bai1;Integrated Security=True";
con.ConnectionString = "server=.\\SQLEXPRESS;database=QLNV;uid=sa;pwd=123456";
con.Open();
int n = 0;
for (int i = 0; i < arr.Length; i++)
{
string[] s = arr[i].ToString().Split(',');
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert Into MUser(Ten,Tuoi) values(" + s[0].Replace("'", "''") + "," + s[1] + ")";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
n = cmd.ExecuteNonQuery();
}
return n;
}
And code in android:
private boolean insertNhanVient() {
boolean result = false;
try {
String NAMESPACE ="http://tempuri.org/";
String METHOD_NAME ="insertNhanVien";
String URL ="http://localhost:10829/WebSite/Service.asmx";
String SOAP_ACTIONS = NAMESPACE + "/" + METHOD_NAME;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String [] arr =new String[3];
arr[0]="le,12";
arr[1]="hoang,33";
arr[2]="nhung,23";
request.addProperty("arr", arr);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidhttpTranport = new HttpTransportSE(URL);
try {
androidhttpTranport.call(SOAP_ACTIONS, envelope);
} catch (IOException e3) {
result = false;
} catch (XmlPullParserException e3) {
result = false;
}
Object responseBody = null;
try {
responseBody = envelope.getResponse();
String t = responseBody.toString();
if (t.equals("1")) {
result = true;
}
} catch (SoapFault e2) {
result = false;
}
} catch (Exception e) {
result = false;
} finally {
}
return result;
}
Why show exception: java.lang.RuntimeException: Cannot serialize: [Ljava.lang.String;#4051d0a0 ?
you can't pass whole array.. so you have to use seprator ## in String ..and pass it service... and change on service respectivley.
String commasepratedString="";
for(int i=0;i<arr.length();i++)
{
if(i!=(arr.length-1))
{
commasepratedString=commasepratedString+arr[i]+"##";
}
else
{
commasepratedString=commasepratedString+arr[i];
}
}
request.addProperty("arr", commasepratedString);
and change service code like this way
[WebMethod]
public int insertNhanVien(string commasepratedString)
{
String arr[] = commasepratedString.Split('##');
SqlConnection con = new SqlConnection();
// con.ConnectionString = "Data Source=.\\SQLEXPRESS;InitialCatalog=Bai1; Integrated Security=True";
con.ConnectionString = "server=.\\SQLEXPRESS;database=QLNV;uid=sa;pwd=123456";
con.Open();
int n = 0;
for (int i = 0; i < arr.Length; i++)
{
string[] s = arr[i].ToString().Split(',');
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert Into MUser(Ten,Tuoi) values(" + s[0].Replace("'", "''") + "," + s[1] + ")";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
n = cmd.ExecuteNonQuery();
}
return n;
}
replace this line
request.addProperty("arr", arr);
with this
request.addProperty("arr", arr[0]);
you cannot pass whole array.you should pass one element of it.
Update
You can add multiple properties like
request.addProperty("prop1", arr[0]);
request.addProperty("prop2", arr[1]);
request.addProperty("prop3", arr[2]);
I am trying to send the send voice data immediately to local server using audiorecord.. I am able to record the voice & stores it in SDcard.. but I want to store audio voice in buffer & sends immediate to the server using HTTP POST. How can I proceed.got struck..? I am creating this app in ICS i.e android 4.0.3 version.
got the solutions.. sending voice data as a jsonarray to server & recieve back as a json object. convert back jsonobject to short array n write to audiotrack then play back. here is sample code working.
public void SendAudio() {
String LOG_TAG = null;
long SAMPLE_INTERVAL = 1;
Log.e(LOG_TAG, "start send thread, thread id: ");
int bytes_read = 0;
int bytes_count = 0;
br = br % 5;
br++;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpClient httpclient_recv = new DefaultHttpClient();
// System.out.println("mmdata--------- " + value);
HttpPost httppost = new HttpPost("http://192.168.1.39/call");
HttpPost httppost_recv = new HttpPost("http://192.168.1.39/ping");
// Unix time stamp
long unixTime = System.currentTimeMillis();
String timestamp = String.valueOf(unixTime);
// Json Format
JSONObject holder = new JSONObject();
JSONObject holder_recv = new JSONObject();
JSONArray jArray = new JSONArray();
try {
holder.put("UserId", "1");
holder.put("TimeStamp", timestamp);
holder.put("SessionId", "1");
Queue<byte[]> qArray = new LinkedList<byte[]>();
qArray.add(bData);
byte[] tmparr = qArray.poll();
for (int i = 0; i < tmparr.length; i++) {
jArray.put(i, tmparr[i]);
}
System.out.println("send audio -- " + jArray);
holder.put("MMData", jArray.toString());
System.out.println("JSON -- " + holder.toString());
holder_recv.put("UserId", "1");
holder_recv.put("TimeStamp", timestamp);
holder_recv.put("SeqNo", "100");
holder_recv.put("SessionId", "0");
} catch (JSONException e1) {
e1.printStackTrace();
}
System.out.println("time " + timestamp);
try {
StringEntity se = new StringEntity(holder.toString());
StringEntity se_recv = new StringEntity(holder_recv.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
se_recv.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httppost.setEntity(se);
httppost_recv.setEntity(se_recv);
HttpResponse response = httpclient.execute(httppost);
HttpResponse response_recv = httpclient_recv
.execute(httppost_recv);
if (response_recv != null) {
t = EntityUtils.toString(response_recv.getEntity());
System.out.println("after response -- " + t);
Queue<String> qe = new LinkedList<String>();
qe.add(t);
t = null;
System.out.println("on play side ...1 ");
try {
System.out.println("on play side ...2 ");
JSONObject get = new JSONObject(qe.poll());
// JSONArray jArray_recv = get.getJSONArray("MMData");
String mmdata = (String) get.get("MMData");
JSONObject temp2 = new JSONObject("{ \"MMData\" : "
+ mmdata + "}");
JSONArray jArray_recv = temp2.getJSONArray("MMData");
System.out.println("jsonarray -- " + jArray_recv);
// String timeData = (String) get.get("TimeStamp");
String userData = (String) get.get("UserId");
// String sessionId = (String) get.get("TimeStamp");
System.out.println("on play side ...3 ");
// if (Long.valueOf(timeData) > ts)
{
// ts = Long.valueOf(timeData);
System.out.println("on play side ...4 ");
if (at != null) {
System.out.println("on play side ...5 ");
byte[] shortArray = new byte[jArray_recv
.length()];
for (int i = 0; i < jArray_recv.length(); i++) {
shortArray[i] = (byte) jArray_recv
.getInt(i);
}
jArray_recv = null;
System.out.println("recv audio -- " + br
+ " ----" + shortArray);
byte[] temp = shortArray;
shortArray = null;
byte[] bArray = temp;
temp = null;
byte[][] newbarray = new byte[5][1024];
newbarray[br - 1] = bArray;
byte[] sbayyay = new byte[1024 * 5];
System.arraycopy(bArray, 0, sbayyay,
(br - 1) * 1024, bArray.length);
if (br == 5) {
for (int i = 0; i < 5; i++) {
System.out.println("in for---" + i
+ "----" + sbayyay.length);
// System.arraycopy(newbarray[i], 0,
// sbayyay, i * 1024,
// bArray.length);
}
System.out.println("bsbsbsbs --- "
+ new String(sbayyay));
at.write(sbayyay, 0, sbayyay.length);
at.play();
}
}
else {
Log.d("Audio",
"audio track is not initialised ");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception");
e.printStackTrace();
}
bytes_count += bytes_read;
Log.d(LOG_TAG, "bytes_count : " + bytes_count);
Thread.sleep(SAMPLE_INTERVAL, 0);
} catch (InterruptedException ie) {
Log.e(LOG_TAG, "InterruptedException");
}
}
How to process Data table in android>My service return dataTable.How to handle it?
public static final String APPURL = "http://192.168.1.213:6969/MySalesServices";
private static final String METHOD_NAME = "SalesList";
private static final String NAMESPACE = "http://tempuri.org/";
private static String SOAP_ACTION = "http://tempuri.org/IMySalesServices/SalesList";
SoapPrimitive responsePrimitive = null;
ArrayList<String> tablesName = new ArrayList<String>();
public void onCreate(Bundle savedInstanceState) {
..................
}
public SoapPrimitive soapPrimitive(String METHOD_NAME, String SOAP_ACTION,String NAMESPACE, String URL) throws IOException, XmlPullParserException {
SoapPrimitive responses = null;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); // set up
request.addProperty("strExec", strExecutive);
request.addProperty("strBusinessUnit", strBusinessUnit);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // put all required data into a soap
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport httpTransport = new AndroidHttpTransport(URL);
httpTransport.debug = true;
try {
httpTransport.call(SOAP_ACTION, envelope);
responses = (SoapPrimitive) envelope.getResponse();
}catch(SocketException ex){
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return responses;
}
I got following error :
AnyType{element=anyType{complexType=anyType{choice=anyType{element=anyType{complexType=anyType{sequence=anyType{element=anyType{}; element=anyType{}; element=anyType{}; element=anyType{}; element=anyType{}; }; }; }; }; }; }; }
please help me
You return the Method type as String & concert it Datatable to Json as String that is good way to do & easy
//Converting table to json
public String ConverTableToJson(DataTable dtDownloadJson)
{
string[] StrDc = new string[dtDownloadJson.Columns.Count];
string HeadStr = string.Empty;
if (dtDownloadJson.Rows.Count > 0)
{
for (int i = 0; i < dtDownloadJson.Columns.Count; i++)
{
StrDc[i] = dtDownloadJson.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
if (HeadStr.Length > 0)
{
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dtDownloadJson.TableName + "\" : [");
for (int i = 0; i < dtDownloadJson.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dtDownloadJson.Columns.Count; j++)
{
TempStr = TempStr.Replace(dtDownloadJson.Columns[j] + j.ToString() + "¾", dtDownloadJson.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}else
{
return "0";
}
}
else
{
return "0";
}
}
The error you are getting aint an error at all. At least, thats the behavious I saw at my own application using a setup that was quite like the one you have there. Have you tried casting the response to a SoapObject? You can then call the .getPropertyCount() method on that SoapObject to start looping trough the content of the response. Quick example:
//Create a Transport object makes the webservice call
HttpTransportSE httpTrans = new HttpTransportSE(URL);
httpTrans.call(SOAP_ACTION, env);
//Cast the object to SoapObject
SoapObject storages = (SoapObject)env.getResponse();
//Loop trough the result
for(int i = 0; i < storages.getPropertyCount(); i++) {
//Get a SoapObject for each storage
SoapObject storage = (SoapObject)storages.getProperty(i);
}
Seeing the response you got, you might have to dig a few levels deep to get the data you need tho. Either 6 or 7 levels deep. If it is an option, I would change the response you get from the webservice so that it is easier to parse.
I have written Update table using dbAdapter.
public void loadDownloadData() {
SoapPrimitive responsePrimitiveData;
//Loop Table list
for (int i = 0; i < tablesName.size(); i++) {
try {
responsePrimitiveData = soapPrimitiveData(tablesName.get(i));
if (responsePrimitiveData != null) {
try {
String result = responsePrimitiveData.toString();
JSONObject jsonobject = new JSONObject(result);
JSONArray array = jsonobject.getJSONArray("Table1");
int max = array.length();
// Loop each table data
for (int j = 0; j < max; j++) {
JSONObject obj = array.getJSONObject(j);
JSONArray names = obj.names();
StringBuilder strFields = new StringBuilder();
StringBuilder strValues = new StringBuilder();
String[] strToFields = new String[names.length()];
String[] strToFieldsVal = new String[names.length()];
//getting the Json name, values in separate string array
for (int k = 0; k < names.length(); k++) {
String name = names.getString(k);
strToFields[k] = names.getString(k);
String strVal;
if(obj.getString(name)== null){
strVal="";
strToFieldsVal[k]="";
}else{
if(obj.getString(name).equals(" ")){
strVal="";
strToFieldsVal[k]="";
}else{
String tmp1 = obj.getString(name).replaceAll("\\s+", " ");
String tmp = tmp1.replaceAll("\\s+", " ");
strVal =tmp.replaceAll("\\s+", " ");
strToFieldsVal[k]=strVal;
}
}
strFields.append(name + ",");
strValues.append(strVal+",");
} //end of json for loop
strFields.deleteCharAt(strFields.length() - 1);
strValues.deleteCharAt(strValues.length() - 1);
if(getTableUpdateType(tablesName.get(i)).equals("1")){
String actualtable = getAndroidTablename(tablesName.get(i));
if(isTableRecords(tablesName.get(i))){
String[] strWhereField = getTablePrimaryKey(tablesName.get(i),strBusinessUnit);
String[] strWhereFieldVal = new String[strWhereField.length];
StringBuilder whereFields = new StringBuilder();
for (int a = 0; a < strWhereField.length; a++) {
strWhereFieldVal[a] = obj.getString(strWhereField[a]);
whereFields.append(strWhereField[a] + "= ? and ");
}
whereFields.delete(whereFields.length() - 4, whereFields.length());
updateTableRecords(actualtable, strToFields, strToFieldsVal,whereFields.toString() ,strWhereFieldVal);
}else{
insertTableRecords(actualtable, strToFields, strToFieldsVal);
}
}else if(getTableUpdateType(tablesName.get(i)).equals("2")){
}else if(getTableUpdateType(tablesName.get(i)).equals("3")){
}else{
}
}//end of each table data
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
and I called like update method:
public void updateTableRecords(String strTableName, String[] strToFields, String[] strValues,String strWhereField ,String[] strWhereFieldVal){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(DownlaodTableActivity.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
for(int i=0 ;i<strToFields.length;i++){
initialValues.put(strToFields[i],strValues[i]);
}
long n = dbAdapter.updateRecordsInDB(strTableName, initialValues, strWhereField, strWhereFieldVal);
System.out.println( " -- n--- " + n);
Toast.makeText(DownlaodTableActivity.this, n+" rows updated", Toast.LENGTH_SHORT).show();
}
I want to generate update statement dynamic way. From These code I put Where part also.But I did not generate where clause.
see :
UPDATE strTableName SET ExecutiveCode=?, FreeIssuePrefix=?, DisPaySchedulePrefix=?, NextFreeIssueNo=?, NextReturnNo=?, UploadedType=?, DisNextFOCNo=?, DisNextFreeIssueNo=?
Please help me How to give the Where clase(Here I gave String & arguments as string array)
Thanks in advance...
try like this
dbAdapter.updateRecordsInDB(strTableName, initialValues,""+whereField+"='"+whereFieldValue+"'",null);
if your whereField field's type is number then don't use ''
If you have to compare with multiple values use
String where="";
for(int i=0;i<strWhereField.length();i++)
{
where=where+whereField[i]+"='"+strWhereFieldValue[i]+"'"
if(i<(strWhereField.length()-1)) where=where+" and"
}
dbAdapter.updateRecordsInDB(strTableName, initialValues,where,null);