//step 6
 public override void OnCreate(SQLiteDatabase db)
 {
     db.ExecSQL(CreateRegistrationTableQuery);
     db.ExecSQL(CreateFavouritesTableQuery);
 }
        public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            db.ExecSQL("DROP TABLE IF EXISTS history");

            OnCreate(db);
        }
 public override void OnCreate(SQLiteDatabase db)
 {
     db.ExecSQL(MapMarkerContract.SQL_CREATE_MARKERTABLE);
 }
Exemplo n.º 4
0
        public override void OnCreate(SQLiteDatabase db)
        {
            System.Console.WriteLine("My Create Table STM \n \n" + admin_creatTable);
            db.ExecSQL(admin_creatTable);
            db.ExecSQL(sales_person_creatTable);
            db.ExecSQL(category_creatTable);
            db.ExecSQL(product_creatTable);
            db.ExecSQL(vendor_creatTable);
            db.ExecSQL(purchase_creatTable);
            db.ExecSQL(customer_creatTable);
            db.ExecSQL(fav_creatTable);
            db.ExecSQL(product_purchase_creatTable);
            db.ExecSQL(order_creatTable);
            db.ExecSQL(product_order_creatTable);
            //insertAdmin("admin","abc");
            string insertStm = "Insert into " + admin_tablename + " values('admin', 'abc');";

            Console.WriteLine(insertStm);
            db.ExecSQL(insertStm);
        }
Exemplo n.º 5
0
 // Default function to create the database.
 public override void OnCreate(SQLiteDatabase db)
 {
     db.ExecSQL(CreateQuery);
     db.ExecSQL(Createscore);
 }
 public override void OnCreate(SQLiteDatabase db)
 {
     db.ExecSQL("CREATE TABLE " + Table + " (Id TEXT PRIMARY KEY, Nombre TEXT, PrecioC DECIMAL(5,2), " +
                " PrecioV DECIMAL(5,2), Fecha TEXT, Categoria TEXT )");
 }
Exemplo n.º 7
0
 public override void onCreate(SQLiteDatabase db) {
     mDatabase = db;
     mDatabase.ExecSQL(FTS_TABLE_CREATE);
     loadDictionary();
 }
Exemplo n.º 8
0
 public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
 {
     db.ExecSQL(Constants.DROP_TB);
     OnCreate(db);
 }
Exemplo n.º 9
0
        private void subirNotificacionAceptada()
        {
            List <int>    listaCodigoNotificacion = new List <int>();
            List <string> listaCodigoNotificador  = new List <string>();
            //List<string> motivo = new List<string>();
            List <string> listaCodigoReferencia = new List <string>();

            if (coneccionInternet.verificaConeccion(ApplicationContext))
            {
                Log.Debug(TAG, "Revisando si existen notificaciones con estado PendienteDeDistribucion at {0}.", DateTime.UtcNow);
                db = SQLiteDatabase.OpenDatabase(dbPath, null, DatabaseOpenFlags.OpenReadwrite);
                string consulta = "";
                // Se guardan los diferentes codigos de notificadores con estado notificandose pendiente de subir
                consulta = "Select CodNotificador from Notificaciones WHERE PendienteSubir='S' AND Estado='PendienteDeDistribucion'";
                ICursor cursor = db.RawQuery(consulta, null);
                if (cursor.MoveToFirst())
                {
                    do
                    {
                        listaCodigoNotificador.Add(cursor.GetString(0));
                    }while (cursor.MoveToNext());
                }
                cursor.Close();
                db.Close();

                if (listaCodigoNotificador.Count > 0)
                {
                    consulta = "";
                    foreach (var codigoNotificador in listaCodigoNotificador)
                    {
                        //tengo por notificador la lista de notificaciones en estado ResultadoEnCorreccion
                        db       = SQLiteDatabase.OpenDatabase(dbPath, null, DatabaseOpenFlags.OpenReadwrite);
                        consulta = "Select CodigoNotificacion,CodReferencia from Notificaciones WHERE PendienteSubir='S' AND Estado='PendienteDeDistribucion' AND CodNotificador='" + codigoNotificador + "'";
                        cursor   = db.RawQuery(consulta, null);

                        if (cursor.MoveToFirst())
                        {
                            Log.Debug(TAG, "Subiendo notificacion ACEPTADA at {0}.", DateTime.UtcNow);
                            do
                            {
                                //agrego los diferentes codigos de notificaciones pendientes de subir para un notificador en especifico
                                listaCodigoNotificacion.Add(Convert.ToInt32(cursor.GetString(0)));
                                //motivo.Add(cursor.GetString(1));
                                listaCodigoReferencia.Add(cursor.GetString(1));
                            }while (cursor.MoveToNext());
                        }
                        cursor.Close();
                        db.Close();

                        //
                        int counter = 0;
                        //Por cada codigo de notificacion creo un webRequest con su respectivo cuerpo de Json
                        foreach (var codigoNotificacion in listaCodigoNotificacion)
                        {
                            try
                            {
                                AprobarActa aprobarActa = new AprobarActa()
                                {
                                    Notificaciones = new List <ClassNotificaciones>()
                                    {
                                        new ClassNotificaciones()
                                        {
                                            CodNotificacion = codigoNotificacion,
                                            CodReferencia   = Convert.ToInt32(listaCodigoReferencia[counter]),
                                        }
                                    }
                                };

                                string request = @"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/ActaNotificacion/AprobarActasNotificacion";
                                string json    = Newtonsoft.Json.JsonConvert.SerializeObject(aprobarActa);
                                Console.WriteLine("Json: " + json);
                                var httpWebRequest = (HttpWebRequest)WebRequest.Create(request);
                                httpWebRequest.ContentType = "application/json";
                                httpWebRequest.Method      = "POST";

                                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                                {
                                    streamWriter.Write(json);
                                    streamWriter.Flush();
                                    streamWriter.Close();
                                }

                                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                                {
                                    var result = streamReader.ReadToEnd();
                                    Console.WriteLine("RESULTADO POST: " + result);

                                    if (result.Equals("true", StringComparison.Ordinal) || result.Equals("True", StringComparison.Ordinal))
                                    {
                                        db = SQLiteDatabase.OpenDatabase(dbPath, null, DatabaseOpenFlags.OpenReadwrite);
                                        db.ExecSQL(@"UPDATE Notificaciones SET PendienteSubir='N' WHERE CodigoNotificacion=" + codigoNotificacion + " ");
                                        db.Close();
                                    }
                                }
                                counter = counter + 1;
                            }
                            catch (Exception ex) { Console.WriteLine("Error subiendo datos para ResultadoEnCorreccion: " + ex.ToString()); }
                        }
                        listaCodigoNotificacion.Clear();
                        listaCodigoReferencia.Clear();
                    }
                }
            }
        }
Exemplo n.º 10
0
 public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
 {
     db.ExecSQL("DROP TABLE IF EXIST" + TableName);
     this.OnCreate(db);
 }
Exemplo n.º 11
0
        //========================SQLiteOpenHelper====================//

        public override void OnCreate(SQLiteDatabase db)
        {
            db.ExecSQL(SQL_CREATE_TABLE_IMAGES_INFO);
            db.ExecSQL(SQL_CREATE_TABLE_IMAGES_COORDINATES);
            db.ExecSQL(SQL_CREATE_TABLE_COMMENTS);
        }
Exemplo n.º 12
0
 public override void OnCreate(SQLiteDatabase db)
 {
     db.ExecSQL(tableCreate);
     db.ExecSQL(tableCreate1);
 }
 public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
 {
     db.ExecSQL("DROP TABLE IF EXISTS " + TaskContract.TaskEntry.TABLE_NAME);
     OnCreate(db);
 }
 public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
 {
     db.ExecSQL(MapMarkerContract.SQL_CREATE_MARKERTABLE);
 }
Exemplo n.º 15
0
 //step 7
 public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
 {
     db.ExecSQL(DeleteQuery);
     db.ExecSQL(FavoritesDeleteQuery);
 }
Exemplo n.º 16
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            RequestWindowFeature(WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.LayoutConfiguracaoSistema);

            SetResult(Result.Canceled);
            //==========================================================//
            //              CRIAR BANCO DE DADOS                        //
            //==========================================================//
            mdTemp = new BancoDados("PRINCIPAL");
            mdTemp.CreateDatabases("PRINCIPAL");
            //==========================================================//
            var toolbar = FindViewById <Toolbar>(Resource.Id.toolbar);

            SetSupportActionBar(toolbar);
            SupportActionBar.Title = "CONFIGURAÇÃO SISTEMA";
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeButtonEnabled(true);
            var relogioDigital = FindViewById <DigitalClock>(Resource.Id.digitalClock1);

            relogioDigital.Visibility = Android.Views.ViewStates.Visible;
            Validacoes.NrSegundosPeso = 1;
            Android.Support.V7.Widget.AppCompatImageButton BtnSair   = FindViewById <Android.Support.V7.Widget.AppCompatImageButton>(Resource.Id.BtnSairComunicacao);
            Android.Support.V7.Widget.AppCompatImageButton BtnSalvar = FindViewById <Android.Support.V7.Widget.AppCompatImageButton>(Resource.Id.BtnSalvarComunicacao);

            Android.Support.V7.Widget.AppCompatButton BtnliberaCalibracao = FindViewById <Android.Support.V7.Widget.AppCompatButton>(Resource.Id.btnLiberarCalibracao);


            BtnliberaCalibracao.Click += (sender, e) =>
            {
                StartActivity(typeof(ActSenhaCalibracao));


                //    Finish();
            };

            spinner         = FindViewById <Spinner>(Resource.Id.spinnernrplataformas);
            selecao         = new string[10];
            selecao[0]      = "01";
            selecao[1]      = "02";
            selecao[2]      = "03";
            selecao[3]      = "04";
            selecao[4]      = "05";
            selecao[5]      = "06";
            selecao[6]      = "07";
            selecao[7]      = "08";
            selecao[8]      = "09";
            selecao[9]      = "10";
            adapter         = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, selecao);
            spinner.Adapter = adapter;
            //================================================================================//
            //                              VALOR CADASTRADOS                                 //
            //================================================================================//
            string sLocation = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string sDB       = Path.Combine(sLocation, "PRINCIPAL");

            sqldTemp = SQLiteDatabase.OpenOrCreateDatabase(sDB, null);
            bool   bIsExists = File.Exists(sDB);
            string sSQLQuery = "";

            Android.Database.ICursor icursorTemp = null;
            sSQLQuery = "SELECT NR_SEGUNDOS_PESO " +
                        " FROM CONFIGURACAO_SISTEMA WHERE _id=1";
            icursorTemp = sqldTemp.RawQuery(sSQLQuery, null);
            int ValorCursor = icursorTemp.Count;
            int nrParcelas  = 0;

            if (ValorCursor > 0)
            {
                icursorTemp.MoveToNext();
                string TotalSegundos = icursorTemp.GetString(0);
                Validacoes.NrSegundosPeso = int.Parse(TotalSegundos);
            }
            Window.SetSoftInputMode(SoftInput.StateHidden);

            //==============================================//
            //                  BLUETOOTH                   //
            //==============================================//

            if (Validacoes.NrSegundosPeso > 0)
            {
                spinner.SetSelection(Validacoes.NrSegundosPeso);
            }
            spinner.ItemSelected += (s, e) =>
            {
                firstItem = spinner.SelectedItem.ToString();
                if (firstItem.Equals(spinner.SelectedItem.ToString()))
                {
                    Validacoes.NrSegundosPeso = int.Parse(spinner.SelectedItem.ToString());
                }
                else
                {
                    Toast.MakeText(this, "You have selected: " + e.Parent.GetItemIdAtPosition(e.Position).ToString(),
                                   ToastLength.Short).Show();
                }
            };



            // Register for broadcasts when a device is discovered

            BtnSair.Click += delegate
            {
                Finish();
            };


            BtnSalvar.Click += delegate
            {
                string DescricaoComunicao = "";



                //==============================================================================================//
                //                             VERIFICA SE JÁ EXISTE UM ENDEREÇO GRAVADO                        //
                //==============================================================================================//
                sSQLQuery = "";
                sSQLQuery = "SELECT NR_SEGUNDOS_PESO " +
                            " FROM CONFIGURACAO_SISTEMA ";

                icursorTemp = sqldTemp.RawQuery(sSQLQuery, null);
                ValorCursor = icursorTemp.Count;


                string Data = System.DateTime.Today.ToShortDateString();
                string Hora = System.DateTime.Today.ToShortTimeString();

                if (ValorCursor == 0)
                {
                    string Valores = int.Parse(spinner.SelectedItem.ToString()) - 1 + ",'" +
                                     Data + "','" +
                                     Hora + "'";
                    string Campos = "NR_SEGUNDOS_PESO," +
                                    "DATA_CADASTRO," +
                                    "HORA_CADASTRO";

                    sSQLQuery = "INSERT INTO " +
                                "CONFIGURACAO_SISTEMA " + "(" + Campos + ") " +
                                "VALUES(" + Valores + ");";
                    sqldTemp.ExecSQL(sSQLQuery);
                    sMessage = "Record is saved.";
                    Toast.MakeText(this, "REGISTRO GRAVADO COM SUCESSO", ToastLength.Long).Show();
                }
                else
                {
                    string ComandoSql = "update CONFIGURACAO_SISTEMA set " +
                                        $" NR_SEGUNDOS_PESO={int.Parse(spinner.SelectedItem.ToString()) - 1}," +
                                        $" DATA_CADASTRO='{Data}', " +
                                        $" HORA_CADASTRO='{Hora}' " +
                                        $" where _id=1  ";

                    sqldTemp.ExecSQL(ComandoSql);
                    Toast.MakeText(this, "Atualização realizada com sucesso", ToastLength.Long).Show();
                }
                Validacoes.TempoCapturaPeso = int.Parse(spinner.SelectedItem.ToString()) - 1;
            };
        }
Exemplo n.º 17
0
 public override void OnCreate(SQLiteDatabase db)
 {
     db.ExecSQL(sql: qry_create_table);
 }
Exemplo n.º 18
0
        public override void OnCreate(SQLiteDatabase db)
        {
            string query = $"CREATE TABLE {DbHelper.DB_TABLE} (ID INTEGER PRIMARY KEY AUTOINCREMENT, {DbHelper.DB_COLUMN} TEXT NOT NULL);";

            db.ExecSQL(query);
        }
Exemplo n.º 19
0
        public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            db.ExecSQL("DROP TABLE IF EXISTS " + NoteDatabaseConstants.TableName);

            OnCreate(db);
        }
Exemplo n.º 20
0
        public override void OnCreate(SQLiteDatabase db)
        {
            System.Console.WriteLine("My Create Table STM \n \n" + creatTable);

            db.ExecSQL(creatTable);
        }
Exemplo n.º 21
0
        public void updateOrderStatus(string o_id)
        {
            String updateStm = "update " + order_tablename + " set " + order_status + " = 'complete' where " + order_id + " = " + o_id + ";";

            connectionObj.ExecSQL(updateStm);
            Console.WriteLine(updateStm);
        }
Exemplo n.º 22
0
        private void findposition(int position, string locationname, string inventorytype, string id)
        {
            if (i > 0)
            {
                dialog.Dismiss();

                ISharedPreferences prefs;
                // context.StartActivity(typeof(Main));
                prefs = PreferenceManager.GetDefaultSharedPreferences(context);
                ISharedPreferencesEditor editor = prefs.Edit();

                Dialog locationeditdialog = new Dialog(context);
                dialog = new Dialog(context);

                dialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
                dialog.SetContentView(Resource.Layout.LocationEditPopUp);
                ImageView      imgCloseLocationEditPopUp = dialog.FindViewById <ImageView>(Resource.Id.imgCloseLocationEditPopUp);
                RelativeLayout rlAddLocation             = dialog.FindViewById <RelativeLayout>(Resource.Id.rlAddLocation);
                RelativeLayout rlRenameLocation          = dialog.FindViewById <RelativeLayout>(Resource.Id.rlRenameLocation);
                RelativeLayout rlDeleteLocation          = dialog.FindViewById <RelativeLayout>(Resource.Id.rlDeleteLocation);
                RelativeLayout rlDetailsLocation         = dialog.FindViewById <RelativeLayout>(Resource.Id.rlDetailsLocation);
                RelativeLayout rlListLocationItem        = dialog.FindViewById <RelativeLayout>(Resource.Id.rlListLocationItem);

                if (inventorytype.Trim() == "Manual" || inventorytype.Trim() == "Barcode")
                {
                    rlListLocationItem.Visibility = ViewStates.Visible;
                }
                else
                {
                    rlListLocationItem.Visibility = ViewStates.Gone;
                }

                imgCloseLocationEditPopUp.Click += delegate
                {
                    dialog.Dismiss();
                };


                rlAddLocation.Click += delegate
                {
                    try
                    {
                        if (inventorytype.Trim() == "Manual")
                        {
                            editor.PutLong("InventoryType", 1);
                            editor.PutString("LocationName", locationname);

                            context.StartActivity(typeof(EntryTab));
                        }
                        if (inventorytype.Trim() == "Barcode")
                        {
                            editor.PutLong("InventoryType", 3);
                            editor.PutString("LocationName", locationname);
                            context.StartActivity(typeof(EntryTab));
                        }
                        if (inventorytype.Trim() == "Voice")
                        {
                            editor.PutLong("InventoryType", 2);
                            editor.PutString("LocationName", locationname);
                            editor.PutInt("FromVoiceEdit", 1);
                            context.StartActivity(typeof(EntryTab));
                        }
                        editor.Commit();
                        // applies changes synchronously on older APIs
                        editor.Apply();
                        dialog.Dismiss();
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(context, "Something went wrong. Please try back in few minutes.", ToastLength.Short).Show();
                    }
                };

                rlListLocationItem.Click += delegate
                {
                    try
                    {
                        editor.PutString("LocationNameFromLocationList", locationname);
                        if (inventorytype.Trim() == "Manual")
                        {
                            editor.PutString("InventoryTypeFromLocationList", "1");
                        }
                        if (inventorytype.Trim() == "Barcode")
                        {
                            editor.PutString("InventoryTypeFromLocationList", "3");
                        }
                        editor.Commit();
                        // applies changes synchronously on older APIs
                        editor.Apply();
                        try
                        {
                            context.Finish();
                        }
                        catch
                        {
                        }
                        context.StartActivity(typeof(LocationListItem));
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(context, "Something went wrong. Please try back in few minutes.", ToastLength.Short).Show();
                    }
                };
                rlDeleteLocation.Click += delegate
                {
                    try
                    {
                        db = context.OpenOrCreateDatabase("ImInventory", FileCreationMode.Private, null);
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.SetMessage("Are you sure want to delete this location?");
                        builder.SetCancelable(false);
                        //builder .SetIcon (Resource.Drawable.Icon);
                        builder.SetPositiveButton("Yes", (object sender, DialogClickEventArgs e) =>
                        {
                            string locationnamefromsession = prefs.GetString("LocationName", "");
                            if (locationname.Trim() == locationnamefromsession.Trim())
                            {
                                editor.PutString("LocationName", "");
                                editor.Commit();
                                editor.Apply();
                            }
                            if (inventorytype.Trim() == "Manual")
                            {
                                try
                                {
                                    db.ExecSQL("delete from " + "tbl_Inventory where ID='" + id + "'");
                                    context.Finish();
                                    context.StartActivity(typeof(LocationList));
                                    Toast.MakeText(context, "Location deleted successfully", ToastLength.Long).Show();
                                }
                                catch
                                {
                                    // Toast.MakeText(context, "An error occured. Pls try again later", ToastLength.Long).Show();
                                }
                            }

                            if (inventorytype.Trim() == "Barcode")
                            {
                                try
                                {
                                    db.ExecSQL("delete from " + "tbl_Inventory where ID='" + id + "'");
                                    context.Finish();
                                    context.StartActivity(typeof(LocationList));
                                    Toast.MakeText(context, "Location deleted successfully", ToastLength.Long).Show();
                                }
                                catch
                                {
                                    // Toast.MakeText(context, "An error occured. Pls try again later", ToastLength.Long).Show();
                                }
                            }

                            if (inventorytype.Trim() == "Voice")
                            {
                                try
                                {
                                    db.ExecSQL("delete from " + "tbl_Inventory where ID='" + id + "'");
                                    context.Finish();
                                    context.StartActivity(typeof(LocationList));
                                    Toast.MakeText(context, "Location deleted successfully", ToastLength.Long).Show();
                                }
                                catch
                                {
                                    //Toast.MakeText(context, "An error occured. Pls try again later", ToastLength.Long).Show();
                                }
                            }
                        });

                        builder.SetNegativeButton("No", (object sender, DialogClickEventArgs e) =>
                        {
                        });
                        AlertDialog alertdialog = builder.Create();
                        alertdialog.Show();
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(context, "Something went wrong. Please try back in few minutes.", ToastLength.Short).Show();
                    }
                };

                rlRenameLocation.Click += delegate
                {
                    try
                    {
                        locationeditdialog = new Dialog(context);
                        locationeditdialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
                        locationeditdialog.SetContentView(Resource.Layout.EditLocationFromPopUp);

                        ImageView btnEditLocationFromPopUp       = locationeditdialog.FindViewById <ImageView>(Resource.Id.btnEditLocationFromPopUp);
                        EditText  txtEditPopUpLocationName       = locationeditdialog.FindViewById <EditText>(Resource.Id.txtEditPopUpLocationName);
                        ImageView btnCancelEditLocationFromPopUp = locationeditdialog.FindViewById <ImageView>(Resource.Id.btnCancelEditLocationFromPopUp);
                        Typeface  tf = Typeface.CreateFromAsset(context.Assets, "Fonts/ROBOTO-LIGHT.TTF");
                        txtEditPopUpLocationName.Typeface = tf;
                        txtEditPopUpLocationName.Invalidate();
                        txtEditPopUpLocationName.Text = locationname;
                        locationeditdialog.SetCanceledOnTouchOutside(false);
                        locationeditdialog.Show();
                        btnCancelEditLocationFromPopUp.Click += delegate
                        {
                            locationeditdialog.Dismiss();
                        };
                        btnEditLocationFromPopUp.Click += delegate
                        {
                            try
                            {
                                string updatequery = "";

                                ContentValues values = new ContentValues();
                                values.Put("Location", txtEditPopUpLocationName.Text);

                                db = context.OpenOrCreateDatabase("ImInventory", FileCreationMode.Private, null);
                                if (inventorytype.Trim() == "Manual")
                                {
                                    updatequery = "update" + " tbl_Inventory set Location='" + txtEditPopUpLocationName.Text + "'   where Location='" + locationname + "'";
                                    db.Update("tbl_Inventory", values, "ID = " + id, null);
                                    //db.ExecSQL ("update" + " tbl_Inventory set Location='" + txtEditPopUpLocationName.Text + "' where ID = " + id);
                                }
                                if (inventorytype.Trim() == "Barcode")
                                {
                                    //updatequery = "update" + " tbl_Inventory set Location='" + txtEditPopUpLocationName.Text + "' where Location='" + locationname + "'";
                                    db.Update("tbl_Inventory", values, "ID = " + id, null);
                                    //db.ExecSQL ("update" + " tbl_Inventory set Location='" + txtEditPopUpLocationName.Text + "' where ID = " + id);
                                }
                                if (inventorytype.Trim() == "Voice")
                                {
                                    //db.Update("tbl_Inventory",values,"ID = " + id,null);
                                    //db.ExecSQL ("update" + " tbl_Inventory set Location='" + txtEditPopUpLocationName.Text + "' where ID = " + id);
                                }
                                context.Finish();
                                context.StartActivity(typeof(LocationList));
                                Toast.MakeText(context, "Location updated successfully", ToastLength.Long).Show();
                            }
                            catch (Exception ex)
                            {
                                Toast.MakeText(context, "Location updation failed", ToastLength.Long).Show();
                            }
                        };
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(context, "Something went wrong. Please try back in few minutes.", ToastLength.Short).Show();
                    }
                };

                rlDetailsLocation.Click += delegate
                {
                    try
                    {
                        db = context.OpenOrCreateDatabase("ImInventory", FileCreationMode.Private, null);
                        int     manualcount  = 0;
                        int     voicecount   = 0;
                        int     barcodecount = 0;
                        ICursor c1           = db.RawQuery("SELECT * FROM " + "tbl_Inventory Where InventoryType=1 AND Location='" + locationname + "'", null);
                        manualcount = c1.Count;



                        c1           = db.RawQuery("SELECT * FROM " + "tbl_Inventory Where InventoryType=3 AND Location='" + locationname + "'", null);
                        barcodecount = c1.Count;

                        c1         = db.RawQuery("SELECT * FROM " + "tbl_Inventory Where InventoryType=2 AND Location='" + locationname + "'", null);
                        voicecount = c1.Count;

                        Dialog locationdetailsdialog = new Dialog(context);
                        locationdetailsdialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
                        locationdetailsdialog.SetContentView(Resource.Layout.LocationDetails);

                        TextView txtManualEntryCount  = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtManualEntryCount);
                        TextView txtVoiceLength       = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtVoiceLength);
                        TextView txtBarcodeEntryCount = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtBarcodeEntryCount);

                        TextView  txtManualEntryCountText    = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtManualEntryCountText);
                        TextView  txtVoiceLengthText         = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtVoiceLengthText);
                        TextView  txtBarcodeEntryCountText   = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtBarcodeEntryCountText);
                        ImageView imgCloseLocationCountPopUp = locationdetailsdialog.FindViewById <ImageView>(Resource.Id.imgCloseLocationCountPopUp);
                        imgCloseLocationCountPopUp.Click += delegate
                        {
                            locationdetailsdialog.Dismiss();
                        };
                        string audiopath     = CreateDirectoryForAudio();
                        String duration      = "";
                        Int32  totalduration = 0;
                        string timeduration  = "";
                        int    hourcount     = 0;
                        int    mincount      = 0;
                        int    seccount      = 0;
                        string hour          = "";
                        string min           = "";
                        string sec           = "";

                        c1.MoveToFirst();
                        if (voicecount > 0)
                        {
                            //locationnamecolumn = c1.GetColumnIndex("Location");
                            //addeddate = c1.GetColumnIndex("Addeddate");
                            int voicecolumn = c1.GetColumnIndex("AudioFileName");

                            do
                            {
                                String AudioFileName = c1.GetString(voicecolumn);
                                if (AudioFileName != "")
                                {
                                    if (AudioFileName.Contains("|"))
                                    {
                                        string[] ArrAudioFileName = AudioFileName.Split('|');
                                        foreach (var item in ArrAudioFileName)
                                        {
                                            if (item.ToString() != "")
                                            {
                                                string AudioFilePath = "";
                                                AudioFilePath = audiopath + "/" + item.ToString();
                                                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                                                mmr.SetDataSource(AudioFilePath);
                                                duration      = mmr.ExtractMetadata(MetadataKey.Duration);
                                                totalduration = totalduration + Convert.ToInt32(duration);
                                                TimeSpan ts = new TimeSpan(0, 0, 0, 0, Convert.ToInt32(duration));
                                                ts        = TimeSpan.FromMilliseconds(Convert.ToDouble(totalduration));
                                                hourcount = hourcount + ts.Hours;
                                                mincount  = mincount + ts.Minutes;
                                                seccount  = seccount + ts.Seconds;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                                        mmr.SetDataSource(audiopath + "/" + AudioFileName);
                                        duration      = mmr.ExtractMetadata(MetadataKey.Duration);
                                        totalduration = totalduration + Convert.ToInt32(duration);
                                        TimeSpan ts = new TimeSpan(0, 0, 0, 0, Convert.ToInt32(duration));
                                        ts        = TimeSpan.FromMilliseconds(Convert.ToDouble(totalduration));
                                        hourcount = hourcount + ts.Hours;
                                        mincount  = mincount + ts.Minutes;
                                        seccount  = seccount + ts.Seconds;
                                    }
                                }

                                //mmr.SetDataSource(
                            }while (c1.MoveToNext());
                        }

                        if (hourcount < 10)
                        {
                            hour = "0" + hourcount.ToString();
                        }
                        else
                        {
                            hour = hourcount.ToString();
                        }

                        if (mincount < 10)
                        {
                            min = "0" + mincount.ToString();
                        }
                        else
                        {
                            min = mincount.ToString();
                        }

                        if (seccount < 10)
                        {
                            sec = "0" + seccount.ToString();
                        }
                        else
                        {
                            sec = seccount.ToString();
                        }
                        timeduration = string.Format("{0}:{1}:{2}", hour, min, sec);


                        Typeface tf = Typeface.CreateFromAsset(context.Assets, "Fonts/ROBOTO-LIGHT.TTF");
                        txtBarcodeEntryCount.Typeface = tf;
                        txtBarcodeEntryCount.Invalidate();
                        txtManualEntryCount.Text = manualcount.ToString();;

                        txtVoiceLength.Typeface = tf;
                        txtVoiceLength.Invalidate();
                        txtVoiceLength.Text = timeduration;

                        txtBarcodeEntryCount.Typeface = tf;
                        txtBarcodeEntryCount.Invalidate();
                        txtBarcodeEntryCount.Text = barcodecount.ToString();


                        txtManualEntryCountText.Typeface = tf;
                        txtManualEntryCountText.Invalidate();

                        txtVoiceLengthText.Typeface = tf;
                        txtVoiceLengthText.Invalidate();

                        txtBarcodeEntryCountText.Typeface = tf;
                        txtBarcodeEntryCountText.Invalidate();
                        locationdetailsdialog.SetCanceledOnTouchOutside(false);

                        locationdetailsdialog.Show();
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(context, "Something went wrong. Please try back in few minutes.", ToastLength.Short).Show();
                    }
                };
                dialog.SetCanceledOnTouchOutside(false);
                dialog.Show();
                i = i + 1;
            }
            else
            {
                ISharedPreferences prefs;
                // context.StartActivity(typeof(Main));
                prefs = PreferenceManager.GetDefaultSharedPreferences(context);
                ISharedPreferencesEditor editor = prefs.Edit();

                Dialog locationeditdialog = new Dialog(context);
                dialog = new Dialog(context);

                dialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
                dialog.SetContentView(Resource.Layout.LocationEditPopUp);
                ImageView      imgCloseLocationEditPopUp = dialog.FindViewById <ImageView>(Resource.Id.imgCloseLocationEditPopUp);
                RelativeLayout rlAddLocation             = dialog.FindViewById <RelativeLayout>(Resource.Id.rlAddLocation);
                RelativeLayout rlRenameLocation          = dialog.FindViewById <RelativeLayout>(Resource.Id.rlRenameLocation);
                RelativeLayout rlDeleteLocation          = dialog.FindViewById <RelativeLayout>(Resource.Id.rlDeleteLocation);
                RelativeLayout rlDetailsLocation         = dialog.FindViewById <RelativeLayout>(Resource.Id.rlDetailsLocation);
                RelativeLayout rlListLocationItem        = dialog.FindViewById <RelativeLayout>(Resource.Id.rlListLocationItem);

                if (inventorytype.Trim() == "Manual" || inventorytype.Trim() == "Barcode")
                {
                    rlListLocationItem.Visibility = ViewStates.Visible;
                }
                else
                {
                    rlListLocationItem.Visibility = ViewStates.Gone;
                }
                imgCloseLocationEditPopUp.Click += delegate
                {
                    dialog.Dismiss();
                };
                rlListLocationItem.Click += delegate
                {
                    try
                    {
                        editor.PutString("LocationNameFromLocationList", locationname);
                        if (inventorytype.Trim() == "Manual")
                        {
                            editor.PutString("InventoryTypeFromLocationList", "1");
                        }
                        if (inventorytype.Trim() == "Barcode")
                        {
                            editor.PutString("InventoryTypeFromLocationList", "3");
                        }
                        editor.Commit();
                        // applies changes synchronously on older APIs
                        editor.Apply();


                        try
                        {
                            context.Finish();
                        }
                        catch
                        {
                        }

                        context.StartActivity(typeof(LocationListItem));
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(context, "Something went wrong. Please try back in few minutes.", ToastLength.Short).Show();
                    }
                };
                rlAddLocation.Click += delegate
                {
                    try
                    {
                        if (inventorytype.Trim() == "Manual")
                        {
                            editor.PutLong("InventoryType", 1);
                            editor.PutString("LocationName", locationname);
                            context.StartActivity(typeof(EntryTab));
                        }
                        if (inventorytype.Trim() == "Barcode")
                        {
                            editor.PutLong("InventoryType", 3);
                            editor.PutString("LocationName", locationname);
                            context.StartActivity(typeof(EntryTab));
                        }
                        if (inventorytype.Trim() == "Voice")
                        {
                            editor.PutLong("InventoryType", 2);
                            editor.PutString("LocationName", locationname);
                            editor.PutInt("FromVoiceEdit", 1);
                            context.StartActivity(typeof(EntryTab));
                        }
                        editor.Commit();
                        // applies changes synchronously on older APIs
                        editor.Apply();
                        dialog.Dismiss();
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(context, "Something went wrong. Please try back in few minutes.", ToastLength.Short).Show();
                    }
                };
                rlDeleteLocation.Click += delegate
                {
                    try
                    {
                        db = context.OpenOrCreateDatabase("ImInventory", FileCreationMode.Private, null);
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.SetMessage("Are you sure want to delete this location?");
                        builder.SetCancelable(false);
                        //builder .SetIcon (Resource.Drawable.Icon);
                        builder.SetPositiveButton("Yes", (object sender, DialogClickEventArgs e) =>
                        {
                            if (inventorytype.Trim() == "Manual")
                            {
                                try
                                {
                                    db.ExecSQL("delete from " + "tbl_Inventory where ID='" + id + "'");
                                    context.Finish();
                                    context.StartActivity(typeof(LocationList));
                                    Toast.MakeText(context, "Location deleted successfully", ToastLength.Long).Show();
                                }
                                catch
                                {
                                    // Toast.MakeText(context, "An error occured. Pls try again later", ToastLength.Long).Show();
                                }
                            }

                            if (inventorytype.Trim() == "Barcode")
                            {
                                try
                                {
                                    db.ExecSQL("delete from " + "tbl_Inventory where ID='" + id + "'");
                                    context.Finish();
                                    context.StartActivity(typeof(LocationList));
                                    Toast.MakeText(context, "Location deleted successfully", ToastLength.Long).Show();
                                }
                                catch
                                {
                                    // Toast.MakeText(context, "An error occured. Pls try again later", ToastLength.Long).Show();
                                }
                            }

                            if (inventorytype.Trim() == "Voice")
                            {
                                try
                                {
                                    db.ExecSQL("delete from " + "tbl_Inventory where ID='" + id + "'");
                                    context.Finish();
                                    context.StartActivity(typeof(LocationList));
                                    Toast.MakeText(context, "Location deleted successfully", ToastLength.Long).Show();
                                }
                                catch
                                {
                                    //Toast.MakeText(context, "An error occured. Pls try again later", ToastLength.Long).Show();
                                }
                            }
                        });

                        builder.SetNegativeButton("No", (object sender, DialogClickEventArgs e) =>
                        {
                        });
                        AlertDialog alertdialog = builder.Create();
                        alertdialog.Show();
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(context, "Something went wrong. Please try back in few minutes.", ToastLength.Short).Show();
                    }
                };

                rlRenameLocation.Click += delegate
                {
                    try
                    {
                        locationeditdialog = new Dialog(context);
                        locationeditdialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
                        locationeditdialog.SetContentView(Resource.Layout.EditLocationFromPopUp);
                        ImageView btnEditLocationFromPopUp       = locationeditdialog.FindViewById <ImageView>(Resource.Id.btnEditLocationFromPopUp);
                        EditText  txtEditPopUpLocationName       = locationeditdialog.FindViewById <EditText>(Resource.Id.txtEditPopUpLocationName);
                        ImageView btnCancelEditLocationFromPopUp = locationeditdialog.FindViewById <ImageView>(Resource.Id.btnCancelEditLocationFromPopUp);
                        Typeface  tf = Typeface.CreateFromAsset(context.Assets, "Fonts/ROBOTO-LIGHT.TTF");
                        txtEditPopUpLocationName.Typeface = tf;
                        txtEditPopUpLocationName.Invalidate();
                        txtEditPopUpLocationName.Text = locationname;
                        locationeditdialog.Show();

                        btnCancelEditLocationFromPopUp.Click += delegate
                        {
                            locationeditdialog.Dismiss();
                        };
                        btnEditLocationFromPopUp.Click += delegate
                        {
                            try
                            {
                                string updatequery = "";

                                ContentValues values = new ContentValues();
                                values.Put("Location", locationname);

                                db = context.OpenOrCreateDatabase("ImInventory", FileCreationMode.Private, null);
                                if (inventorytype.Trim() == "Manual")
                                {
                                    updatequery = "update" + " tbl_Inventory set Location='" + txtEditPopUpLocationName.Text + "'   where Location='" + locationname + "'";

                                    db.ExecSQL("update" + " tbl_Inventory set Location='" + txtEditPopUpLocationName.Text + "' where ID = " + id);
                                }
                                if (inventorytype.Trim() == "Barcode")
                                {
                                    updatequery = "update" + " tbl_Inventory set Location='" + txtEditPopUpLocationName.Text + "' where Location='" + locationname + "'";

                                    db.ExecSQL("update" + " tbl_Inventory set Location='" + txtEditPopUpLocationName.Text + "' where ID = " + id);
                                }
                                if (inventorytype.Trim() == "Voice")
                                {
                                    db.ExecSQL("update" + " tbl_Inventory set Location='" + txtEditPopUpLocationName.Text + "' where ID = " + id);
                                }
                                context.Finish();
                                context.StartActivity(typeof(LocationList));
                                Toast.MakeText(context, "Location updated successfully", ToastLength.Long).Show();
                            }
                            catch (Exception ex)
                            {
                                Toast.MakeText(context, "Location updation failed", ToastLength.Long).Show();
                            }
                        };
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(context, "Something went wrong. Please try back in few minutes.", ToastLength.Short).Show();
                    }
                };

                rlDetailsLocation.Click += delegate
                {
                    try
                    {
                        db = context.OpenOrCreateDatabase("ImInventory", FileCreationMode.Private, null);
                        int     manualcount  = 0;
                        int     voicecount   = 0;
                        int     barcodecount = 0;
                        ICursor c1           = db.RawQuery("SELECT * FROM " + "tbl_Inventory Where InventoryType=1 AND Location='" + locationname + "'", null);
                        manualcount = c1.Count;


                        c1           = db.RawQuery("SELECT * FROM " + "tbl_Inventory Where InventoryType=3 AND Location='" + locationname + "'", null);
                        barcodecount = c1.Count;

                        c1         = db.RawQuery("SELECT * FROM " + "tbl_Inventory Where InventoryType=2 AND Location='" + locationname + "'", null);
                        voicecount = c1.Count;

                        Dialog locationdetailsdialog = new Dialog(context);
                        locationdetailsdialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
                        locationdetailsdialog.SetContentView(Resource.Layout.LocationDetails);
                        TextView txtManualEntryCount  = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtManualEntryCount);
                        TextView txtVoiceLength       = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtVoiceLength);
                        TextView txtBarcodeEntryCount = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtBarcodeEntryCount);

                        TextView txtManualEntryCountText  = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtManualEntryCountText);
                        TextView txtVoiceLengthText       = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtVoiceLengthText);
                        TextView txtBarcodeEntryCountText = locationdetailsdialog.FindViewById <TextView>(Resource.Id.txtBarcodeEntryCountText);

                        ImageView imgCloseLocationCountPopUp = locationdetailsdialog.FindViewById <ImageView>(Resource.Id.imgCloseLocationCountPopUp);
                        imgCloseLocationCountPopUp.Click += delegate
                        {
                            locationdetailsdialog.Dismiss();
                        };
                        string audiopath     = CreateDirectoryForAudio();
                        String duration      = "";
                        Int32  totalduration = 0;
                        string timeduration  = "";

                        int    hourcount = 0;
                        int    mincount  = 0;
                        int    seccount  = 0;
                        string hour      = "";
                        string min       = "";
                        string sec       = "";
                        c1.MoveToFirst();
                        if (voicecount > 0)
                        {
                            //locationnamecolumn = c1.GetColumnIndex("Location");
                            //addeddate = c1.GetColumnIndex("Addeddate");
                            int voicecolumn = c1.GetColumnIndex("AudioFileName");

                            do
                            {
                                String AudioFileName = c1.GetString(voicecolumn);
                                if (AudioFileName != "")
                                {
                                    if (AudioFileName.Contains("|"))
                                    {
                                        string[] ArrAudioFileName = AudioFileName.Split('|');
                                        foreach (var item in ArrAudioFileName)
                                        {
                                            if (item.ToString() != "")
                                            {
                                                string AudioFilePath = "";
                                                AudioFilePath = audiopath + "/" + item.ToString();
                                                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                                                mmr.SetDataSource(AudioFilePath);
                                                duration      = mmr.ExtractMetadata(MetadataKey.Duration);
                                                totalduration = totalduration + Convert.ToInt32(duration);
                                                TimeSpan ts = new TimeSpan(0, 0, 0, 0, Convert.ToInt32(duration));
                                                ts        = TimeSpan.FromMilliseconds(Convert.ToDouble(totalduration));
                                                hourcount = hourcount + ts.Hours;
                                                mincount  = mincount + ts.Minutes;
                                                seccount  = seccount + ts.Seconds;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                                        mmr.SetDataSource(audiopath + "/" + AudioFileName);
                                        duration      = mmr.ExtractMetadata(MetadataKey.Duration);
                                        totalduration = totalduration + Convert.ToInt32(duration);
                                        TimeSpan ts = new TimeSpan(0, 0, 0, 0, Convert.ToInt32(duration));
                                        ts        = TimeSpan.FromMilliseconds(Convert.ToDouble(totalduration));
                                        hourcount = hourcount + ts.Hours;
                                        mincount  = mincount + ts.Minutes;
                                        seccount  = seccount + ts.Seconds;
                                    }
                                }
                                //mmr.SetDataSource(
                            }while (c1.MoveToNext());
                        }
                        if (hourcount < 10)
                        {
                            hour = "0" + hourcount.ToString();
                        }
                        else
                        {
                            hour = hourcount.ToString();
                        }

                        if (mincount < 10)
                        {
                            min = "0" + mincount.ToString();
                        }
                        else
                        {
                            min = mincount.ToString();
                        }

                        if (seccount < 10)
                        {
                            sec = "0" + seccount.ToString();
                        }
                        else
                        {
                            sec = seccount.ToString();
                        }
                        timeduration = string.Format("{0}:{1}:{2}", hour, min, sec);
                        Typeface tf = Typeface.CreateFromAsset(context.Assets, "Fonts/ROBOTO-LIGHT.TTF");
                        txtBarcodeEntryCount.Typeface = tf;
                        txtBarcodeEntryCount.Invalidate();
                        txtManualEntryCount.Text = manualcount.ToString();;

                        txtVoiceLength.Typeface = tf;
                        txtVoiceLength.Invalidate();
                        txtVoiceLength.Text = timeduration;

                        txtBarcodeEntryCount.Typeface = tf;
                        txtBarcodeEntryCount.Invalidate();
                        txtBarcodeEntryCount.Text = barcodecount.ToString();


                        txtManualEntryCountText.Typeface = tf;
                        txtManualEntryCountText.Invalidate();

                        txtVoiceLengthText.Typeface = tf;
                        txtVoiceLengthText.Invalidate();

                        txtBarcodeEntryCountText.Typeface = tf;
                        txtBarcodeEntryCountText.Invalidate();


                        locationdetailsdialog.SetCanceledOnTouchOutside(false);

                        locationdetailsdialog.Show();
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(context, "Something went wrong. Please try back in few minutes.", ToastLength.Short).Show();
                    }
                };
                dialog.SetCanceledOnTouchOutside(false);
                dialog.Show();
                i = i + 1;
            }
        }
