~phroa/phone-app

ref: 31f8f2dddef1d35557457de9fe53d74deeaad2e4 phone-app/phms/MainActivity.cs -rw-r--r-- 2.3 KiB
31f8f2ddJack Stratton Connect to PostgreSQL 6 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// SPDX-License-Identifier: AGPL-3.0-or-later

using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Support.Design.Widget;
using Android.Support.V7.App;
using Android.Widget;
using Npgsql;

namespace phms
{
    using R = Resource;
    
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        private const string DatabaseUriPref = "db_uri";

        protected override void OnCreate(Bundle? savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            var prefs = GetPreferences(FileCreationMode.Private) ??
                        throw new Exception("Couldn't GetPreferences.");

            var databaseUri = FindViewById<EditText>(R.Id.databaseUri) ??
                              throw new Exception("Couldn't FindViewById.");
            databaseUri.Text = prefs.GetString(DatabaseUriPref, "");
            databaseUri.AfterTextChanged += (sender, e) =>
            {
                using var prefsEditor = prefs.Edit() ??
                                        throw new Exception("Couldn't Edit preferences.");
                var newValue = databaseUri.Text;
                prefsEditor.PutString(DatabaseUriPref, newValue);
                prefsEditor.Apply();
            };

            var connect = FindViewById<Button>(R.Id.connect) ??
                          throw new Exception("Couldn't FindViewById.");
            connect.Click += (sender, e) =>
            {
                try
                {
                    using var conn = new NpgsqlConnection(databaseUri.Text);
                    conn.Open();
                    using var cmd = new NpgsqlCommand("SHOW server_version", conn);
                    var result = cmd.ExecuteScalar();
                    Snackbar.Make(connect, $"Success, {result}", Snackbar.LengthShort).Show();
                }
                catch
                {
                    Console.WriteLine();
                    Snackbar.Make(connect, "Failure", Snackbar.LengthShort).Show();
                    throw;
                }
            };
        }
    }
}