5,596,568 Members 40,935 Now Online
XDA Developers Android and Mobile Development Forum

[Q] Insert multiple records using webservice in android

Tip us?
Junior Member - OP
Thanks Meter 0
Posts: 5
Join Date: Feb 2014
Question [Q] Insert multiple records using webservice in android

I have been following this forum for quite a long time now, but I have not decided to publish my questions here.

Hope anyone can help me with this:

I am developing an android app that gets the calls made in a day, and I want those calls to be inserted into a SQL server table using a webservice.

I am kind of an android begginer, since I have never worked with webservices.

So far I am able to get the information of the calls and show it in the display and to insert up to 3-4 records in the database. the problem that I am facing right now is that when I get to insert more than 3 records, the webservice inserts duplicate entries and the call duration gets set to 0 in every call. For example: I have calls to the numbers 1,2,3,4 with a duration of 5 seconds each. When I invoke the webservice, it inserts the call 1,3,3,3 with duration of 0 seconds in all of the calls.

I am adding the code of my Activity and some captions of the device and the SQL server. If you need any more code, just let me know.

Thanks everyone!

package com.trucka.llamadasdrivers;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

import com.trucka.llamadasdrivers.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.TextView;
import android.telephony.*;
import android.util.Log;

import java.text.SimpleDateFormat;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

public class ActividadLlamadasDrivers extends Activity {
	TextView txtInformacion = null;
	TextView txtDetalles = null;
	TextView tv = null;
	// Comunicación con el webservice.
 	private final String NAMESPACE = "htt p://truckanet.com/MensajeOperador";
	private final String URL = "htt p://";
 	//private final String URL = "htt p://";
	private final String SOAP_ACTION = "htt p://truckanet.com/MensajeOperador/ActualizarFede";
	private final String METHOD_NAME = "ActualizarFede";
	private String TAG = "TRUCKA_DRIVERS";
	private String resultado;
	String phNumber = null;
	String callType = null;
	String callDate = null;
	DateFormat shortFecha = null;
	DateFormat shortDF = null;
	Date callDayTime = null;
	Date fin = null;
	String fechaLlamada1 = null;
	String fechaLlamada2 = null;
	String callDuration = null;
	String dir = null;
	public  String tolo = null;
	String imei = null;
	String comentario = null;
	String fechaRegistro = null;
	String insercion = null;
	String fechaInicio = null;
	String fechaFin = null;