Exemplo n.º 23
0
        //Cria um novo banco de dados cujo nome é dado pelo parâmetro
        public void CriarDatabase(string sqldb_nome)
        {
            try
            {
                sqldb_mensagem = "";
                string sqldb_location = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                string sqldb_path     = Path.Combine(sqldb_location, sqldb_nome);
                bool   sqldb_exists   = File.Exists(sqldb_path);
                if (!sqldb_exists)
                {
                    sqldb       = SQLiteDatabase.OpenOrCreateDatabase(sqldb_path, null);
                    sqldb_query = "CREATE TABLE IF NOT EXISTS Users (Username VARCHAR PRIMARY KEY, Password VARCHAR, FullName VARCHAR);";
                    sqldb.ExecSQL(sqldb_query);
                    sqldb_mensagem = "Banco de dados '" + sqldb_nome + "' criado com sucesso!";
                }
                else
                {
                    sqldb          = SQLiteDatabase.OpenDatabase(sqldb_path, null, DatabaseOpenFlags.OpenReadwrite);
                    sqldb_mensagem = "Banco de dados '" + sqldb_nome + "' carregado com sucesso!";
                }
                sqldb_dispoTalhao = true;
            }
            catch (SQLiteException ex)
            {
                sqldb_mensagem = ex.Message;
            }

            if (sqldb_nome == "perfil")
            {
                try
                {
                    sqldb_mensagem = "";
                    string sqldb_location = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    string sqldb_path     = Path.Combine(sqldb_location, sqldb_nome);
                    bool   sqldb_exists   = File.Exists(sqldb_path);

                    if (true)
                    {
                        sqldb       = SQLiteDatabase.OpenOrCreateDatabase(sqldb_path, null);
                        sqldb_query = "CREATE TABLE IF NOT EXISTS perfil (_ID INTEGER PRIMARY KEY AUTOINCREMENT, paciente VARCHAR, responsavel VARCHAR);";
                        sqldb.ExecSQL(sqldb_query);
                        sqldb_mensagem = "Banco de dados '" + sqldb_nome + "' criado com sucesso!";
                        //sqldb_query = "INSERT INTO perfil (paciente,responsavel) VALUES('POC','POC')";
                        //sqldb.ExecSQL(sqldb_query);
                    }
                    else
                    {
                        sqldb          = SQLiteDatabase.OpenDatabase(sqldb_path, null, DatabaseOpenFlags.OpenReadwrite);
                        sqldb_mensagem = "Banco de dados '" + sqldb_nome + "' carregado com sucesso!";
                        sqldb_query    = "SELECT * FROM dual where 1 = 0";
                        sqldb.ExecSQL(sqldb_query);
                    }
                    sqldb_dispoTalhao = true;
                }
                catch (SQLiteException ex)
                {
                    sqldb_mensagem = ex.Message;
                }
            }
            else if (sqldb_nome == "remedio")
            {
                try
                {
                    sqldb_mensagem = "";
                    string sqldb_location = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    string sqldb_path     = Path.Combine(sqldb_location, sqldb_nome);
                    bool   sqldb_exists   = File.Exists(sqldb_path);

                    if (true)
                    {
                        sqldb       = SQLiteDatabase.OpenOrCreateDatabase(sqldb_path, null);
                        sqldb_query = "CREATE TABLE IF NOT EXISTS remedio (_ID INTEGER PRIMARY KEY AUTOINCREMENT, data VARCHAR);";
                        sqldb.ExecSQL(sqldb_query);
                        sqldb_mensagem = "Banco de dados '" + sqldb_nome + "' criado com sucesso!";
                        //sqldb_query = "INSERT INTO remedio (data) VALUES('POC')";
                        //sqldb.ExecSQL(sqldb_query);
                    }
                    else
                    {
                        sqldb          = SQLiteDatabase.OpenDatabase(sqldb_path, null, DatabaseOpenFlags.OpenReadwrite);
                        sqldb_mensagem = "Banco de dados '" + sqldb_nome + "' carregado com sucesso!";
                        sqldb_query    = "SELECT * FROM dual where 1 = 0";
                        sqldb.ExecSQL(sqldb_query);
                    }
                    sqldb_dispoTalhao = true;
                }
                catch (SQLiteException ex)
                {
                    sqldb_mensagem = ex.Message;
                }
            }
        }
