Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using Android.App;
- using Android.Content.PM;
- using Android.Runtime;
- using Android.Views;
- using Android.Widget;
- using Android.OS;
- using Android.Content;
- using System.Json;
- using System.Net;
- using System.IO;
- using System.Threading.Tasks;
- using static Android.Support.V7.Widget.Toolbar;
- using Android.Support.V7.App;
- using Android.Support.V4.Widget;
- using Java.Util;
- namespace Upgrid.Droid
- {
- [Activity(Label = "", Icon = "@drawable/upgrid", Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
- public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
- {
- private string pt = "Utilizador desconhecido";
- private string en = "Unknown user";
- private string loggedUserID;
- private string retrievedCred;
- private string[] credentials = new string[2];
- private SharedPreferences sp = new SharedPreferences();
- protected override void OnCreate(Bundle bundle)
- {
- base.OnCreate(bundle);
- //elimina o utilizador
- //removeUserLogin("Username", "Password");
- //recebe as credenciais do utilizador
- retrievedCred = sp.retrieveCredencials();
- //verifica se o utilizador já tem o login feito ou não
- checkLogin(retrievedCred);
- global::Xamarin.Forms.Forms.Init(this, bundle);
- LoadApplication(new App());
- }
- //verifica se o utilizador já tem o login feito ou não
- private async void checkLogin(string retrievedCred)
- {
- //se o campo das credenciais tiver dados de um utilizador, faz login com esse utilizador
- if (!retrievedCred.Equals("-"))
- {
- string loggedUsername = "";
- string loggedPassword = "";
- string[] words = retrievedCred.Split('-');
- for (int i = 0; i < words.Length; i++)
- {
- credentials[i] = words[i];
- }
- //username + password
- int j = 0;
- loggedUsername = credentials[j];
- loggedPassword = credentials[j + 1];
- string url = "http://intra.withus.pt:8080/upgrid/api/v1/fakelogin/" + loggedUsername + "/" + loggedPassword;
- //Ler valores do utilizador
- JsonValue json = await FetchUrlAsync(url);
- //Passa diretamente para a páginal inicial da aplicação com os dados do utilizador
- var dashboard = new Intent(this, typeof(Dashboard));
- dashboard.PutExtra("loggedUserID", loggedUserID); //passa o id do utilizador para acesso a dados
- StartActivity(dashboard);
- }
- else
- {
- //se o campo das credenciais estiver sem dados, pede login ao utilizador
- TabLayoutResource = Resource.Layout.Tabbar;
- ToolbarResource = Resource.Layout.toolbar;
- SetContentView(Resource.Layout.login_layout);
- var userName = FindViewById<EditText>(Resource.Id.usertext);
- var password = FindViewById<EditText>(Resource.Id.passwordtext);
- var loginButton = FindViewById<Button>(Resource.Id.loginButton);
- //Botão para login
- loginButton.Click += async delegate {
- userName.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) =>
- {
- userName.Text = e.Text.ToString();
- };
- password.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) =>
- {
- password.Text = e.Text.ToString();
- };
- //Pedido ao servidor
- string url = "http://intra.withus.pt:8080/upgrid/api/v1/fakelogin/" + userName.Text + "/" + password.Text;
- //Ler valores do utilizador
- JsonValue json = await FetchUrlAsync(url);
- //Verificar se o utilizador existe
- checkUser(loggedUserID, userName, password);
- };
- }
- }
- //verifica se o utilizador existe (no caso de não haver credenciais guardadas)
- private void checkUser(string loggedUserID, EditText userName, EditText password)
- {
- //Utilizador desconhecido
- if (loggedUserID.Equals("-1"))
- {
- string language = Locale.Default.Language;
- if (language.Equals("pt"))
- {
- Toast.MakeText(this, pt, ToastLength.Long).Show();
- }
- else if (language.Equals("en"))
- {
- Toast.MakeText(this, en, ToastLength.Long).Show();
- }
- }
- else
- {
- sp.saveCredentials(userName.Text, password.Text); //guardar credenciais de acesso à app
- var dashboard = new Intent(this, typeof(Dashboard));
- dashboard.PutExtra("loggedUserID", loggedUserID); //passa o id do utilizador para acesso a dados
- StartActivity(dashboard);
- }
- }
- // Gets data from the passed URL.
- private async Task<JsonValue> FetchUrlAsync(string url)
- {
- // Create an HTTP web request using the URL:
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
- request.ContentType = "application/json";
- request.Method = "GET";
- // Send the request to the server and wait for the response:
- using (WebResponse response = await request.GetResponseAsync())
- {
- // Get a stream representation of the HTTP web response:
- using (Stream stream = response.GetResponseStream())
- {
- // Use this stream to build a JSON document object:
- JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
- //Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
- //Get user ID (-1 if not exists)
- loggedUserID = jsonDoc.ToString();
- // Return the JSON document:
- //Console.Out.WriteLine(" - " + jsonDoc.ToString());
- return jsonDoc;
- }
- }
- }
- public override void OnBackPressed()
- {
- base.OnBackPressed();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement