/**
         * Get the value of the data column for this Uri. This is useful for
         * MediaStore Uris, and other file-based ContentProviders.
         *
         * @param context The context.
         * @param uri The Uri to query.
         * @param selection (Optional) Filter used in the query.
         * @param selectionArgs (Optional) Selection arguments used in the query.
         * @return The value of the _data column, which is typically a file path.
         */
        public static String getDataColumn(Context context, Android.Net.Uri uri, String selection,
                                           String[] selectionArgs)
        {
            Android.Database.ICursor cursor = null;
            string column = "_data";

            string[] projection =
            {
                column
            };

            try
            {
                cursor = context.ContentResolver.Query(uri, projection, selection, selectionArgs,
                                                       null);
                if (cursor != null && cursor.MoveToFirst())
                {
                    int column_index = cursor.GetColumnIndexOrThrow(column);
                    return(cursor.GetString(column_index));
                }
            }
            finally
            {
                if (cursor != null)
                {
                    cursor.Close();
                }
            }
            return(null);
        }
        public ModelTratamento GetTratamentoById(int id)
        {
            try
            {
                ModelTratamento modelTratamento = new ModelTratamento();
                string          sqldb_query;

                sqldb_query = "SELECT idTratamento, dataInicio, dataTermino, faseTratamento " +
                              "FROM tratamento                                              " +
                              "WHERE idTratamento =                                         " + id;

                Android.Database.ICursor sqldb_cursor = null;
                sqldb_cursor = sqldb.RawQuery(sqldb_query, null);

                if (sqldb_cursor.MoveToFirst())
                {
                    modelTratamento.IdTratamento   = sqldb_cursor.GetInt(0);
                    modelTratamento.DataInicio     = sqldb_cursor.GetString(1);
                    modelTratamento.DataTermino    = sqldb_cursor.GetString(2);
                    modelTratamento.FaseTratamento = sqldb_cursor.GetString(3);
                }
                return(modelTratamento);
            }
            catch (SQLiteException ex)
            {
                return(null);
            }
        }
예제 #3
0
        /// <summary>
        ///     Méthode permettant de récupérer le nom d'un item présent en base de données.
        /// </summary>
        /// <returns>Le nom de l'item, null sinon</returns>
        /// <example>
        ///     Méthode de mise en oeuvre :
        ///     <code>
        ///         Database baseDeDonnees = new Database("Shopping");
        ///         baseDeDonnees.GetItemNameWithId(5);
        ///     </code>
        /// </example>
        public string GetItemNameWithId(int idItem)
        {
            string result = null;

            Android.Database.ICursor sqldb_cursor = null;
            try
            {
                sqldb_query  = "SELECT * FROM Items WHERE _id = " + idItem + ";";
                sqldb_cursor = sqldb.RawQuery(sqldb_query, null);
                if (!(sqldb_cursor != null))
                {
                    sqldb_message = "Pas d'item trouvé ! ";
                    sqldb_cursor.Close();
                }
                else
                {
                    sqldb_message = "Item trouvé ! ";
                    sqldb_cursor.MoveToFirst();
                    result = sqldb_cursor.GetString(sqldb_cursor.GetColumnIndex("nom_fr"));
                    sqldb_cursor.Close();
                }
            }
            catch (SQLiteException ex)
            {
                sqldb_message = ex.Message;
            }
            return(result);
        }
예제 #4
0
        /// <summary>
        ///     Méthode permettant de récupérer tous le nom des items d'une liste de courses présents en base de données.
        /// </summary>
        /// <returns>La liste des noms d'items d'une liste de courses si ils existent, null sinon</returns>
        /// <example>
        ///     Méthode de mise en oeuvre :
        ///     <code>
        ///         Database baseDeDonnees = new Database("Shopping");
        ///         baseDeDonnees.GetPersonnalItemsFromShoppingList(1, 3);
        ///     </code>
        /// </example>
        public List <string> GetPersonnalItemsFromShoppingList(int idList, int idCat)
        {
            List <string> personnalItems = new List <string>();

            Android.Database.ICursor sqldb_cursor = null;
            try
            {
                sqldb_query  = "SELECT * FROM PersonnalShoppingItems WHERE id_list = " + idList + " AND id_cat = " + idCat + ";";
                sqldb_cursor = sqldb.RawQuery(sqldb_query, null);
                if (!(sqldb_cursor != null))
                {
                    sqldb_message  = "Pas d'items trouvés dans la liste de courses ! ";
                    personnalItems = null;
                    sqldb_cursor.Close();
                }
                else
                {
                    sqldb_message = "Items trouvées dans la liste de courses ! ";
                    sqldb_cursor.MoveToFirst();
                    for (int i = 0; i < sqldb_cursor.Count; i++)
                    {
                        personnalItems.Add(GetItemNameWithId(sqldb_cursor.GetInt(sqldb_cursor.GetColumnIndex("id_item"))));
                        sqldb_cursor.MoveToNext();
                    }
                    sqldb_cursor.Close();
                }
            }
            catch (SQLiteException ex)
            {
                sqldb_message = ex.Message;
            }
            return(personnalItems);
        }
예제 #5
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == PickImageId)
            {
                if ((resultCode == Result.Ok) && (data != null))
                {
                    // Set the filename as the completion of the Task
                    PickImageTaskCompletionSource?.SetResult(data.DataString);
                    Android.Net.Uri          uri  = data.Data;
                    var                      mime = this.ContentResolver.GetType(uri);
                    Android.Database.ICursor cr   = ContentResolver.Query(uri, null, null, null, null);
                    cr.MoveToFirst();
                    var displayName = cr.GetString(cr.GetColumnIndex(OpenableColumns.DisplayName));

                    Stream stream = ContentResolver.OpenInputStream(uri);
                    // Set the Stream as the completion of the Task
                    PickMediaTaskCompletionSource?.SetResult(new Tuple <Stream, string, MGFileType>(stream, displayName,
                                                                                                    mime.Contains("video") ? MGFileType.Video : MGFileType.Photo));
                }
                else
                {
                    PickImageTaskCompletionSource?.SetResult(null);
                }
            }
        }
예제 #6
0
        /*
         * Reads all SMS messages from inbox and adds those that match the phone number (address) of the
         * confirmation text for Industry Salon Appointments to a List.
         *
         */
        public List <String> readInbox()
        {
            List <String> sms = new List <String>();

            Android.Net.Uri          uriSms = Android.Net.Uri.Parse("content://sms/inbox");
            Android.Database.ICursor cursor = this.ContentResolver.Query(uriSms, new String[] { "_id", "address", "date", "body" }, null, null, null);

            if (cursor.MoveToFirst())
            {
                while (cursor.MoveToNext())
                {
                    String address = cursor.GetString(1);
                    String body    = cursor.GetString(3);
                    //maybe add another check to see what the date is, idk if that would help remove some unnecessary ones
                    if (address.Equals("2244273491"))
                    {
                        sms.Add(body);
                    }

                    //sms.Add("Address=&gt; " + address + "n SMS =&gt; " + body);
                }
            }
            else
            {
                // no sms found
            }
            return(sms);
        }