 protected void onCreate(Bundle savedInstanceState) {
	txtInformacion = (TextView) findViewById(R.id.textview_call);
	txtDetalles = (TextView)findViewById(R.id.textview_call2);
 // Obtener la fecha actual del teléfono.
 public long getTodayTimestamp(){
	 Calendar c1 = Calendar.getInstance();
	 c1.setTime(new Date());
	 Calendar c2 = Calendar.getInstance();
	 c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
	 c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
	 c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
	 c2.set(Calendar.HOUR_OF_DAY, 0);
	 c2.set(Calendar.MINUTE, 0);
	 c2.set(Calendar.SECOND, 0);
	 return c2.getTimeInMillis();

 //Obtener el detalle de las llamadas con la fecha actual.
private void getCallDetails() {
	 String timestamp = String.valueOf(getTodayTimestamp());
	 StringBuffer sb = new StringBuffer();
	 Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, CallLog.Calls.DATE + ">= ?", new String[]{timestamp}, null);
	 int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
	 int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
	 int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
	 int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
	 sb.append("Bitácora de llamadas :");
	 Integer contador = 0;
	 while (managedCursor.moveToNext()) {
		 contador = contador + 1;
		 phNumber = managedCursor.getString(number);
		 callType = managedCursor.getString(type);
		 callDate = managedCursor.getString(date);
		 shortFecha = DateFormat.getDateInstance(DateFormat.SHORT);
		 shortDF = DateFormat.getTimeInstance(DateFormat.SHORT);
		 callDayTime = new Date(Long.valueOf(callDate));
		 fechaLlamada1 = shortDF.format(callDayTime);
		 fechaLlamada2 = shortFecha.format(callDayTime);
		 callDuration = managedCursor.getString(duration);
		 int dircode = Integer.parseInt(callType);
		 TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		 switch (dircode) {
		 case CallLog.Calls.OUTGOING_TYPE:
			 dir = "Saliente";

		 case CallLog.Calls.INCOMING_TYPE:
			 dir = "Entrante";

		 case CallLog.Calls.MISSED_TYPE:
			 dir = "Perdida";
		 imei = mngr.getDeviceId();
		 comentario = dir;
		 fechaRegistro = fechaLlamada2;
		 DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
		 String ahorita=df.format(callDayTime);
		 fechaInicio = ahorita.toString();
		 //fechaFin = df.format(callDayTime.setSeconds(callDayTime.getSeconds()+5));
		 insercion = "DECLARE @claveDriver INT, @nombreDriver VARCHAR(max), @evento VARCHAR(max), @duracion int, @inicial varchar(max) "
				 + "SET @claveDriver = (SELECT cve_tra FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '"+mngr.getDeviceId()+"') "
				 + "SET @nombreDriver = (SELECT nombre FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '"+mngr.getDeviceId()+"') "
				 + "SET @duracion = " + managedCursor.getString(duration)
				 + "SET @evento = '(LOG) Llamada " + dir + ". Duración ' + CONVERT(varchar, @duracion, 103) + ' segundos al número: " + phNumber +"' "
				 //+ "SET @duracion = " + callDuration
				 +" SET @inicial = '" + fechaInicio + "'"
				 + "INSERT INTO bitacora.dbo.registroDellamadasOperadores (fechacreacion,fecha_fin,fecha_inicio,idMobil,Tractor,Nom_tra,Cve_tra,FechaRegistro,Evento) "
				 + " VALUES('" + fechaInicio + "', DATEADD(SECOND,@duracion,@inicial),'" + fechaInicio + "','" + mngr.getDeviceId() + "','',@nombreDriver,@claveDriver,current_timestamp,@evento)";
		 AsyncCallWS tareaEnviarABD = new AsyncCallWS();
		 sb.append("\nNúmero de teléfono:--- " + phNumber + " \nTipo de llamada:--- "
				 + dir + " \nFecha de llamada:--- " + fechaLlamada2 + " " + fechaLlamada1
				 + " \nDuración en segundos:--- " + callDuration
				 + " \nDispositivo actual:--" +mngr.getDeviceId());
 private class AsyncCallWS extends AsyncTask<String, Void, Void> {
     protected Void doInBackground(String... params) {
         return null;

     protected void onPostExecute(Void result) {
         Log.i(TAG, "onPostExecute");
         txtInformacion.setText("Información enviada");

     protected void onPreExecute() {
         Log.i(TAG, "onPreExecute");
         txtInformacion.setText("Enviando información...");

     protected void onProgressUpdate(Void... values) {
         Log.i(TAG, "onProgressUpdate");
     public void InsertarLlamada(String insercion) {
         //Creamos la solicitud
         SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
         //Propiedades que contienen los valores
         PropertyInfo propiedades = new PropertyInfo();
         //Agregamos las propiedades
         //Creamos el envelope
         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
         envelope.dotNet = true;
         //ponemos la salida SOAP
         //Creamos la llamada HTTP
         HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
         try {
             //Invocamos el servicio
             androidHttpTransport.call(SOAP_ACTION, envelope);
             //Obtenemos la respuesta
             Object response = envelope.getResponse();
             //Asignamos el resultado de la consulta
             resultado = response.toString();
             } catch (Exception e) {
        	 resultado = e.getMessage();
Attached Thumbnails
Click image for larger version

Name:	Captura2.JPG
Views:	116
Size:	38.8 KB
ID:	2579457   Click image for larger version

Name:	Captura.JPG
Views:	94
Size:	34.6 KB
ID:	2579458  
Junior Member - OP
Thanks Meter 0
Posts: 5
Join Date: Feb 2014
I do not know if this is the best way to do it, but i used sql variables and only sent 2 parameters to the webservice.

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes