Post Reply

[Q] Insert multiple records using webservice in android

OP FedePrado

14th February 2014, 07:20 PM   |  #1  
OP Junior Member
Thanks Meter: 0
 
5 posts
Join Date:Joined: Feb 2014
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!

Code:
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://192.168.10.94/MensajeOperador/MensajeOperador.asmx";
 	//private final String URL = "htt p://200.76.187.148/MensajeOperador/MensajeOperador.asmx";
	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;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_actividad_llamadas_drivers);
	txtInformacion = (TextView) findViewById(R.id.textview_call);
	txtDetalles = (TextView)findViewById(R.id.textview_call2);
	
	getCallDetails();
 }
 
 // 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.
 @SuppressLint("SimpleDateFormat")
private void getCallDetails() {
	 String timestamp = String.valueOf(getTodayTimestamp());
	 StringBuffer sb = new StringBuffer();
	 @SuppressWarnings("deprecation")
	 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";
			 break;

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

		 case CallLog.Calls.MISSED_TYPE:
			 dir = "Perdida";
			 break;
		 }
		 
		 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();
		 tareaEnviarABD.execute();
		 
		 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());
		 sb.append("\n----------------------------------");
		 
	 }
	 txtDetalles.setText(sb);
 	}
 
 private class AsyncCallWS extends AsyncTask<String, Void, Void> {
	 @Override
     protected Void doInBackground(String... params) {
		 Log.i(TAG,"doInBackground");
		 InsertarLlamada(insercion);
         return null;
     }

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

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

     @Override
     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();
         
         propiedades.setName("insercion");
         propiedades.setValue(insercion);
         propiedades.setType(String.class);
         //Agregamos las propiedades
         request.addProperty(propiedades);
         //Creamos el envelope
         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                 SoapEnvelope.VER11);
         envelope.dotNet = true;
         //ponemos la salida SOAP
         envelope.setOutputSoapObject(request);
         //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:	118
Size:	38.8 KB
ID:	2579457   Click image for larger version

Name:	Captura.JPG
Views:	99
Size:	34.6 KB
ID:	2579458  
24th February 2014, 06:39 PM   |  #2  
OP Junior Member
Thanks Meter: 0
 
5 posts
Join Date:Joined: Feb 2014
Thumbs up
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.

Thanks
Post Reply Subscribe to Thread
Previous Thread Next Thread
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes


Top Threads in Java for Android App Development by ThreadRank