public override void OnReceive(Context context, Intent intent) { PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService); PowerManager.WakeLock w1 = pm.NewWakeLock (WakeLockFlags.Full | WakeLockFlags.AcquireCausesWakeup | WakeLockFlags.OnAfterRelease, "NotificationReceiver"); w1.Acquire (); //Toast.MakeText (context, "Received intent!", ToastLength.Short).Show (); var nMgr = (NotificationManager)context.GetSystemService (Context.NotificationService); //var notification = new Notification (Resource.Drawable.Icon, context.Resources.GetString(Resource.String.ReminderTitle)); var notification = new Notification (Resource.Drawable.Icon, context.Resources.GetString(Resource.String.ReminderTitle)); //Clicking the pending intent does not go to the Home Activity Screen, but to the last activity that was active before leaving the app var pendingIntent = PendingIntent.GetActivity (context, 0, new Intent (context, typeof(Home)), PendingIntentFlags.UpdateCurrent); //Notification should be language specific notification.SetLatestEventInfo (context, context.Resources.GetString(Resource.String.ReminderTitle), context.Resources.GetString(Resource.String.InvalidationText), pendingIntent); notification.Flags |= NotificationFlags.AutoCancel; nMgr.Notify (0, notification); // Vibrator vibrator = (Vibrator) context.GetSystemService(Context.VibratorService); // if (vibrator != null) // vibrator.Vibrate(400); //change shared preferences such that the questionnaire button can change its availability ISharedPreferences sharedPref = context.GetSharedPreferences("com.FSoft.are_u_ok.PREFERENCES",FileCreationMode.Private); ISharedPreferencesEditor editor = sharedPref.Edit(); editor.PutBoolean("QuestionnaireActive", false ); editor.Commit (); //insert a line of -1 into some DB values to indicate that the questions have not been answered at the scheduled time MoodDatabase dbMood = new MoodDatabase(context); ContentValues insertValues = new ContentValues(); insertValues.Put("date", DateTime.Now.ToString("dd.MM.yy")); insertValues.Put("time", DateTime.Now.ToString("HH:mm")); insertValues.Put("mood", -1); insertValues.Put("people", -1); insertValues.Put("what", -1); insertValues.Put("location", -1); //use the old value of questionFlags Android.Database.ICursor cursor; cursor = dbMood.ReadableDatabase.RawQuery("SELECT date, QuestionFlags FROM MoodData WHERE date = '" + DateTime.Now.ToString("dd.MM.yy") + "'", null); // cursor query 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 } insertValues.Put("QuestionFlags", alreadyAsked); dbMood.WritableDatabase.Insert ("MoodData", null, insertValues); //set the new alarm AlarmReceiverQuestionnaire temp = new AlarmReceiverQuestionnaire(); temp.SetAlarm(context); w1.Release (); //check these pages for really waking up the device // http://stackoverflow.com/questions/6864712/android-alarmmanager-not-waking-phone-up // https://forums.xamarin.com/discussion/7490/alarm-manager //it's good to use the alarm manager for tasks that should last even days: // http://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android/ }
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/ }; }
protected override void OnCreate(Bundle bundle) { base.OnCreate (bundle); // Create your application here SetContentView(Resource.Layout.History); db = new MoodDatabase(this); Button MoodTime = FindViewById<Button> (Resource.Id.buttonMoodTime); MoodTime.Click += delegate { //create an intent to go to the next screen Intent intent = new Intent(this, typeof(MoodTime)); StartActivity(intent); }; Button MoodPeople = FindViewById<Button> (Resource.Id.buttonMoodPeople); MoodPeople.Click += delegate { //create an intent to go to the next screen Intent intent = new Intent(this, typeof(MoodPeople)); StartActivity(intent); }; Button ExDB = FindViewById<Button> (Resource.Id.buttonExDB); ExDB.Click += delegate { //delete current DB and fill it with an example dataset db.WritableDatabase.ExecSQL("DROP TABLE IF EXISTS MoodData"); db.WritableDatabase.ExecSQL(MoodDatabase.create_table_sql); //we want histograms that show bad mood when you are alone and good mood when you are with people db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '07:30', 3, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '09:30', 3, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '11:30', 7, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '16:30', 1, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '20:30', 6, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '07:30', 3, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '09:30', 2, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '11:30', 7, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '16:30', 1, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '20:30', 6, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '09:30', 2, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '11:30', 7, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '13:30', 1, 0, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '16:30', 8, 2, 1, 1, 1023)"); db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '18:30', 3, 0, 1, 1, 1023)"); //Feedback message Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short); toast.SetGravity (GravityFlags.Center, 0, 0); toast.Show (); }; 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); //Feedback message Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short); toast.SetGravity (GravityFlags.Center, 0, 0); toast.Show (); //restart this activity in order to update the view Intent intent = new Intent(this, typeof(History)); intent.SetFlags(ActivityFlags.ClearTop); //remove the history StartActivity(intent); }; //EXPORT BUTTON TO WRITE SQLITE DB FILE TO SD CARD Button ExportButton = FindViewById<Button> (Resource.Id.button3); ExportButton.Click += delegate { //This is for exporting the db file 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(); //Now try to export everything as a csv file Android.Database.ICursor cursor; cursor = db.ReadableDatabase.RawQuery("SELECT * FROM MoodData ORDER BY _id DESC", null); // cursor query //only write a file if there are entries in the DB if (cursor.Count > 0) { backupDB = new File(sd, "MoodData.csv"); //this is where we're going to export to OS = new FileOutputStream(backupDB); //write a header in the beginning string header = "date; time; mood; people; what; location; pos1; pos2; pos3; pos4; pos5; neg1; neg2; neg3; neg4; neg5\n"; byte[] bytes = new byte[header.Length * sizeof(char)]; System.Buffer.BlockCopy(header.ToCharArray(), 0, bytes, 0, bytes.Length); OS.Write(bytes); for (int ii = 0; ii < cursor.Count; ii++) { //go through all rows cursor.MoveToPosition (ii); //now go through all columns for (int kk = 1; kk < cursor.ColumnCount-1; kk++) { //skip the first column since it is just the ID and the last since it's the question flags //[date] TEXT NOT NULL, [time] TEXT NOT NULL, [mood] INT NOT NULL, [people] INT NOT NULL, [what] INT NOT NULL, [location] INT NOT NULL, [pos1] INT, [pos2] INT , [pos3] INT, [pos4] INT, [pos5] INT, [neg1] INT, [neg2] INT , [neg3] INT, [neg4] INT, [neg5] INT, [QuestionFlags] INT NOT NULL)"; //the first two columns are strings, the rest is int string tempStr; if (kk < 3) { tempStr = cursor.GetString(kk); } else { int tempInt = cursor.GetInt(kk); tempStr = tempInt.ToString(); } if (kk == cursor.ColumnCount-2) //if last column, advance to next line tempStr += "\n"; else tempStr += "; "; //convert to byte and write bytes = new byte[tempStr.Length * sizeof(char)]; System.Buffer.BlockCopy(tempStr.ToCharArray(), 0, bytes, 0, bytes.Length); OS.Write(bytes); } } OS.Close(); //Encrypt File var zipTemp = new ZIPHelper(); zipTemp.Save(sd.AbsolutePath); System.Console.WriteLine("Path: " + sd.AbsolutePath ); //send via email var email = new Intent(Intent.ActionSend); email.SetType("text/plain"); //email.PutExtra(Android.Content.Intent.ExtraEmail, new string[]{"*****@*****.**"}); email.PutExtra(Android.Content.Intent.ExtraSubject, "R-U-OK Export"); email.PutExtra(Android.Content.Intent.ExtraText, "Beschreibung der Datenbank Einträge :\n[mood] Stimmung 0-8, -1 wenn die Erinnerung verpasst wurde\n[people] keiner-viele, 0-2 \n[what] Freizeit-Arbeit, 0-2 \n[location] Unterwegs/Daheim, 0-1 \n[pos1-5] und [neg1-5] sind die Affekt Fragen, bewertet zwischen 1-9. Einträge mit 0 sind nicht gefragt worden. Die Frage sind folgende:\nPos1: Wie fröhlich fühlen Sie sich?\nPos2: Wie optimistisch sind Sie?\nPos3: Wie zufrieden sind Sie?\nPos4: Wie entspannt sind Sie?\nPos5: 5te Frage fehlt noch\nNeg1: Wie traurig sind Sie?\nNeg2: Wie ängstlich sind Sie?\nNeg3: Wie einsam sind Sie?\nNeg4: Wie unruhig sind Sie?\nNeg5: Wie ärgerlich sind Sie?\n" ); //email.PutExtra(Android.Content.Intent.ExtraStream, Android.Net.Uri.Parse("file://" + backupDB.AbsolutePath)); email.PutExtra(Android.Content.Intent.ExtraStream, Android.Net.Uri.Parse("file://" + sd.AbsolutePath + "//MoodData.zip")); //System.Console.WriteLine(backupDB.AbsolutePath); StartActivity(Intent.CreateChooser(email, "Send email...")); } //Feedback message Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short); toast.SetGravity (GravityFlags.Center, 0, 0); toast.Show (); //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/ }; }
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; } }
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; } }
//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); } }; } }