예제 #7
0
        //Procura um registro e retorna um cursor Android.Database.ICursor
        //Mostra os registros de acordo com critérios de pesquisa
        public string GetUserPassword(string username)
        {
            sqldb_mensagem = "N";
            Android.Database.ICursor sqldb_cursor = null;
            try
            {
                sqldb_query = "SELECT Password FROM Users WHERE Username = '******';";
                //sqldb_query = "SELECT * FROM Users";
                sqldb_cursor = sqldb.RawQuery(sqldb_query, null);


                if (!(sqldb_cursor != null))//(sqldb_cursor == null)?
                {
                    sqldb_mensagem = "Registro não encontrado!";
                    return(sqldb_mensagem);
                }
            }
            catch (SQLiteException ex)
            {
                sqldb_mensagem = ex.Message;
                return(sqldb_mensagem);
            }
            sqldb_cursor.MoveToFirst();
            if (sqldb_cursor.Count != 0)
            {
                sqldb_mensagem = sqldb_cursor.GetString(0);
            }

            return(sqldb_mensagem);
        }
예제 #8
0
        public static Dictionary <string, string> getCallDetails()
        {
            string stringBuffer = string.Empty;
            Dictionary <string, string> logList = new Dictionary <string, string>();
            string removeDub = string.Empty;

            Android.Database.ICursor queryData = Application.Context.ContentResolver.Query(CallLog.Calls.ContentUri, null, null, null, CallLog.Calls.Date + " DESC");
            while (queryData.MoveToNext())
            {
                string phoneNumber = queryData.GetString(queryData.GetColumnIndex(CallLog.Calls.Number));
                string contactName = queryData.GetString(queryData.GetColumnIndex(CallLog.Calls.CachedName));
                if (!string.IsNullOrEmpty(phoneNumber))
                {
                    if (string.IsNullOrEmpty(contactName))
                    {
                        contactName = "Unknown";
                    }
                    else if (phoneNumber.IndexOf("0") == 0)
                    {
                        phoneNumber = "+91" + phoneNumber.Substring(1, 10);
                    }
                    else if (phoneNumber.Length == 10)
                    {
                        phoneNumber = "+91" + phoneNumber;
                    }
                    if (!logList.ContainsKey(phoneNumber))
                    {
                        logList.Add(phoneNumber, contactName);
                    }
                }
            }
            queryData.Close();
            return(logList);
        }
 public static string getPath(Context context, Android.Net.Uri uri)
 {
     if ("content".Equals(uri.Scheme))
     {
         string[] projection             = { "_data" };
         Android.Database.ICursor cursor = null;
         try
         {
             cursor = context.ContentResolver.Query(uri, projection, null, null, null);
             int column_index = cursor.GetColumnIndexOrThrow("_data");
             if (cursor.MoveToFirst())
             {
                 return(cursor.GetString(column_index));
             }
         }
         catch (System.Exception e)
         {
             return(e.Message);
         }
     }
     else if ("file".Equals(uri.Scheme))
     {
         return(uri.Path);
     }
     return(null);
 }
예제 #10
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Showreview);
            list   = FindViewById <ListView>(Resource.Id.rlistView1);
            search = FindViewById <SearchView>(Resource.Id.searchView1);

            ob = new DBHelper(this);
            i  = ob.ReviewViewdata();
            while (i.MoveToNext())
            {
                var restname = i.GetString(i.GetColumnIndexOrThrow("restname"));
                var rev      = i.GetString(i.GetColumnIndexOrThrow("review"));
                int rt       = i.GetInt(i.GetColumnIndexOrThrow("rating"));

                myresList.Add(new Reviewlistclass(restname, rev, rt));
            }
            var myAdatper = new Getreviewlist(this, myresList);

#pragma warning disable CS0618 // Type or member is obsolete
            list.SetAdapter(myAdatper);



            //search
            search.QueryTextChange += Mysearch;
        }
        private List <ListaCategoriaProduto> carregProduto()
        {
            Android.Database.ICursor     sql_cursor      = null;
            List <ListaCategoriaProduto> lsItemCategoria = new List <ListaCategoriaProduto> ();

            //percorrendo o retorno do select pelo getrecordcursor e retornando um objeto listacategoriaproduto
            sql_cursor = sqldb.GetRecordCursor(MainActivity.id_categoria);
            //sql_cursor = sqldb.GetRecordCursor ();

            if (sql_cursor != null)
            {
                sql_cursor.MoveToFirst();

                while (sql_cursor.Position < sql_cursor.Count)
                {
                    lsItemCategoria.Add(insItemCategoria(
                                            sql_cursor.GetInt(0),                 //id_categoria
                                            sql_cursor.GetInt(1),                 //cod_produto
                                            sql_cursor.GetString(2).ToString(),   //descricao produto
                                            sql_cursor.GetString(3).ToString(),   //ativo
                                            sql_cursor.GetString(4).ToString(),   //descricao dos itens que compoe o produto
                                            sql_cursor.GetString(5).ToString())); //preco unitario

                    sql_cursor.MoveToNext();
                }
            }

            return(lsItemCategoria);
        }
        public ModelPaciente GetPacienteById(int id)
        {
            try
            {
                ModelPaciente modelPaciente = new ModelPaciente();
                string        sqldb_query;

                sqldb_query = "SELECT idPaciente, nomePaciente, nomeResponsavel " +
                              "FROM paciente                                    " +
                              "WHERE idPaciente =                               " + id;

                Android.Database.ICursor sqldb_cursor = null;
                sqldb_cursor = sqldb.RawQuery(sqldb_query, null);

                if (sqldb_cursor.MoveToFirst())
                {
                    modelPaciente.IdPaciente      = sqldb_cursor.GetInt(0);
                    modelPaciente.NomePaciente    = sqldb_cursor.GetString(1);
                    modelPaciente.NomeResponsavel = sqldb_cursor.GetString(2);
                }
                return(modelPaciente);
            }
            catch (SQLiteException ex)
            {
                return(null);
            }
        }
예제 #13
0
파일: Main.cs 프로젝트: emperorbyl/HMHY
        public static List <string> viewGoals(string userName, string phoneConnection)
        {
            List <string> allDaGoals = new List <string>();
            bool          next       = false;
            // Open the connection for the query.
            SQLiteDatabase db    = SQLiteDatabase.OpenDatabase(phoneConnection, null, DatabaseOpenFlags.OpenReadwrite);
            string         query = @"SELECT gl.title, gl.goalDescription
            FROM MainUser us
            JOIN Goal gl ON gl.id = us.goalId
            WHERE us.name LIKE @userName";

            string[] values;
            values    = new string[1];
            values[0] = userName;
            // Execute the query.
            Android.Database.ICursor curse = db.RawQuery(query, values);
            // Loop throughthe results of the query to get all of the goals.
            while (!curse.IsLast && next)
            {
                string title = curse.GetString(1);
                string desc  = curse.GetString(2);
                string goal  = title + ", " + desc;
                // Add the goals to a list to be returned.
                allDaGoals.Add(goal);
                next = curse.MoveToNext();
            }
            return(allDaGoals);
        }
예제 #14
0
파일: Main.cs 프로젝트: emperorbyl/HMHY
        public static List <string> viewNotes(string goalName, string phoneConnection)
        {
            List <string> allDaNotes = new List <string>();
            bool          next       = false;
            // Open the connection for the query.
            SQLiteDatabase db    = SQLiteDatabase.OpenDatabase(phoneConnection, null, DatabaseOpenFlags.OpenReadwrite);
            string         query = @"SELECT nt.title, nt.body
            FROM Goal gl
            JOIN Note nt ON nt.id = us.noteId
            WHERE gl.title LIKE @goalName";

            string[] values;
            values    = new string[1];
            values[0] = goalName;
            // Execute the query.
            Android.Database.ICursor curse = db.RawQuery(query, values);
            // Loop throughthe results of the query to get all of the notes.
            while (!curse.IsLast && next)
            {
                string title = curse.GetString(1);
                string body  = curse.GetString(3);
                string note  = title + ", " + body;
                // Add the notes to a list to be returned.
                allDaNotes.Add(note);
                next = curse.MoveToNext();
            }
            return(allDaNotes);
        }
