Why show error Cannot serialize? - android

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]);

Related

NullPointerException on getting data from database

I've made working source codes on synchronizing database before but suddenly it's not working now. Here, I'm trying to read my records in local database in the DB_User class. But it returned java.lang.NullPointerException. So this is what I made.
This is the stacktrace of my error
01-15 06:42:20.080: I/ActivityManager(60): Displayed activity com.yolanda.ta/.DBSynchronizer: 387 ms (total 387 ms)
01-15 06:42:40.639: D/dalvikvm(1147): GC_FOR_MALLOC freed 2008 objects / 125592 bytes in 74ms
01-15 06:43:21.149: D/dalvikvm(1147): GC_FOR_MALLOC freed 777 objects / 219464 bytes in 79ms
01-15 06:44:02.018: D/dalvikvm(1147): GC_FOR_MALLOC freed 830 objects / 404856 bytes in 67ms
01-15 06:44:35.578: D/dalvikvm(1147): GC_FOR_MALLOC freed 830 objects / 404976 bytes in 78ms
01-15 06:44:58.399: W/dalvikvm(1147): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
01-15 06:44:58.411: E/AndroidRuntime(1147): FATAL EXCEPTION: Thread-8
01-15 06:44:58.411: E/AndroidRuntime(1147): java.lang.NullPointerException
01-15 06:44:58.411: E/AndroidRuntime(1147): at com.yolanda.ta.ThreadUser.fetchLocal(ThreadUser.java:192)
01-15 06:44:58.411: E/AndroidRuntime(1147): at com.yolanda.ta.ThreadUser.run(ThreadUser.java:59)
01-15 06:44:58.492: W/ActivityManager(60): Force finishing activity com.yolanda.ta/.DBSynchronizer
and this is fetchLocal() to get data from database which I call it to get data from the local database
public String[] fetchLocal (int column)
{
Cursor user = mDbHelper.getAllRow3();
String Result[] = new String[user.getCount()];
user.moveToFirst();
int i = 0;
while (user.isAfterLast() == false) {
Result[i++] = user.getString(column);
user.moveToNext();
}
user.close();
return Result;
}
and this is the method of getAllRow3()
public Cursor getAllRow3()
{
Cursor c = db.query(NAMA_TABEL, new String[]{ROW_ID, ROW_NAMAL, ROW_NAMA, ROW_PW, ROW_ALAMAT, ROW_TELEPON, ROW_LEVEL, ROW_STATUS,ROW_TIME}, null, null, null, null, null, null);
return c;
}
and this is my table structure
public class DB_User {
private static final String ROW_ID = "IDUser";
private static final String ROW_NAMAL = "NamaLogin";
private static final String ROW_NAMA ="NamaUser";
private static final String ROW_PW ="PasswordUser";
private static final String ROW_ALAMAT ="AlamatUser";
private static final String ROW_TELEPON ="TeleponUser";
private static final String ROW_LEVEL ="LevelUser";
private static final String ROW_STATUS ="StatusUser";
private static final String ROW_TIME ="Waktu";
private static final String NAMA_DB = "TA";
private static final String NAMA_TABEL = "User";
private static final int DB_VERSION = 1;
private static int batas = 5;
private static final String CREATE_TABLE = "create table if not exists "+ NAMA_TABEL +" ("+ ROW_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
ROW_NAMAL +" VARCHAR not null, "+ ROW_NAMA +" VARCHAR not null, " + ROW_PW + " VARCHAR not null, " + ROW_ALAMAT + " VARCHAR not null, "
+ ROW_TELEPON + " VARCHAR, "+ ROW_LEVEL+ " VARCHAR not null, " + ROW_STATUS + " INTEGER not null, "+ROW_TIME+" LONG not null)";
I don't have any idea since the other activity can get exactly the same data using the same query while my thread can't. Any suggestion is welcome.
EDIT:
line 192: Cursor user = mDbHelper.getAllRow3();
line 59: String[] LocalRowID = fetchLocal(0);
Here is my ThreadUser codes:
public class ThreadUser extends Thread implements Runnable {
private boolean RunSync = false;
private DB_User mDbHelper;
private long sleeptime;
public void setDatabase(DB_User mDbHelper)
{
this.mDbHelper = mDbHelper;
}
public void setRun(boolean set)
{
RunSync = set;
}
public void setDelay(long delay)
{
sleeptime = delay;
}
#Override
public void run()
{
while(RunSync)
{
String[] RemoteID = fetch("http://10.0.2.2/project/User.php?ct=Sel_IDUser");
String[] RemoteNamaL = fetch("http://10.0.2.2/project/User.php?ct=Sel_NamaLogin");
String[] RemoteNama = fetch("http://10.0.2.2/project/User.php?ct=Sel_NamaUser");
String[] RemotePassword = fetch("http://10.0.2.2/project/User.php?ct=Sel_PasswordUser");
String[] RemoteAlamat = fetch("http://10.0.2.2/project/User.php?ct=Sel_AlamatUser");
String[] RemoteTelepon = fetch("http://10.0.2.2/project/User.php?ct=Sel_TeleponUser");
String[] RemoteLevel = fetch("http://10.0.2.2/project/User.php?ct=Sel_LevelUser");
String[] RemoteStatus = fetch("http://10.0.2.2/project/User.php?ct=Sel_StatusUser");
String[] RemoteTime = fetch("http://10.0.2.2/project/User.php?ct=Sel_Waktu");
//ROW_ID, ROW_NAMAL, ROW_NAMA, ROW_PW, ROW_ALAMAT, ROW_TELEPON, ROW_LEVEL, ROW_STATUS,ROW_TIME
String[] LocalRowID = fetchLocal(0);
String[] LocalNamaL = fetchLocal(1);
String[] LocalNama = fetchLocal(2);
String[] LocalPassword = fetchLocal(3);
String[] LocalAlamat = fetchLocal(4);
String[] LocalTelepon = fetchLocal(5);
String[] LocalLevel = fetchLocal(6);
String[] LocalStatus = fetchLocal(7);
String[] LocalTime = fetchLocal(8);
Calendar cal = Calendar.getInstance();;
for(int i = 1; i < RemoteID.length; i++)
{ Log.e("index remote1", Integer.toString(i));
for(int j = 0; j < LocalRowID.length; j++)
{
Log.e("indexlocal1", Integer.toString(j));
if(RemoteID[i].equalsIgnoreCase(LocalRowID[j]))
{
if(Long.parseLong(RemoteTime[i]) > Long.parseLong(LocalTime[j]))
{
// //id, namal, nama, alamat, password, telepon, level, status, time
mDbHelper.updateBaris2(Integer.parseInt(LocalRowID[j]), RemoteNamaL[i],
RemoteNama[i], RemoteAlamat[i],RemotePassword[i],
RemoteTelepon[i], RemoteLevel[i], Integer.parseInt(RemoteStatus[i]), cal.getTimeInMillis());
break;
}
else if (Long.parseLong(RemoteTime[i]) < Long.parseLong(LocalTime[j]))
{
call("http://10.0.2.2/project/User.php?ct=EDT&namal="+LongData(LocalNamaL[j].toString())+
"&nama="+LongData(LocalNama[j].toString())+"&pw="+LongData(LocalPassword[j].toString())+"&alamat="+LongData(LocalAlamat[j].toString())+
"&telepon="+LongData(LocalTelepon[j].toString())+"&level="+LongData(LocalLevel[j].toString())+"&status="+LocalStatus[j]+"&time="
+cal.getTimeInMillis()+"&id="+LocalRowID[j].toString());
break;
}
}
}
if (LocalRowID.length + 1 > RemoteID.length)
{//namal, nama, alamat, password, telepon, level, status, time
try{
call("http://10.0.2.2/project/User.php?ct=INS&namal="+LongData(LocalNamaL[LocalRowID.length-1].toString())+
"&nama="+LongData(LocalNama[LocalRowID.length-1].toString())+"&pw="+LongData(LocalPassword[LocalRowID.length-1].toString())+"&alamat="+LongData(LocalAlamat[LocalRowID.length-1].toString())+
"&telepon="+LongData(LocalTelepon[LocalRowID.length-1].toString())+"&level="+LongData(LocalLevel[LocalRowID.length-1].toString())+"&status="+LocalStatus[LocalRowID.length-1]+"&time="
+cal.getTimeInMillis());
Log.e("nambah server","voila");
break;
}
catch (Exception e){Log.e("walah",e.toString());}
}
else
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
for(int i = 0; i < LocalRowID.length-1; i++)
{ Log.e("index local2", Integer.toString(i));
if(RemoteID.length <= 1)
{
try{
call("http://10.0.2.2/project/User.php?ct=INS&namal="+LongData(LocalNamaL[i].toString())+
"&nama="+LongData(LocalNama[i].toString())+"&pw="+LongData(LocalPassword[i].toString())+"&alamat="+LongData(LocalAlamat[i].toString())+
"&telepon="+LongData(LocalTelepon[i].toString())+"&level="+LongData(LocalLevel[i].toString())+"&status="+LocalStatus[i]+"&time="
+cal.getTimeInMillis()+"&id="+LocalRowID[i].toString());
}
catch(Exception e){
Log.e("wooooy", e.toString());
}
}
for(int j = 1; j < RemoteID.length; j++)
{
Log.e("indexremote2", Integer.toString(j));
if(LocalRowID[i].equalsIgnoreCase(RemoteID[j]))
{
break;
}
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
if (RemoteID.length-1 > LocalRowID.length)
{
i-=1;
try{
mDbHelper.addRow2(RemoteNamaL[RemoteID.length-1], RemoteNama[RemoteID.length-1], RemoteAlamat[RemoteID.length-1], RemotePassword[RemoteID.length-1],
RemoteTelepon[RemoteID.length-1], RemoteLevel[RemoteID.length-1], Integer.parseInt(RemoteStatus[RemoteID.length-1]), cal.getTimeInMillis());
break;
}
catch(Exception e){
Log.e("wuuuy", e.toString());
}
}
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
try {
sleep(sleeptime);
} catch (InterruptedException e) {
break;
}
}
}
public String LongData (String Data)
{
String LongData ="";
for (int i = 0; i < Data.length(); i++)
{
if (Data.charAt(i)==' ')
{
LongData += '~';
}
else
LongData += Data.charAt(i);
}
return LongData;
}
public String[] fetchLocal (int column)
{
Cursor user = mDbHelper.getAllRow3();
String Result[] = new String[user.getCount()];
user.moveToFirst();
int i = 0;
while (user.isAfterLast() == false) {
Result[i++] = user.getString(column);
user.moveToNext();
}
user.close();
return Result;
}
public String[] fetch(String url)
{
HttpClient httpclient = new DefaultHttpClient();
HttpRequestBase httpRequest = null;
HttpResponse httpResponse = null;
InputStream inputStream = null;
String response = "";
StringBuffer buffer = new StringBuffer();
httpRequest = new HttpGet(url);
try
{
httpResponse = httpclient.execute(httpRequest);
}
catch (ClientProtocolException el)
{
el.printStackTrace();
}
catch (IOException el)
{
el.printStackTrace();
}
try
{
inputStream = httpResponse.getEntity().getContent();
}
catch (IllegalStateException el)
{
el.printStackTrace();
}
catch (IOException el)
{
el.printStackTrace();
}
byte[] data = new byte[512];
int len = 0;
try
{
while(-1 != (len = inputStream.read(data)))
{
buffer.append(new String(data,0,len));
}
}
catch (IOException el)
{
el.printStackTrace();
}
try
{
inputStream.close();
}
catch (IOException el)
{
el.printStackTrace();
}
response = buffer.toString();
StringParser parser = new StringParser();
ArrayList<Object> output = parser.Parse(response);
Object[] Output = output.toArray();
String[] content = new String[Output.length];
for (int i = 0; i < content.length; i++)
{
content[i] = Output[i].toString();
}
return content;
}
public String call(String url)
{
int BUFFER_SIZE = 2000;
InputStream in = null;
try
{
in = OpenHttpConnection(url);
}
catch (IOException el) {
el.printStackTrace();
return "Error: " + el.getMessage();
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try
{
while((charRead = isr.read(inputBuffer)) > 0)
{
String readString = String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
return "Error 02";
}
return str;
}
private InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if(!(conn instanceof HttpURLConnection)) throw new IOException("Not an Http Connection");
try
{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if(response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception e)
{
throw new IOException("Error Connecting");
}
return in;
}
}`
First of all, your code don't have code line number, so we don't know which line is "ThreadUser.java:192" and "ThreadUser.java:59".
Actually this problem may be a synchronized problem, please provide more code detail about TheadUser.java code. If so please add synchronized to method or synchronized block to solve this issue.

Android : Streaming Audio TO a URL in Android using AudioRecord

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 convert Soap Response to Multidimensional Array?

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
}
}
}

Android call WCF Service , that return DataTable

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.

Android update sqlite table

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);

Categories

Resources