Exemplo n.º 24
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            RequestWindowFeature(WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.layoutConfiguraComunicacao);


            SetResult(Result.Canceled);
            //==========================================================//
            //              CRIAR BANCO DE DADOS                        //
            //==========================================================//
            mdTemp = new BancoDados("PRINCIPAL");
            mdTemp.CreateDatabases("PRINCIPAL");
            //==========================================================//
            var toolbar = FindViewById <Toolbar>(Resource.Id.toolbar);

            SetSupportActionBar(toolbar);
            SupportActionBar.Title = "CONFIGURAÇÃO COMUNICAÇÃO PLATAFORMAS";
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeButtonEnabled(true);
            var relogioDigital = FindViewById <DigitalClock>(Resource.Id.digitalClock1);

            relogioDigital.Visibility = Android.Views.ViewStates.Visible;
            TextView textIpHeard      = FindViewById <TextView>(Resource.Id.textIpHeard);
            EditText TextIp           = FindViewById <EditText>(Resource.Id.TextIpConfigura);
            TextView textPortaHeard   = FindViewById <TextView>(Resource.Id.textPortaHeard);
            EditText TextPorta        = FindViewById <EditText>(Resource.Id.TextPortaComunicacao);
            EditText TextSenha        = FindViewById <EditText>(Resource.Id.TextSenhaComunicacao);
            TextView TextHeadBlutooth = FindViewById <TextView>(Resource.Id.textHeaderBluetooth);

            TextBluetooth      = FindViewById <EditText>(Resource.Id.BluetoothConfigura);
            TextBluetooth.Text = Intent.GetStringExtra("nome");


            RadioButton RdnWifi      = FindViewById <RadioButton>(Resource.Id.RdnWifi);
            RadioButton RdnBluetooth = FindViewById <RadioButton>(Resource.Id.RdnBluetooth);

            Android.Support.V7.Widget.AppCompatImageButton BtnSair            = FindViewById <Android.Support.V7.Widget.AppCompatImageButton>(Resource.Id.BtnSairComunicacao);
            Android.Support.V7.Widget.AppCompatImageButton BtnSalvar          = FindViewById <Android.Support.V7.Widget.AppCompatImageButton>(Resource.Id.BtnSalvarComunicacao);
            Android.Support.V7.Widget.AppCompatButton      BtnTestarBluetooth = FindViewById <Android.Support.V7.Widget.AppCompatButton>(Resource.Id.btnTestarBluetooth);
            Android.Support.V7.Widget.AppCompatButton      BtnPesquisar       = FindViewById <Android.Support.V7.Widget.AppCompatButton>(Resource.Id.btnPequisaBluetooth);
            StringBuilder        outStringBuffer;
            BluetoothAdapter     bluetoothAdapter  = null;
            BluetoothChatService ServiceConnection = null;

            spinner         = FindViewById <Spinner>(Resource.Id.spinnernrplataformas);
            selecao         = new string[6];
            selecao[0]      = "01";
            selecao[1]      = "02";
            selecao[2]      = "03";
            selecao[3]      = "04";
            selecao[4]      = "05";
            selecao[5]      = "06";
            adapter         = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, selecao);
            spinner.Adapter = adapter;
            //================================================================================//
            //                              VALOR CADASTRADOS                                 //
            //================================================================================//
            string sLocation = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string sDB       = Path.Combine(sLocation, "PRINCIPAL");

            sqldTemp = SQLiteDatabase.OpenOrCreateDatabase(sDB, null);
            bool   bIsExists = File.Exists(sDB);
            string sSQLQuery = "";

            Android.Database.ICursor icursorTemp = null;
            sSQLQuery = "SELECT NR_PLATAFORMAS," +
                        " DESCRICAO_TIPO_CONEXAO, " +
                        " ENDERECO_IP, " +
                        " PORTA, " +
                        " BLUETOOTH " +
                        " FROM CONEXAO_PLATAFORMA WHERE _id=1";
            icursorTemp = sqldTemp.RawQuery(sSQLQuery, null);
            int ValorCursor = icursorTemp.Count;
            int nrParcelas  = 0;

            if (ValorCursor > 0)
            {
                icursorTemp.MoveToNext();
                if (icursorTemp.GetString(1) == "WIFI")
                {
                    RdnWifi.Checked = true;
                }
                else
                {
                    RdnBluetooth.Checked = true;
                }

                TextIp.Text    = icursorTemp.GetString(2);
                TextPorta.Text = icursorTemp.GetString(3);
                if (TextBluetooth.Text == "")
                {
                    TextBluetooth.Text = icursorTemp.GetString(4);
                }
                Validacoes.NrPlataformas = int.Parse(icursorTemp.GetString(0));
            }
            else
            {
                RdnBluetooth.Checked = true;
            }
            if (RdnWifi.Checked == true && Validacoes.ConexaoWifiBluetooth != true)
            {
                TextHeadBlutooth.Visibility = ViewStates.Invisible;
                TextBluetooth.Visibility    = ViewStates.Invisible;
                BtnPesquisar.Visibility     = ViewStates.Invisible;
            }
            if (RdnBluetooth.Checked == true || Validacoes.ConexaoWifiBluetooth == true)
            {
                textIpHeard.Visibility    = ViewStates.Invisible;
                TextIp.Visibility         = ViewStates.Invisible;
                textPortaHeard.Visibility = ViewStates.Invisible;
                TextPorta.Visibility      = ViewStates.Invisible;
                RdnBluetooth.Checked      = true;
            }
            TextBluetooth.InputType = 0;
            RdnWifi.Click          += RadioButtonBluetooth;
            RdnBluetooth.Click     += RadioButtonWifi;
            Window.SetSoftInputMode(SoftInput.StateHidden);

            //==============================================//
            //                  BLUETOOTH                   //
            //==============================================//

            var scanButton = FindViewById <Button>(Resource.Id.btnPequisaBluetooth);

            if (Validacoes.NrPlataformas > 0)
            {
                spinner.SetSelection(Validacoes.NrPlataformas);
            }
            spinner.ItemSelected += (s, e) =>
            {
                firstItem = spinner.SelectedItem.ToString();
                if (firstItem.Equals(spinner.SelectedItem.ToString()))
                {
                    Validacoes.NrPlataformas = int.Parse(spinner.SelectedItem.ToString()) - 1;
                }
                else
                {
                    Toast.MakeText(this, "You have selected: " + e.Parent.GetItemIdAtPosition(e.Position).ToString(),
                                   ToastLength.Short).Show();
                }
            };



            scanButton.Click += (sender, e) =>
            {
                StartActivity(typeof(DeviceListActivity));
                RdnBluetooth.Checked         = true;
                textIpHeard.Visibility       = ViewStates.Invisible;
                TextIp.Visibility            = ViewStates.Invisible;
                textPortaHeard.Visibility    = ViewStates.Invisible;
                TextPorta.Visibility         = ViewStates.Invisible;
                Validacoes.DeviceListPrinter = false;

                Finish();
            };

            // Register for broadcasts when a device is discovered

            BtnSair.Click += delegate
            {
                Finish();
            };

            BtnTestarBluetooth.Click += delegate
            {
                BluetoothAdapter adaptador = BluetoothAdapter.DefaultAdapter; // procura o adap. bluetooth
                ICollection <BluetoothDevice> aparelhos = adaptador.BondedDevices;
                BluetoothDevice[]             apa       = new BluetoothDevice[aparelhos.Count];
                ParcelUuid[]      chaves;
                BluetoothSocket[] socket = new BluetoothSocket[1];
                int i = 0;

                string Conectado = "nao";
                foreach (BluetoothDevice aparelho in aparelhos)
                {
                    apa[i] = aparelho;
                    if (aparelho.Name == TextBluetooth.Text)
                    {
                        Conectado = "sim";
                        chaves    = aparelho.GetUuids();
                        socket[0] = aparelho.CreateInsecureRfcommSocketToServiceRecord(chaves[0].Uuid);
                        break;
                    }
                    i++;
                }
                if (adaptador?.IsEnabled == false)
                {
                    var enableBtIntent = "ok";
                }
                if (Conectado == "sim")
                {
                    var address = apa[i].Address;
                    conectar(socket[0]);
                }
            };

            BtnSalvar.Click += delegate
            {
                if (RdnWifi.Checked == true)
                {
                    if (TextIp.Text == "")
                    {
                        Toast.MakeText(this, "Deve ser digitado um Endereço de nº IP", ToastLength.Short).Show();
                        return;
                    }
                    if (TextPorta.Text == "")
                    {
                        Toast.MakeText(this, "Deve ser digitado uma Porta de comunicação", ToastLength.Short).Show();
                        return;
                    }
                }
                if (RdnBluetooth.Checked == true)
                {
                    if (TextBluetooth.Text == "")
                    {
                        Toast.MakeText(this, "Deve ser digitado um pareamento BlueTooth", ToastLength.Short).Show();
                        return;
                    }
                }
                //if (TextSenha.Text == "")
                //{
                //    Toast.MakeText(this, "Deve ser digitada uma Senha", ToastLength.Short).Show();
                //    return;
                //}

                string DescricaoComunicao = "";



                //==============================================================================================//
                //                             VERIFICA SE JÁ EXISTE UM ENDEREÇO GRAVADO                        //
                //==============================================================================================//
                sSQLQuery = "";
                sSQLQuery = "SELECT _id,NR_PLATAFORMAS,DESCRICAO_TIPO_CONEXAO " +
                            " FROM CONEXAO_PLATAFORMA ";
                icursorTemp = sqldTemp.RawQuery(sSQLQuery, null);
                ValorCursor = icursorTemp.Count;
                if (RdnWifi.Checked == true)
                {
                    DescricaoComunicao = "WIFI";
                }
                if (RdnBluetooth.Checked == true)
                {
                    DescricaoComunicao = "BLUETOOTH";
                }

                string Data = System.DateTime.Today.ToShortDateString();
                string Hora = System.DateTime.Today.ToShortTimeString();

                if (ValorCursor == 0)
                {
                    string Valores = int.Parse(spinner.SelectedItem.ToString()) - 1 + ",'" +
                                     DescricaoComunicao + "','" +
                                     TextIp.Text + "','" +
                                     TextPorta.Text + "','" +
                                     TextBluetooth.Text + "','" +
                                     TextSenha.Text + "','" +
                                     Data + "','" +
                                     Hora + "'";
                    string Campos = "NR_PLATAFORMAS," +
                                    "DESCRICAO_TIPO_CONEXAO," +
                                    "ENDERECO_IP," +
                                    "PORTA," +
                                    "BLUETOOTH," +
                                    "SENHA," +
                                    "DATA_CADASTRO," +
                                    "HORA_CADASTRO";

                    sSQLQuery = "INSERT INTO " +
                                "CONEXAO_PLATAFORMA " + "(" + Campos + ") " +
                                "VALUES(" + Valores + ");";
                    sqldTemp.ExecSQL(sSQLQuery);
                    sMessage = "Record is saved.";
                    Toast.MakeText(this, "REGISTRO GRAVADO COM SUCESSO", ToastLength.Long).Show();
                }
                else
                {
                    string ComandoSql = "update CONEXAO_PLATAFORMA set " +
                                        $" NR_PLATAFORMAS={int.Parse(spinner.SelectedItem.ToString())-1}," +
                                        $" DESCRICAO_TIPO_CONEXAO='{DescricaoComunicao}'," +
                                        $" ENDERECO_IP='{TextIp.Text}'," +
                                        $" PORTA='{TextPorta.Text}', " +
                                        $" BLUETOOTH='{TextBluetooth.Text}', " +
                                        $" SENHA='{TextSenha.Text}', " +
                                        $" DATA_CADASTRO='{Data}', " +
                                        $" HORA_CADASTRO='{Hora}' " +
                                        $" where _id=1  ";

                    sqldTemp.ExecSQL(ComandoSql);
                    Toast.MakeText(this, "Atualização realizada com sucesso", ToastLength.Long).Show();
                }
            };
            void RadioButtonWifi(object sender, EventArgs e)
            {
                RadioButton rb = (RadioButton)sender;

                TextHeadBlutooth.Visibility     = ViewStates.Visible;
                TextBluetooth.Visibility        = ViewStates.Visible;
                textIpHeard.Visibility          = ViewStates.Invisible;
                TextIp.Visibility               = ViewStates.Invisible;
                textPortaHeard.Visibility       = ViewStates.Invisible;
                TextPorta.Visibility            = ViewStates.Invisible;
                BtnPesquisar.Visibility         = ViewStates.Visible;
                Validacoes.ConexaoWifiBluetooth = true;
            }

            void RadioButtonBluetooth(object sender, EventArgs e)
            {
                RadioButton rb = (RadioButton)sender;

                TextHeadBlutooth.Visibility     = ViewStates.Invisible;
                TextBluetooth.Visibility        = ViewStates.Invisible;
                textIpHeard.Visibility          = ViewStates.Visible;
                TextIp.Visibility               = ViewStates.Visible;
                textPortaHeard.Visibility       = ViewStates.Visible;
                TextPorta.Visibility            = ViewStates.Visible;
                BtnPesquisar.Visibility         = ViewStates.Invisible;
                Validacoes.ConexaoWifiBluetooth = false;
            }
        }