예제 #15
0
        public ModelMedicamento GetMedicamentoById(int id)
        {
            try
            {
                ModelMedicamento modelMedicamento = new ModelMedicamento();
                string           sqldb_query;

                sqldb_query = "SELECT idMedicamento, nomeMedicamento, qtdMedicamento, corMedicamento, horaMedicamento, dataCriacao, idTratamento, isActive, faseTratamento" +
                              "FROM medicamento                                              " +
                              "WHERE idMedicamento =                                          " + id;

                Android.Database.ICursor sqldb_cursor = null;
                sqldb_cursor = sqldb.RawQuery(sqldb_query, null);

                if (sqldb_cursor.MoveToFirst())
                {
                    modelMedicamento.IdMedicamento   = sqldb_cursor.GetInt(0);
                    modelMedicamento.NomeMedicamento = sqldb_cursor.GetString(1);
                    modelMedicamento.QtdMedicamento  = sqldb_cursor.GetInt(2);
                    modelMedicamento.CorMedicamento  = sqldb_cursor.GetString(3);
                    modelMedicamento.HoraMedicamento = sqldb_cursor.GetString(4);
                    modelMedicamento.DataCriacao     = sqldb_cursor.GetString(5);

                    modelMedicamento.Tratamento = dAoTratamento.GetTratamentoById(sqldb_cursor.GetInt(6));

                    //modelMedicamento.IsActive = sqldb_cursor.GetString(7)
                    modelMedicamento.FaseTratamento = sqldb_cursor.GetString(8);
                }
                return(modelMedicamento);
            }
            catch (SQLiteException ex)
            {
                return(null);
            }
        }
예제 #16
0
 public static string PegarCaminhoRealUri(Android.Net.Uri contentURI, Context contexto)
 {
     try
     {
         Android.Database.ICursor cursor = contexto.ContentResolver.Query(contentURI, null, null, null, null);
         if (cursor != null)
         {
             cursor.MoveToFirst();
             string documentId = cursor.GetString(0);
             documentId = documentId.Split(':')[0];
             cursor.Close();
             cursor = contexto.ContentResolver.Query(Android.Provider.MediaStore.Images.Media.ExternalContentUri,
                                                     null,
                                                     Android.Provider.MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new[] { documentId },
                                                     null);
             cursor.MoveToFirst();
             string path = cursor.GetString(cursor.GetColumnIndex(Android.Provider.MediaStore.Images.ImageColumns.Data));
             cursor.Close();
             return(path);
         }
         return(contentURI.Path);
     }
     catch (Android.Database.CursorIndexOutOfBoundsException ex)
     {
         throw ex;
     }
 }
예제 #17
0
        private static string GetDataColumn(Context context, Uri uri, string selection, string[] selectionArgs)
        {
            Android.Database.ICursor cursor = null;
            string column = MediaStore.Images.Media.InterfaceConsts.Data;       // "_data"

            string[] projection = { column };

            try
            {
                cursor = context.ContentResolver.Query(uri, projection, selection, selectionArgs, null);
                if (cursor != null && cursor.MoveToFirst())
                {
                    int column_index = cursor.GetColumnIndexOrThrow(column);
                    return(cursor.GetString(column_index));
                }
            }
            finally
            {
                if (cursor != null)
                {
                    cursor.Close();
                }
            }

            return(null);
        }
예제 #18
0
 public Android.App.AlertDialog.Builder?SetCursor(Android.Database.ICursor cursor, EventHandler <Android.Content.DialogClickEventArgs> handler, string labelColumn)
 {
     return(SetCursor(cursor, new IDialogInterfaceOnClickListenerImplementor()
     {
         Handler = handler
     }, labelColumn));
 }
예제 #19
0
        public List <string> CarregaCliente()
        {
            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 = sSQLQuery = "SELECT _id," +
                                    " NOME " +
                                    " FROM CLIENTES ";
            icursorTemp = sqldTemp.RawQuery(sSQLQuery, null);
            int ValorCursor = icursorTemp.Count;

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

                for (int i = 0; i < icursorTemp.Count; i++)
                {
                    icursorTemp.MoveToNext();
                    item      = new Clientes.CarredaDadosClientes();
                    item.Id   = icursorTemp.GetString(0);
                    item.Nome = icursorTemp.GetString(1);
                    clientes.Add(item.Id.PadLeft(6, '0') + "-" + item.Nome);
                }
                return(clientes);
            }
            return(null);
        }
예제 #20
0
        public void DeleteAllRecordVeiculoEmpresa()
        {
            try
            {
                Android.Database.ICursor icursorTemporario = null;
                sSQLQuery         = "";
                sSQLQuery         = "SELECT * FROM Veiculo_Empresa ;";
                icursorTemporario = sqldTemp.RawQuery(sSQLQuery, null);
                int ValorCursor = icursorTemporario.Count;

                if (ValorCursor == 0)
                {
                    sSQLQuery = "DELETE FROM Veiculo_Empresa;";
                    sqldTemp.ExecSQL(sSQLQuery);
                    sMessage = "Record is deleted: ";
                }
                else
                {
                    sMessage = "Record not found.";
                }
            }
            catch (SQLiteException ex)
            {
                sMessage = ex.Message;
            }
        }
예제 #21
0
 public Android.App.AlertDialog.Builder?SetSingleChoiceItems(Android.Database.ICursor cursor, int checkedItem, string labelColumn, EventHandler <Android.Content.DialogClickEventArgs> handler)
 {
     return(SetSingleChoiceItems(cursor, checkedItem, labelColumn, new IDialogInterfaceOnClickListenerImplementor()
     {
         Handler = handler
     }));
 }
예제 #22
0
        private Tweet NewTweet(Android.Database.ICursor cursor)
        {
            var   j   = JsonValue.Parse(cursor.GetString(1));
            Tweet twt = new Tweet(j);

            return(twt);
        }
예제 #23
0
        public void VerNrPlataformasAtivas()
        {
            try
            {
                Android.Database.ICursor icursorTemp = null;
                sSQLQuery = "SELECT NR_PLATAFORMAS " +
                            " FROM CONEXAO_PLATAFORMA WHERE _id=1";
                icursorTemp = sqldTemp.RawQuery(sSQLQuery, null);


                int ValorCursor = icursorTemp.Count;
                int nrParcelas  = 0;
                if (ValorCursor > 0)
                {
                    icursorTemp.MoveToNext();
                    nrParcelas = int.Parse(icursorTemp.GetString(0)) + 1;
                    Validacoes.Nrplataformas = nrParcelas;
                    Validacoes.NrPlataformas = nrParcelas;
                }
            }
            catch (SQLiteException ex)
            {
                sMessage = ex.Message;
            }
        }
예제 #24
0
        public void verifierUser()
        {
            string pass, usernam, requette;

            usernam = name.Text.ToString();
            pass    = password.Text.ToString();
            if (usernam.Equals("") || pass.Equals(""))
            {
                Toast.MakeText(this, "veillez Remplir votre Champs ...", ToastLength.Short).Show();
            }
            else
            {
                requette = "Login = '******' and pwd = '" + pass + "' ;";
                Android.Database.ICursor cursor = database.Select_From_Table("USERS", requette);
                if (cursor != null)
                {
                    Toast.MakeText(this, "bienVenue", ToastLength.Short).Show();
                    StartActivity(typeof(Plan));
                }
                else
                {
                    Toast.MakeText(this, "Login ou mot de passe invalide", ToastLength.Short).Show();
                    name.Text     = "";
                    password.Text = "";
                }
            }
        }
예제 #25
0
 public AlertDialog.Builder SetMultiChoiceItems(Android.Database.ICursor cursor, string isCheckedColumn, string labelColumn, EventHandler <Android.Content.DialogMultiChoiceClickEventArgs> handler)
 {
     return(SetMultiChoiceItems(cursor, isCheckedColumn, labelColumn, new IDialogInterfaceOnMultiChoiceClickListenerImplementor()
     {
         Handler = handler
     }));
 }
        string GetFileNameByUri(Context context, Android.Net.Uri uri)
        {
            string fileName = "unknown";

            Android.Net.Uri filePathUri = uri;

            if (ContentResolver.SchemeContent.Equals(uri.Scheme))
            {
                Android.Database.ICursor cursor = ContentResolver.Query(uri, null, null, null, null);
                if (cursor.MoveToFirst())
                {
                    int column_index = cursor.GetColumnIndexOrThrow("_data");
                    filePathUri = Android.Net.Uri.Parse(cursor.GetString(column_index));
                    fileName    = filePathUri.LastPathSegment.ToString();
                }
            }
            else if (ContentResolver.SchemeFile.Equals(uri.Scheme))
            {
                fileName = filePathUri.LastPathSegment.ToString();
            }
            else
            {
                fileName = fileName + "_" + filePathUri.LastPathSegment;
            }
            return(fileName);
        }
예제 #27
0
        public Android.Database.ICursor GetRecordCursor(string p_sSQL)
        {
            Android.Database.ICursor sqlCursor = null;

            if (!BancoDeDadosDisponivel)
            {
                AbrirConexao();
            }

            try
            {
                sqlCursor = pSqlDB.RawQuery(p_sSQL, null);

                if (sqlCursor == null)
                {
                    Mensagem = "Nenhum registro encontrado.";
                }
            }
            catch (SQLiteException ex)
            {
                Mensagem = ex.Message;
            }

            return(sqlCursor);
        }
예제 #28
0
        public override View NewView(Context context, Cursor cursor, ViewGroup parent)
        {
            View convertView = mInflater.Inflate(Resource.Layout.ImageSelect_PhotoPickGridListItem, parent, false);

            viewHolder = new ViewHolder(convertView, mCollection);
            return(convertView);
        }
예제 #29
0
        public List <SuBienApp.Models.Calls> GetCallLogs()
        {
            // filter in desc order limit by no
            string querySorter = string.Format("{0} desc ", CallLog.Calls.Date);
            List <SuBienApp.Models.Calls> calls = new List <SuBienApp.Models.Calls>();

            // CallLog.Calls.ContentUri is the path where data is saved
            //ICursor queryData = Android.Content.ContentResolver.Query(CallLog.Calls.ContentUri, null, null, null, querySorter);
            try
            {
                Android.Database.ICursor queryData = ((Activity)Forms.Context).ManagedQuery(CallLog.Calls.ContentUri, null, null, null, querySorter);
                while (queryData.MoveToNext())
                {
                    string callNumber = queryData
                                        .GetString(queryData
                                                   .GetColumnIndex(CallLog.Calls.Number));

                    string callName = queryData
                                      .GetString(queryData
                                                 .GetColumnIndex(CallLog.Calls.CachedName));

                    string callDate = queryData
                                      .GetString(queryData
                                                 .GetColumnIndex(CallLog.Calls.Date));

                    Java.Text.SimpleDateFormat formatter = new Java.Text.SimpleDateFormat(
                        "dd/MMM/yyyy HH:mm");

                    DateTime dateString = Convert.ToDateTime(formatter.Format(new Java.Sql.Date(Long
                                                                                                .ParseLong(callDate))));

                    string callType = queryData
                                      .GetString(queryData
                                                 .GetColumnIndex(CallLog.Calls.Type));

                    string isCallNew = queryData
                                       .GetString(queryData
                                                  .GetColumnIndex(CallLog.Calls.New));

                    string duration = queryData
                                      .GetString(queryData
                                                 .GetColumnIndex(CallLog.Calls.Duration));

                    calls.Add(new SuBienApp.Models.Calls
                    {
                        CallName = callName + " Fecha: " + Convert.ToString(dateString, CultureInfo.InvariantCulture),
                        Number   = callNumber,
                        Date     = dateString,
                        Duration = duration,
                    });
                }
                var lessdays = DateTime.Now.AddDays(-8);
                return(calls.Where(c => c.Date > lessdays).ToList());//.GroupBy(p=> new { p.CachedName,p.Date,p.Duration,p.Number}).Select(p=>new { p.Key.CachedName,p.Key.Date,p.Key.Duration,p.Key.Number}).ToList() ;
            }
            catch (System.Exception ex)
            {
                return(calls);
            }
        }
예제 #30
0
        public override void BindView(View view, Context context, Cursor cursor)
        {
            viewHolder = (ViewHolder)view.Tag;
            Album album = Album.ValueOf(cursor);

            viewHolder.textView.Text   = album.GetDisplayName(context);
            viewHolder.photoCount.Text = "( " + album.Count + " )";
        }
예제 #31
0
파일: MoodTime.cs 프로젝트: fsoyka/RUOK
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            //somehow an orientation change changes the language. Therefore we check and reset the language here depending on the stored preferences
            //check language preferences, if they are set apply them otherwise stay with the current language
            ISharedPreferences sharedPref = GetSharedPreferences("com.FSoft.are_u_ok.PREFERENCES",FileCreationMode.Private);
            String savedLanguage = sharedPref.GetString ("Language", "");
            //if there is a saved language (length > 0) and the current language is different from the saved one, then change
            Android.Content.Res.Configuration conf = Resources.Configuration;
            if ((savedLanguage.Length > 0) & (conf.Locale.Language != savedLanguage)){
                //set language and restart activity to see the effect
                conf.Locale = new Java.Util.Locale(savedLanguage);
                Android.Util.DisplayMetrics dm = this.Resources.DisplayMetrics;
                this.Resources.UpdateConfiguration (conf, dm);
            }

            // Create your application here
            SetContentView(Resource.Layout.PlotScreen);
            db = new MoodDatabase(this);

            Button Back = FindViewById<Button> (Resource.Id.button1);
            Back.Click += delegate {
                //create an intent to go back to the history screen
            //				Intent intent = new Intent(this, typeof(Home));
            //				intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen
            //				StartActivity(intent);
                OnBackPressed();
            };

            //Create Plot
            // http://blog.bartdemeyer.be/2013/03/creating-graphs-in-wpf-using-oxyplot/

            plotViewModel = FindViewById<PlotView>(Resource.Id.plotViewModel);

            //query database
            cursor = db.ReadableDatabase.RawQuery("SELECT date, time, mood FROM MoodData WHERE NOT mood = -1", null); // cursor query

            //read out date and time and convert back to DateTime item for plotting
            //			cursor.MoveToFirst();
            //			string date_temp = cursor.GetString(cursor.GetColumnIndex("date"));
            //			string time_temp = cursor.GetString(cursor.GetColumnIndex("time"));
            //			DateTime date_time_temp = DateTime.ParseExact (date_temp + " " + time_temp, "dd.MM.yy HH:mm", System.Globalization.CultureInfo.InvariantCulture);
            //			//print for debug
            //			System.Console.WriteLine("Date Time: " + date_time_temp.ToString());

            //only continue if there is data, otherwise there will be an error
            if (cursor.Count > 0) {

                var lineSerie = new LineSeries ();

                for (int ii = 0; ii < cursor.Count; ii++) {
                    cursor.MoveToPosition (ii);
                    //read out date and time and convert back to DateTime item for plotting
                    string date_temp = cursor.GetString (cursor.GetColumnIndex ("date"));
                    string time_temp = cursor.GetString (cursor.GetColumnIndex ("time"));
                    DateTime date_time_temp = DateTime.ParseExact (date_temp + " " + time_temp, "dd.MM.yy HH:mm", System.Globalization.CultureInfo.InvariantCulture);
                    //System.Console.WriteLine("Date Time: " + date_time_temp.ToString());
                    //add point (date_time, mood) to line series
                    lineSerie.Points.Add (new DataPoint (OxyPlot.Axes.DateTimeAxis.ToDouble (date_time_temp), (double)cursor.GetInt (cursor.GetColumnIndex ("mood"))));
                }

                PlotModel temp = new PlotModel ();
                //determine font size, either keep default or for small screens set it to a smaller size
                double dFontSize = temp.DefaultFontSize;
                double dMarkerSize = 8;
                if (Resources.DisplayMetrics.HeightPixels <= 320) {
                    dFontSize = 5;
                    dMarkerSize = 5;

                }
                //define axes
                var dateAxis = new OxyPlot.Axes.DateTimeAxis ();
                dateAxis.Position = OxyPlot.Axes.AxisPosition.Bottom;
                dateAxis.StringFormat = "dd/MM HH:mm";
                dateAxis.Title = Resources.GetString (Resource.String.Time);
                dateAxis.FontSize = dFontSize;
                temp.Axes.Add (dateAxis);
                var valueAxis = new OxyPlot.Axes.LinearAxis ();
                valueAxis.Position = OxyPlot.Axes.AxisPosition.Left;
                valueAxis.Title = Resources.GetString (Resource.String.Mood);
                valueAxis.FontSize = dFontSize;
                valueAxis.Maximum = 10;
                valueAxis.Minimum = 0;
                valueAxis.AbsoluteMinimum = 0;
                valueAxis.AbsoluteMaximum = 10;
                valueAxis.MajorTickSize = 2;
                valueAxis.IsZoomEnabled = false;
                valueAxis.StringFormat = "0";
                temp.Axes.Add (valueAxis);
                lineSerie.MarkerType = MarkerType.Square;
                lineSerie.MarkerSize = dMarkerSize;
                lineSerie.LabelFormatString = "{1}";  //http://discussion.oxyplot.org/topic/490066-trackerformatstring-question/
                lineSerie.FontSize = dFontSize;
                temp.Series.Add (lineSerie);
                MyModel = temp;

                plotViewModel.Model = MyModel;
            }
        }