Exemplo n.º 25
0
 // Default function to upgrade the database.
 public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
 {
     db.ExecSQL(DeleteQuery);
     OnCreate(db);
 }
Exemplo n.º 26
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            string sSQLQuery = "";

            SetContentView(Resource.Layout.layoutProdutos);

            SetResult(Result.Canceled);
            //==========================================================//
            //              CRIAR BANCO DE DADOS                        //
            //==========================================================//
            mdTemp = new BancoDados("PRINCIPAL");
            mdTemp.CreateDatabases("PRINCIPAL");
            //==========================================================//


            var toolbar = FindViewById <Toolbar>(Resource.Id.toolbar);

            SetSupportActionBar(toolbar);
            SupportActionBar.Title = "CADASTRO DE PRODUTOS";
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeButtonEnabled(true);


            var relogioDigital = FindViewById <DigitalClock>(Resource.Id.digitalClock2);

            relogioDigital.Visibility = Android.Views.ViewStates.Visible;

            Android.Support.V7.Widget.AppCompatImageButton BtnSair   = FindViewById <Android.Support.V7.Widget.AppCompatImageButton>(Resource.Id.BtnVoltarProduto);
            Android.Support.V7.Widget.AppCompatImageButton BtnSalvar = FindViewById <Android.Support.V7.Widget.AppCompatImageButton>(Resource.Id.BtnSalvarProduto);

            EditText produto = FindViewById <EditText>(Resource.Id.TxtDescicaoProduto);
            EditText valor   = FindViewById <EditText>(Resource.Id.TextValorProduto);
            TextView codigo  = FindViewById <TextView>(Resource.Id.TxtCodigoProduto);

            sSQLQuery = "";
            string sLocation = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string sDB       = Path.Combine(sLocation, "PRINCIPAL");

            sqldTemp = SQLiteDatabase.OpenOrCreateDatabase(sDB, null);
            bool bIsExists = File.Exists(sDB);


            valor.AfterTextChanged += EditTextValor_AfterTextChanged;

            nomes = new string[1];
            for (int i = 0; i < 1; i++)
            {
                nomes[i] = " ".ToString();
            }
            CarregaListaProdutos();
            Window.SetSoftInputMode(SoftInput.StateHidden);

            BtnSair.Click += delegate
            {
                Finish();
            };

            BtnSalvar.Click += delegate
            {
                if (produto.Text == "")
                {
                    Toast.MakeText(this, "Deve ser digitada uma PRODUTO!", ToastLength.Short).Show();
                    return;
                }
                if (valor.Text == "")
                {
                    Toast.MakeText(this, "Deve ser selecionado um valor de PRODUTO!", ToastLength.Short).Show();
                    return;
                }

                //==============================================================================================//
                //                             VERIFICA SE JÁ EXISTE UM ENDEREÇO GRAVADO                        //
                //==============================================================================================//

                sLocation = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                sDB       = Path.Combine(sLocation, "PRINCIPAL");
                sqldTemp  = SQLiteDatabase.OpenOrCreateDatabase(sDB, null);
                bIsExists = File.Exists(sDB);


                Android.Database.ICursor icursorTemp = null;

                sSQLQuery   = "";
                sSQLQuery   = $"SELECT _id FROM PRODUTOS WHERE _id='{codigo.Text}'";
                icursorTemp = sqldTemp.RawQuery(sSQLQuery, null);
                int ValorCursor = icursorTemp.Count;


                string Data = System.DateTime.Today.ToShortDateString();
                string Hora = System.DateTime.Today.ToShortTimeString();

                if (ValorCursor == 0)
                {
                    //  string ValorProduto = System.String.Format(valor.Text,"C2");


                    string Valores = "'" + produto.Text + "','" +
                                     valor.Text + "','" +
                                     Data + "','" +
                                     Hora + "'";

                    string Campos = "PRODUTO," +
                                    "VALOR," +
                                    "DATA_CADASTRO," +
                                    "HORA_CADASTRO";

                    sSQLQuery = "INSERT INTO " +
                                "PRODUTOS " + "(" + Campos + ") " +
                                "VALUES(" + Valores + ");";
                    sqldTemp.ExecSQL(sSQLQuery);
                    sMessage = "Record is saved.";
                    Toast.MakeText(this, "REGISTRO GRAVADO COM SUCESSO", ToastLength.Long).Show();
                }
                else
                {
                    string ComandoSql = "update PRODUTOS set " +
                                        $" PRODUTO='{produto.Text}'," +
                                        $" VALOR='{valor.Text}'," +
                                        $" DATA_CADASTRO='{Data}', " +
                                        $" HORA_CADASTRO='{Hora}' " +
                                        $" where _id={codigo.Text}";

                    sqldTemp.ExecSQL(ComandoSql);
                    Toast.MakeText(this, "Atualização realizada com sucesso", ToastLength.Long).Show();
                }
                produto.Text = "";
                valor.Text   = "";
                codigo.Text  = "";
                CarregaListaProdutos();
            };


            void EditTextValor_AfterTextChanged(object sender, AfterTextChangedEventArgs e)
            {
                var text = e.Editable.ToString();

                valor.AfterTextChanged -= EditTextValor_AfterTextChanged;
                var formatedText = FormatarCampos.ValorValueConverter(text);

                valor.Text = formatedText;
                valor.SetSelection(formatedText.Length);
                valor.AfterTextChanged += EditTextValor_AfterTextChanged;
            }

            void CarregaListaProdutos()
            {
                Android.Database.ICursor icursorTemp = null;
                sSQLQuery = "SELECT _id," +
                            " PRODUTO, " +
                            " VALOR " +
                            " FROM PRODUTOS ";


                icursorTemp = sqldTemp.RawQuery(sSQLQuery, null);


                int ValorCursor = icursorTemp.Count;

                if (ValorCursor > 0)
                {
                    nomes = new string[icursorTemp.Count];

                    for (int i = 0; i < icursorTemp.Count; i++)
                    {
                        icursorTemp.MoveToNext();
                        item         = new CarreDadosProdutos();
                        item.Id      = icursorTemp.GetString(0);
                        item.Produto = icursorTemp.GetString(1);
                        item.Valor   = icursorTemp.GetString(2);
                        // item.Produto = FormatarCampos.RetornaTextoLista(item.Produto.PadRight(35, '0'));
                        string Linha = "";
                        Linha = item.Id.PadLeft(5, '0') + "       " +
                                item.Produto.PadRight(15, '_') +
                                item.Valor.PadLeft(20, '_');
                        nomes[i] = Linha;
                    }
                    ArrayAdapter <System.String> itemsAdapter = new ArrayAdapter <System.String>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, nomes);



                    Android.Widget.ListView listview = FindViewById <Android.Widget.ListView>(Resource.Id.ListaProdutos);
                    listview = FindViewById <Android.Widget.ListView>(Resource.Id.ListaProdutos);

                    listview.Adapter = itemsAdapter;

                    listview.ItemClick += ListView_ItemClick;
                }

                void ListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
                {
                    Validacoes.ValorItem = nomes[e.Id];

                    sSQLQuery = "SELECT _id," +
                                " PRODUTO, " +
                                " VALOR " +
                                " FROM PRODUTOS " +
                                $" WHERE _id={Convert.ToInt16(Validacoes.ValorItem.Substring(0, 6))}";

                    icursorTemp = sqldTemp.RawQuery(sSQLQuery, null);


                    ValorCursor = icursorTemp.Count;
                    if (ValorCursor > 0)
                    {
                        icursorTemp.MoveToNext();
                        codigo.Text  = icursorTemp.GetString(0);
                        produto.Text = icursorTemp.GetString(1);
                        valor.Text   = icursorTemp.GetString(2);
                    }
                }
            }
        }
Exemplo n.º 27
0
 public override void OnCreate(SQLiteDatabase db) // Step: 1 - 2:1
 {
     db.ExecSQL(CreateUserTableQuery);            // Step: 4
 }
Exemplo n.º 28
0
 public override void OnCreate(SQLiteDatabase db)
 {
     db.ExecSQL("CREATE TABLE motion_activity(Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Confidence FLOAT NOT NULL, Event INTEGER NOT NULL, Timestamp INTEGER NOT NULL)");
     db.ExecSQL("CREATE INDEX idx_timestamp ON motion_activity(Timestamp);");
 }