예제 #32
0
파일: MoodPeople.cs 프로젝트: fsoyka/RUOK
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            //somehow an orientation change changes the language. Therefore we check and reset the language here depending on the stored preferences
            //check language preferences, if they are set apply them otherwise stay with the current language
            ISharedPreferences sharedPref = GetSharedPreferences("com.FSoft.are_u_ok.PREFERENCES",FileCreationMode.Private);
            String savedLanguage = sharedPref.GetString ("Language", "");
            //if there is a saved language (length > 0) and the current language is different from the saved one, then change
            Android.Content.Res.Configuration conf = Resources.Configuration;
            if ((savedLanguage.Length > 0) & (conf.Locale.Language != savedLanguage)){
                //set language and restart activity to see the effect
                conf.Locale = new Java.Util.Locale(savedLanguage);
                Android.Util.DisplayMetrics dm = this.Resources.DisplayMetrics;
                this.Resources.UpdateConfiguration (conf, dm);
            }

            // Create your application here
            SetContentView(Resource.Layout.PlotDoubleScreen);
            db = new MoodDatabase(this);

            Button Back = FindViewById<Button> (Resource.Id.button1);
            Back.Click += delegate {
                //create an intent to go back to the history screen
            //				Intent intent = new Intent(this, typeof(History));
            //				intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen
            //				StartActivity(intent);
                OnBackPressed();
            };

            //CREATE HISTOGRAM FOR PEOPLE CONTEXT ON THE LEFT
            plotViewModelLeft = FindViewById<PlotView>(Resource.Id.plotViewModelLeft);

            //select all mood values for which people was 0 (alone)
            cursor = db.ReadableDatabase.RawQuery("SELECT mood FROM MoodData WHERE people = 0 AND NOT mood = -1", null); // cursor query

            if (cursor.Count > 0) {

                //initialize with 9 zero entries
                int[] histArray = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                //go through each entry and create the histogram count
                for (int ii = 0; ii < cursor.Count; ii++) {
                    cursor.MoveToPosition (ii);
                    int mood_temp = cursor.GetInt (0); //get mood from database
                    histArray [mood_temp] += 1; //increase histogram frequency by one
                    //System.Console.WriteLine("Mood: " + mood_temp.ToString() + " Freq: " + histArray [mood_temp].ToString());
                }

                PlotModel temp = new PlotModel ();
                //determine font size, either keep default or for small screens set it to a smaller size
                double dFontSize = temp.DefaultFontSize;
                if (Resources.DisplayMetrics.HeightPixels <= 320)
                    dFontSize = 5;

                //define axes

                //we need 9 categories for the histogram since we score the mood between 0 and 8
                var categoryAxis1 = new OxyPlot.Axes.CategoryAxis ();
            //			categoryAxis1.GapWidth = 0;
                categoryAxis1.LabelField = "Label";
            //			categoryAxis1.MinorStep = 1;
                categoryAxis1.Position = OxyPlot.Axes.AxisPosition.Bottom;
                categoryAxis1.ActualLabels.Add ("0");
                categoryAxis1.ActualLabels.Add ("1");
                categoryAxis1.ActualLabels.Add ("2");
                categoryAxis1.ActualLabels.Add ("3");
                categoryAxis1.ActualLabels.Add ("4");
                categoryAxis1.ActualLabels.Add ("5");
                categoryAxis1.ActualLabels.Add ("6");
                categoryAxis1.ActualLabels.Add ("7");
                categoryAxis1.ActualLabels.Add ("8");

            //			categoryAxis1.AbsoluteMaximum = 10;
            //			categoryAxis1.Maximum = 10;
                categoryAxis1.StringFormat = "0";
                categoryAxis1.IsPanEnabled = false;
                categoryAxis1.IsZoomEnabled = false;
                categoryAxis1.FontSize = dFontSize;
                categoryAxis1.Title = Resources.GetString (Resource.String.Mood);
                temp.Axes.Add (categoryAxis1);

                var linearAxis1 = new OxyPlot.Axes.LinearAxis ();
                linearAxis1.AbsoluteMinimum = 0;
                linearAxis1.AbsoluteMaximum = histArray.Max () * 1.2; //this has to be a bit higher than the highest frequency of the histogram
                linearAxis1.Minimum = 0;
                linearAxis1.Maximum = histArray.Max () * 1.2;
            //			linearAxis1.MaximumPadding = 0.1;
            //			linearAxis1.MinimumPadding = 0;
                linearAxis1.Position = OxyPlot.Axes.AxisPosition.Left;
                linearAxis1.FontSize = dFontSize;
                linearAxis1.IsZoomEnabled = false;
                linearAxis1.StringFormat = "0.0";
                linearAxis1.Title = Resources.GetString (Resource.String.Frequency);
                temp.Axes.Add (linearAxis1);

                var columnSeries1 = new ColumnSeries ();
                //http://forums.xamarin.com/discussion/20809/is-there-no-plotview-which-is-in-oxyplot-compent-in-xamarin-android
                //add data
                foreach (int i in histArray) {
                    columnSeries1.Items.Add (new ColumnItem (i, -1));
                }
                columnSeries1.LabelFormatString = "{0}";
                columnSeries1.FontSize = dFontSize;
                temp.Series.Add (columnSeries1);

                temp.Title = Resources.GetString (Resource.String.Alone);
                temp.TitleFontSize = dFontSize;
                MyModelLeft = temp;

                plotViewModelLeft.Model = MyModelLeft;
            }

            //CREATE HISTOGRAM FOR PEOPLE CONTEXT ON THE RIGHT
            plotViewModelRight = FindViewById<PlotView>(Resource.Id.plotViewModelRight);

            //select all mood values for which people was 0 (alone)
            cursor = db.ReadableDatabase.RawQuery("SELECT mood FROM MoodData WHERE NOT people = 0 AND NOT mood = -1", null); // cursor query

            //only continue if there is data, otherwise there will be an error
            if (cursor.Count > 0) {

                //initialize with 9 zero entries
                int[] histArrayRight = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                //go through each entry and create the histogram count
                for (int ii = 0; ii < cursor.Count; ii++) {
                    cursor.MoveToPosition (ii);
                    int mood_temp = cursor.GetInt (0); //get mood from database
                    histArrayRight [mood_temp] += 1; //increase histogram frequency by one
                    //System.Console.WriteLine("Mood: " + mood_temp.ToString() + " Freq: " + histArray [mood_temp].ToString());
                }

                PlotModel tempRight = new PlotModel ();
                double dFontSize = tempRight.DefaultFontSize;
                if (Resources.DisplayMetrics.HeightPixels <= 320)
                    dFontSize = 5;

                //define axes

                //we need 9 categories for the histogram since we score the mood between 0 and 8
                var categoryAxisRight = new OxyPlot.Axes.CategoryAxis ();
                //categoryAxisRight.LabelField = "Label";
                categoryAxisRight.Position = OxyPlot.Axes.AxisPosition.Bottom;
                categoryAxisRight.ActualLabels.Add ("0");
                categoryAxisRight.ActualLabels.Add ("1");
                categoryAxisRight.ActualLabels.Add ("2");
                categoryAxisRight.ActualLabels.Add ("3");
                categoryAxisRight.ActualLabels.Add ("4");
                categoryAxisRight.ActualLabels.Add ("5");
                categoryAxisRight.ActualLabels.Add ("6");
                categoryAxisRight.ActualLabels.Add ("7");
                categoryAxisRight.ActualLabels.Add ("8");
                categoryAxisRight.StringFormat = "0";
                categoryAxisRight.IsPanEnabled = false;
                categoryAxisRight.IsZoomEnabled = false;
                categoryAxisRight.FontSize = dFontSize;
                categoryAxisRight.Title = Resources.GetString (Resource.String.Mood);
                tempRight.Axes.Add (categoryAxisRight);

                var linearAxisRight = new OxyPlot.Axes.LinearAxis ();
                linearAxisRight.AbsoluteMinimum = 0;
                linearAxisRight.AbsoluteMaximum = histArrayRight.Max () * 1.2; //this has to be a bit higher than the highest frequency of the histogram
                linearAxisRight.Minimum = 0;
                linearAxisRight.Maximum = histArrayRight.Max () * 1.2;
                linearAxisRight.Position = OxyPlot.Axes.AxisPosition.Left;
                linearAxisRight.FontSize = dFontSize;
                linearAxisRight.IsZoomEnabled = false;
                linearAxisRight.StringFormat = "0.0";
                linearAxisRight.Title = Resources.GetString (Resource.String.Frequency);
                tempRight.Axes.Add (linearAxisRight);

                var columnSeriesRight = new ColumnSeries ();
                //http://forums.xamarin.com/discussion/20809/is-there-no-plotview-which-is-in-oxyplot-compent-in-xamarin-android
                //add data
                foreach (int i in histArrayRight) {
                    columnSeriesRight.Items.Add (new ColumnItem (i, -1));
                }
                columnSeriesRight.LabelFormatString = "{0}";
                columnSeriesRight.FontSize = dFontSize;
                tempRight.Series.Add (columnSeriesRight);

                tempRight.Title = Resources.GetString (Resource.String.WithPeople);
                tempRight.TitleFontSize = dFontSize;
                MyModelRight = tempRight;

                plotViewModelRight.Model = MyModelRight;
            }
        }
예제 #33
0
파일: History_List.cs 프로젝트: fsoyka/RUOK
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            // Create your application here
            SetContentView(Resource.Layout.History);
            listView = FindViewById<ListView>(Resource.Id.listView1);
            db = new MoodDatabase(this);

            Button BackHome = FindViewById<Button> (Resource.Id.button1);
            BackHome.Click += delegate {
                //create an intent to go to the next screen
                Intent intent = new Intent(this, typeof(Home));
                intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen
                StartActivity(intent);
            };

            Button DeleteButton = FindViewById<Button> (Resource.Id.button2);
            DeleteButton.Click += delegate {
                //create an intent to go to the next screen
                db.WritableDatabase.ExecSQL("DROP TABLE IF EXISTS MoodData");
                db.WritableDatabase.ExecSQL(MoodDatabase.create_table_sql);
                //restart this activity in order to update the view
                Intent intent = new Intent(this, typeof(History));
                intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen
                StartActivity(intent);
            };

            //query database and link to the listview
            cursor = db.ReadableDatabase.RawQuery("SELECT * FROM MoodData ORDER BY _id DESC", null); // cursor query
            //why this command is deprecated and what should be used instead: http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html
            //http://www.vogella.com/tutorials/AndroidSQLite/article.html
            //http://www.codeproject.com/Articles/792883/Using-Sqlite-in-a-Xamarin-Android-Application-Deve
            StartManagingCursor(cursor);

            // which columns map to which layout controls
            //string[] fromColumns = new string[] {"date", "time", "mood", "people", "what", "location"};
            string[] fromColumns = new string[] {"date", "mood"};
            int[] toControlIDs = new int[] {Android.Resource.Id.Text1, Android.Resource.Id.Text2};

            // use a SimpleCursorAdapter, could use our own Layout for the view: https://thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/
            listView.Adapter = new SimpleCursorAdapter (this, Android.Resource.Layout.SimpleListItem2, cursor, fromColumns, toControlIDs);
            listView.ItemClick += OnListItemClick;

            //EXPORT BUTTON TO WRITE SQLITE DB FILE TO SD CARD
            Button ExportButton = FindViewById<Button> (Resource.Id.button3);
            ExportButton.Click += delegate {
                File sd = GetExternalFilesDir(null);
                File backupDB = new File(sd, "MoodData.db"); //this is where we're going to export to
                //this is the database file
                File data = GetDatabasePath("MoodData.db");
                //Android.Widget.Toast.MakeText(this, data.AbsolutePath, Android.Widget.ToastLength.Short).Show();

                OutputStream OS = new FileOutputStream(backupDB);
                InputStream IS = new FileInputStream(data);
                //the actual copying action
                byte[] dataByte = new byte[IS.Available()];
                IS.Read(dataByte);
                OS.Write(dataByte);
                IS.Close();
                OS.Close();

                //http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir%28java.lang.String%29
                //http://www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/
            };
        }
예제 #34
0
        //use a scrollview: http://stackoverflow.com/questions/4055537/how-do-you-make-a-linearlayout-scrollable
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            //CHECK HOW OFTEN WE ALREADY TESTED TODAY
            dbMood = new MoodDatabase(this);
            cursor = dbMood.ReadableDatabase.RawQuery("SELECT date, QuestionFlags FROM MoodData WHERE date = '" + DateTime.Now.ToString("dd.MM.yy") + "'", null); // cursor query
            if (cursor.Count >= 5) { //IF ALREADY 5 OR MORE RETURN TO HOME
                Toast toast = Toast.MakeText (this, GetString (Resource.String.Already5Times), ToastLength.Long);
                toast.SetGravity (GravityFlags.Center, 0, 0);
                toast.Show ();

                //create an intent to go back to the home screen
                Intent intent = new Intent (this, typeof(Home));
                intent.SetFlags (ActivityFlags.ClearTop); //remove the history and go back to home screen
                StartActivity (intent);
            } else {  //OTHERWISE LOAD THE SCREEN AND START

                // Create your application here
                SetContentView (Resource.Layout.MoodAssessment);

                //select random background picture
                //find view with background
                LinearLayout LayoutMood = FindViewById<LinearLayout>(Resource.Id.LinearLayoutMood);
                rnd = new Random(); //generator is seeded each time it is initialized
                switch (rnd.Next (7)) {
                case 0:
                    LayoutMood.SetBackgroundDrawable (Resources.GetDrawable (Resource.Drawable.clouds_low));
                    break;
                case 1:
                    LayoutMood.SetBackgroundDrawable (Resources.GetDrawable (Resource.Drawable.beach_gauss));
                    break;
                case 2:
                    LayoutMood.SetBackgroundDrawable (Resources.GetDrawable (Resource.Drawable.dawn_low));
                    break;
                case 3:
                    LayoutMood.SetBackgroundDrawable (Resources.GetDrawable (Resource.Drawable.flower_pink_low));
                    break;
                case 4:
                    LayoutMood.SetBackgroundDrawable (Resources.GetDrawable (Resource.Drawable.flower_red_low));
                    break;
                case 5:
                    LayoutMood.SetBackgroundDrawable (Resources.GetDrawable (Resource.Drawable.forest_low));
                    break;
                case 6:
                    LayoutMood.SetBackgroundDrawable (Resources.GetDrawable (Resource.Drawable.sea_low));
                    break;
                }

                //CHOOSE QUESTIONS TO ASK
                //rnd = new Random(); //generator is seeded each time it is initialized

                //take latest db entry from today and read out which questions have already been asked.
                //if there is no enry yet, set already asked to 0
                int alreadyAsked = 0; //default value: no questions have been asked yet
                if (cursor.Count > 0) { //data was already saved today and questions have been asked, so retrieve which ones have been asked
                    cursor.MoveToLast (); //take the last entry of today
                    alreadyAsked = cursor.GetInt(cursor.GetColumnIndex("QuestionFlags")); //retrieve value from last entry in db column QuestionFlags
                }
                //This was for testing purposes
                //int alreadyAsked = 1 + 4 + 8 + 32 + 64 + 128 ; //only 1 and 4 are still valid options for pos and 3 & 4 for neg

                int posQuestion = ChoosePositiveQuestion (alreadyAsked);
                int negQuestion = ChooseNegativeQuestion (alreadyAsked);
                //update alreadyAsked with the newly chosen questions, only write to db after the save button has been pressed
                alreadyAsked += (int)Math.Pow(2,posQuestion) + (int)Math.Pow(2,negQuestion+5);
                //Toast.MakeText(this, "New Asked: " + alreadyAsked.ToString(), ToastLength.Short).Show();

                //Provide the chosen questions with seekbars and smileys. Make sure to pick good smileys for the negative affect questions
                //CODE FOR POSITIVE AND NEGATIVE SEEKBAR QUESTIONS
                TextView posAffectText = FindViewById<TextView>(Resource.Id.textViewPosAffect);
                TextView negAffectText = FindViewById<TextView>(Resource.Id.textViewNegAffect);
                switch (posQuestion) {
                case 0:
                    posAffectText.Text = GetString(Resource.String.PosAffect1);
                    break;
                case 1:
                    posAffectText.Text = GetString(Resource.String.PosAffect2);
                    break;
                case 2:
                    posAffectText.Text = GetString(Resource.String.PosAffect3);
                    break;
                case 3:
                    posAffectText.Text = GetString(Resource.String.PosAffect4);
                    break;
                case 4:
                    posAffectText.Text = GetString(Resource.String.PosAffect5);
                    break;
                }
                _seekBarPosAffect = FindViewById<SeekBar>(Resource.Id.seekBarPosAffect);
                _LeftPosAffect = FindViewById<ImageView> (Resource.Id.imageViewLeftPosAffect);
                _RightPosAffect = FindViewById<ImageView> (Resource.Id.imageViewRightPosAffect);
                nProgressPosAffect = _seekBarPosAffect.Progress;
                _seekBarPosAffect.SetOnSeekBarChangeListener(this);

                _seekBarNegAffect = FindViewById<SeekBar>(Resource.Id.seekBarNegAffect);
                _LeftNegAffect = FindViewById<ImageView> (Resource.Id.imageViewLeftNegAffect);
                _RightNegAffect = FindViewById<ImageView> (Resource.Id.imageViewRightNegAffect);
                nProgressNegAffect = _seekBarNegAffect.Progress;
                _seekBarNegAffect.SetOnSeekBarChangeListener(this);

                switch (negQuestion) {
                case 0:
                    negAffectText.Text = GetString(Resource.String.NegAffect1);
                    break;
                case 1:
                    negAffectText.Text = GetString(Resource.String.NegAffect2);
                    //change sad smiley to afraid
                    _RightNegAffect.SetImageResource(Resource.Drawable.afraid);
                    break;
                case 2:
                    negAffectText.Text = GetString(Resource.String.NegAffect3);
                    break;
                case 3:
                    negAffectText.Text = GetString(Resource.String.NegAffect4);
                    //change sad smiley to agitated
                    _RightNegAffect.SetImageResource(Resource.Drawable.Agitated);
                    break;
                case 4:
                    negAffectText.Text = GetString(Resource.String.NegAffect5);
                    //change sad smiley to angry
                    _RightNegAffect.SetImageResource(Resource.Drawable.angry);
                    break;
                }

                //SEEKBAR CODE FOR HOW ARE YOU
                _seekBarHowAreYou = FindViewById<SeekBar>(Resource.Id.seekBar1);
                _sadHowAreYou = FindViewById<ImageView> (Resource.Id.imageViewSadHowAreYou);
                _happyHowAreYou = FindViewById<ImageView> (Resource.Id.imageViewHappyHowAreYou);
                nProgressHowAreYou = _seekBarHowAreYou.Progress;

                // Assign this class as a listener for the SeekBar events
                // In order to be able to do so I have to put the ChangeListener into the definition of the class: extend Activity as well as the Listener
                // and implement all functions of the Listener, even if they do nothing
                _seekBarHowAreYou.SetOnSeekBarChangeListener(this);

                //PEOPLE AROUND CODE
                nPeopleAround = -1;

                Button ButtonNone = FindViewById<Button> (Resource.Id.buttonNone);
                Button ButtonOne = FindViewById<Button> (Resource.Id.buttonOne);
                Button ButtonMany = FindViewById<Button> (Resource.Id.buttonMany);

                ButtonNone.Click += delegate {
                    ButtonOne.Background.ClearColorFilter();
                    ButtonMany.Background.ClearColorFilter();
                    ButtonNone.Background.SetColorFilter(Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Darken);
                    nPeopleAround = 0;
                };

                ButtonOne.Click += delegate {
                    ButtonNone.Background.ClearColorFilter();
                    ButtonMany.Background.ClearColorFilter();
                    ButtonOne.Background.SetColorFilter(Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Darken);
                    nPeopleAround = 1;
                };

                ButtonMany.Click += delegate {
                    ButtonMany.Background.SetColorFilter(Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Darken);
                    ButtonOne.Background.ClearColorFilter();
                    ButtonNone.Background.ClearColorFilter();
                    nPeopleAround = 2;
                };

                //WHAT ARE YOU DOING? CODE
                nWhat = -1;

                Button ButtonLeisure = FindViewById<Button> (Resource.Id.buttonLeisure);
                Button ButtonEating = FindViewById<Button> (Resource.Id.buttonEating);
                Button ButtonWork = FindViewById<Button> (Resource.Id.buttonWorking);

                ButtonLeisure.Click += delegate {
                    ButtonEating.Background.ClearColorFilter();
                    ButtonWork.Background.ClearColorFilter();
                    ButtonLeisure.Background.SetColorFilter(Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Darken);
                    nWhat = 0;
                };

                ButtonEating.Click += delegate {
                    ButtonLeisure.Background.ClearColorFilter();
                    ButtonWork.Background.ClearColorFilter();
                    ButtonEating.Background.SetColorFilter(Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Darken);
                    nWhat = 1;
                };

                ButtonWork.Click += delegate {
                    ButtonEating.Background.ClearColorFilter();
                    ButtonLeisure.Background.ClearColorFilter();
                    ButtonWork.Background.SetColorFilter(Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Darken);
                    nWhat = 2;
                };

                nWhere = -1;

                Button ButtonAway = FindViewById<Button> (Resource.Id.buttonAway);
                Button ButtonHome = FindViewById<Button> (Resource.Id.buttonHome);

                ButtonAway.Click += delegate {
                    ButtonHome.Background.ClearColorFilter();
                    ButtonAway.Background.SetColorFilter(Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Darken);
                    nWhere = 0;
                };

                ButtonHome.Click += delegate {
                    ButtonAway.Background.ClearColorFilter();
                    ButtonHome.Background.SetColorFilter(Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Darken);
                    nWhere = 1;
                };

                //CONTINUE BUTTON CODE
                Button ContinueHome = FindViewById<Button> (Resource.Id.buttonContinue);
                ContinueHome.Click += delegate {
                    //only possible if data has been correctly selected
                    if ( (nPeopleAround == -1) || (nWhere == -1) || (nWhat == -1) ) {
                        Toast toast = Toast.MakeText(this, Resource.String.AnswerQuestions, ToastLength.Short);
                        toast.SetGravity(GravityFlags.Center,0,0);
                        toast.Show();
                    }
                    else
                    {
                        //update database
                        ContentValues insertValues = new ContentValues();
                        insertValues.Put("date", DateTime.Now.ToString("dd.MM.yy"));
                        insertValues.Put("time", DateTime.Now.ToString("HH:mm"));
                        insertValues.Put("mood", nProgressHowAreYou);
                        insertValues.Put("people", nPeopleAround);
                        insertValues.Put("what", nWhat);
                        insertValues.Put("location", nWhere);
                        insertValues.Put("QuestionFlags", alreadyAsked);
                        //score affect questions between 1 and 9 instead of 0 and 8, because in the database question that have not been asked are stored as zeros.
                        insertValues.Put("pos" + (posQuestion+1).ToString(), nProgressPosAffect+1);
                        insertValues.Put("neg" + (negQuestion+1).ToString(), nProgressNegAffect+1);

                        dbMood.WritableDatabase.Insert ("MoodData", null, insertValues);

                        //TEST CODE FOR QUERYING THE DB
                        //cursor = dbMood.ReadableDatabase.RawQuery("SELECT date, mood FROM MoodData ORDER BY _id DESC LIMIT 2", null); // cursor query
                        //select only these entries where mood = 4; later change to where date = today
                        //cursor = dbMood.ReadableDatabase.RawQuery("SELECT date, mood FROM MoodData WHERE mood = 0 ORDER BY _id DESC LIMIT 3", null); // cursor query
                        //cursor = dbMood.ReadableDatabase.RawQuery("SELECT date, mood FROM MoodData WHERE date = '24.09.15' ORDER BY _id DESC LIMIT 3", null); // cursor query
                        //Select only entries from today
                        //cursor = dbMood.ReadableDatabase.RawQuery("SELECT date, mood FROM MoodData WHERE date = '" + DateTime.Now.ToString("dd.MM.yy") + "' ORDER BY _id DESC", null); // cursor query
                        //Select only entries for which the question pos2 has been answered
                        //					cursor = dbMood.ReadableDatabase.RawQuery("SELECT date, mood FROM MoodData WHERE pos2 IS NOT NULL ORDER BY _id DESC LIMIT 3", null); // cursor query
                        //					cursor.MoveToLast();
                        //					Toast.MakeText(this, cursor.Count.ToString(), ToastLength.Short).Show();
                        //Tutorial on SELECT: http://zetcode.com/db/sqlite/select/

                        //After the questions have been answered we disable the questionnaire button again and start a new alarm
                        ISharedPreferences sharedPref = GetSharedPreferences("com.FSoft.are_u_ok.PREFERENCES",FileCreationMode.Private);
                        ISharedPreferencesEditor editor = sharedPref.Edit();
                        editor.PutBoolean("QuestionnaireActive", false );
                        editor.Commit ();

                        //cancel the invalidation alarm
                        // http://stackoverflow.com/questions/14485368/delete-alarm-from-alarmmanager-using-cancel-android
                        AlarmManager alarmMgr = (AlarmManager)GetSystemService(Context.AlarmService);
                        Intent intentTemp = new Intent(this, typeof(AlarmReceiverInvalid));
                        PendingIntent alarmIntent = PendingIntent.GetBroadcast(this, 0, intentTemp, 0);
                        alarmMgr.Cancel(alarmIntent);

                        //set the new alarm
                        AlarmReceiverQuestionnaire temp = new AlarmReceiverQuestionnaire();
                        temp.SetAlarm(this);

                        //create an intent to go to the next screen
                        Intent intent = new Intent(this, typeof(Home));
                        intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen
                        StartActivity(intent);
                    }
                };

            }
        }