Beispiel #1
0
        //метод для обращения к API
        async void GetInfoAsync()
        {
            HttpClient client           = new HttpClient();
            HttpClient client_translate = new HttpClient();

            client.DefaultRequestHeaders.Add("user-key", apiKey);
            client_translate.DefaultRequestHeaders.Add("X-RapidAPI-Host", "microsoft-azure-translation-v1.p.rapidapi.com");
            client_translate.DefaultRequestHeaders.Add("X-RapidAPI-Key", "44aa189e74mshaa49add707f3528p1d96acjsn216ddd330fe5");
            try
            {
                Android.Support.V7.App.AlertDialog dialog =
                    new EDMTDialogBuilder().SetContext(this).SetMessage("Please wait..").Build();
                if (!dialog.IsShowing)
                {
                    dialog.Show();
                }
                //обращение к API
                HttpResponseMessage response = null;
                try
                {
                    response = await client.GetAsync(BasePath + "/restaurant?res_id=" + id);
                }
                catch (HttpRequestException)
                {
                    return;
                }
                //десериализация
                details_response = JsonConvert.DeserializeObject <DetailsResponse>(await response.Content.ReadAsStringAsync());
                var bitmap = GetBitMapFromURL(details_response.featured_image);
                image.SetImageBitmap(bitmap);

                response = null;
                //обращение к API переводчика
                try
                {
                    response = await client_translate.GetAsync("https://microsoft-azure-translation-v1.p.rapidapi.com/" +
                                                               "translate?from=en&to=ru&text=" + details_response.cuisines);
                }
                catch (HttpRequestException)
                {
                    return;
                }
                try
                {
                    //обработка ответа
                    details_response.cuisines = await response.Content.ReadAsStringAsync();

                    details_response.cuisines = details_response.cuisines.Split('>')[1];
                    details_response.cuisines = details_response.cuisines.Split('<')[0];
                }
                catch (IndexOutOfRangeException)
                {
                    return;
                }

                //формирование строки вывода

                string info = $"{details_response.name}\nРейтинг : {details_response.user_rating.aggregate_rating} ; Всего отзывов" +
                              $" : {details_response.user_rating.votes}" +
                              $"\nКухня : {details_response.cuisines}\nАдрес : {details_response.location.address}\nСредний чек :" +
                              $" {details_response.average_cost_for_two} {details_response.currency}\nБронь стола : ";
                if (details_response.has_table_booking == "0")
                {
                    info += $"нет";
                }
                else
                {
                    info += $"есть";
                }
                if (details_response.has_online_delivery == "0")
                {
                    info += $"\nОнлайн доставка : нет";
                }
                else
                {
                    info += $"\nОнлайн доставка : есть";
                }
                if (details_response.phone_numbers != "")
                {
                    info += $"\nНомер телефона : {details_response.phone_numbers}";
                }
                else
                {
                    info += $"\nНомер телефона : нет";
                }
                text.SetText(info, TextView.BufferType.Normal);
                btn_back.Visibility = ViewStates.Visible;
                btn_menu.Visibility = ViewStates.Visible;
                uri = details_response.menu_url;
                if (dialog.IsShowing)
                {
                    dialog.Dismiss();
                }
            }
            catch (Exception ex)
            {
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            IHealthAPI healthAPI;

            int      itemId   = 0;
            DateTime itemDate = DateTime.Now;

            SetContentView(Resource.Layout.pulse_layout);

            healthAPI = RestService.For <IHealthAPI>(sessionUser.uriSession);
            lstData   = FindViewById <ListView>(Resource.Id.pulseList);

            LoadData();


            var btn_addPulse    = FindViewById <Button>(Resource.Id.btn_addPulse);
            var btn_deletePulse = FindViewById <Button>(Resource.Id.btn_deletePulse);
            var btn_loadPulses  = FindViewById <Button>(Resource.Id.btn_loadPulses);

            btn_loadPulses.Click += async(s, e) =>
            {
                try
                {
                    Android.Support.V7.App.AlertDialog dialog = new EDMTDialogBuilder()
                                                                .SetContext(this)
                                                                .SetMessage("Proszę czekać...")
                                                                .Build();

                    if (!dialog.IsShowing)
                    {
                        dialog.Show();
                    }

                    List <Pulse> pulses = await healthAPI.GetPulses();

                    lstSource = pulses.FindAll(x => x.userId == sessionUser.Id);

                    dialog.Dismiss();
                    LoadData();
                }
                catch (Exception ex)
                {
                    Toast.MakeText(this, "" + ex.Message, ToastLength.Long).Show();
                }
            };

            lstData.ItemClick += (s, e) =>
            {
                for (int i = 0; i < lstData.Count; i++)
                {
                    if (e.Position == i)
                    {
                        lstData.GetChildAt(i).SetBackgroundColor(Android.Graphics.Color.DarkOrange);
                    }
                    else
                    {
                        lstData.GetChildAt(i).SetBackgroundColor(Android.Graphics.Color.Transparent);
                    }
                }

                itemId = int.Parse(e.Id.ToString());

                btn_deletePulse.Enabled = true;
            };

            btn_addPulse.Click += (s, e) =>
            {
                Intent nextActivity = new Intent(this, typeof(AddPulseActivity));
                Finish();
                StartActivity(nextActivity);
            };

            btn_deletePulse.Click += async(s, e) =>
            {
                await healthAPI.DeletePulse(itemId);

                LoadData();
            };
        }
        /// <summary>
        /// Метод старта
        /// </summary>
        /// <param name="savedInstanceState"></param>
        protected override void OnCreate(Bundle savedInstanceState)
        {
            string query = "";

            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
            btn_get_cities = FindViewById <Button>(Resource.Id.btn_get_cities);
            search_text    = FindViewById <AutoCompleteTextView>(Resource.Id.search_text);
            list_cities    = FindViewById <ListView>(Resource.Id.list_cities);


            //событие для получения индекса выбранного элемента
            list_cities.ItemClick += new EventHandler <AdapterView.ItemClickEventArgs>(GetIndex);
            //событие для обращения к API
            btn_get_cities.Click += async delegate
            {
                if (search_text.Text != "")
                {
                    //чтение запроса пользователя
                    query = search_text.Text;
                    query = query.Replace(' ', '+');
                    query = query.Replace(",", "%2C");
                    //обращение к API
                    HttpClient client           = new HttpClient();
                    HttpClient client_translate = new HttpClient();
                    client.DefaultRequestHeaders.Add("user-key", apiKey);
                    client_translate.DefaultRequestHeaders.Add("X-RapidAPI-Host", "microsoft-azure-translation-v1.p.rapidapi.com");
                    client_translate.DefaultRequestHeaders.Add("X-RapidAPI-Key", "44aa189e74mshaa49add707f3528p1d96acjsn216ddd330fe5");
                    try
                    {
                        HttpResponseMessage response = null;
                        //открытие диалога загрузки
                        Android.Support.V7.App.AlertDialog dialog =
                            new EDMTDialogBuilder().SetContext(this).SetMessage("Please wait..").Build();
                        if (!dialog.IsShowing)
                        {
                            dialog.Show();
                        }
                        //обращение к API переводчика
                        try
                        {
                            response = await client_translate.GetAsync("https://microsoft-azure-translation-v1.p.rapidapi.com/" +
                                                                       "translate?from=ru&to=en&text=" + query);
                        }
                        catch
                        {
                            Toast.MakeText(this, "Отсутсвует подключение к интернету!", ToastLength.Long).Show();
                            return;
                        }
                        try
                        {
                            //обработка запроса
                            query = await response.Content.ReadAsStringAsync();

                            query = query.Split('>')[1];
                            query = query.Split('<')[0];
                        }
                        catch (IndexOutOfRangeException)
                        {
                            Toast.MakeText(this, "Некорректный запрос", ToastLength.Long).Show();
                            return;
                        }
                        response = null;
                        try
                        {
                            response = await client.GetAsync(BasePath + "/cities?q=" + query);
                        }
                        catch
                        {
                            Toast.MakeText(this, "Отсутсвует подключение к интернету!", ToastLength.Long).Show();
                            return;
                        }
                        //десериализация
                        responce_cities = JsonConvert.DeserializeObject <CitiesResponse>(await response.Content.ReadAsStringAsync());


                        List <string> city_names = new List <string>();
                        response = null;
                        //перевод ответа
                        for (int i = 0; i < responce_cities.location_suggestions.Count; i++)
                        {
                            string name = responce_cities.location_suggestions[i].name;
                            name     = name.Replace(' ', '+');
                            name     = name.Replace(",", "%2C");
                            response = await client_translate.GetAsync("https://microsoft-azure-translation-v1.p.rapidapi.com/" +
                                                                       "translate?from=en&to=ru&text=" + name);

                            try
                            {
                                name = await response.Content.ReadAsStringAsync();

                                name = name.Split('>')[1];
                                name = name.Split('<')[0];
                            }
                            catch (IndexOutOfRangeException)
                            {
                                return;
                            }
                            responce_cities.location_suggestions[i].name = name;
                            city_names.Add(name);
                        }
                        //инициализация списка для вывода на экран
                        if (city_names.Count == 0)
                        {
                            Toast.MakeText(this, "Ничего не найдено!", ToastLength.Long).Show();
                        }
                        else
                        {
                            var adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, city_names);
                            list_cities.Adapter = adapter;
                        }

                        if (dialog.IsShowing)
                        {
                            dialog.Dismiss();
                        }
                    }
                    catch
                    {
                        Toast.MakeText(this, "Отсутсвует подключение к интернету!", ToastLength.Long).Show();
                    }
                }
                else
                {
                    Toast.MakeText(this, "Введите город", ToastLength.Long).Show();
                }
            };
        }
Beispiel #4
0
        //метод для обращения к API
        async void GetListAsync()
        {
            string path = BasePath + "/search?entity_id=" + city_id + "&entity_type=city&count=" + count.ToString();

            if (cuisine_id != "-1")
            {
                path += $"&cuisines={cuisine_id}";
            }
            if (collection_id != "-1")
            {
                path += $"$collection_id={collection_id}";
            }

            if (category_id != "-1")
            {
                path += $"$category_id={category_id}";
            }

            if (sort != "-1")
            {
                path += $"&sort={sort}";
                path += $"&order={sort_dir}";
            }
            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("user-key", apiKey);
                Android.Support.V7.App.AlertDialog dialog =
                    new EDMTDialogBuilder().SetContext(this).SetMessage("Please wait..").Build();
                if (!dialog.IsShowing)
                {
                    dialog.Show();
                }


                HttpResponseMessage response = null;
                try
                {
                    response = await client.GetAsync(path);
                }
                catch (HttpRequestException)
                {
                    Toast.MakeText(this, text: "Отсутсвует подключение к интернету!", duration: ToastLength.Long).Show();
                    return;
                }
                restaurant_collection = JsonConvert.DeserializeObject <RestaurantsResponce>(await response.Content.ReadAsStringAsync());
                restaurants           = restaurant_collection.restaurants;
                foreach (var restaurant in restaurants)
                {
                    restaurants_names.Add(restaurant.restaurant.name);
                }
                var adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, restaurants_names);
                list_restaurants.Adapter = adapter;
                if (dialog.IsShowing)
                {
                    dialog.Dismiss();
                }
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "" + ex.Message, ToastLength.Long).Show();
            }
        }
Beispiel #5
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            IHealthAPI healthAPI;

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.login_layout);

            healthAPI = RestService.For <IHealthAPI>(sessionUser.uriSession);


            var btn_login    = FindViewById <Button>(Resource.Id.btn_login);
            var txt_login    = FindViewById <EditText>(Resource.Id.txt_login);
            var txt_password = FindViewById <EditText>(Resource.Id.txt_password);



            btn_login.Click += async(s, e) =>
            {
                try
                {
                    Android.Support.V7.App.AlertDialog dialog = new EDMTDialogBuilder()
                                                                .SetContext(this)
                                                                .SetMessage("Proszę czekać...")
                                                                .Build();

                    Android.Support.V7.App.AlertDialog dialogNoUser = new EDMTDialogBuilder()
                                                                      .SetContext(this)
                                                                      .SetMessage("No user")
                                                                      .Build();

                    if (!dialog.IsShowing)
                    {
                        dialog.Show();
                    }

                    List <User> users = await healthAPI.GetUsers();

                    User newUser = new User()
                    {
                        Login    = txt_login.Text.ToString(),
                        Password = txt_password.Text.ToString()
                    };

                    var userExists = users.Contains((users.Find(x => (x.Login == newUser.Login) && (x.Password == newUser.Password))));
                    var currUser   = users.Find(x => (x.Login == newUser.Login) && (x.Password == newUser.Password));

                    if (userExists)
                    {
                        dialog.Hide();

                        sessionUser.Id = currUser.Id;
                        Intent nextActivity = new Intent(this, typeof(MainPageActivity));
                        StartActivity(nextActivity);
                    }

                    else
                    {
                        dialogNoUser.Show();
                    }
                }
                catch (Exception ex)
                {
                    Toast.MakeText(this, "" + ex.Message, ToastLength.Long).Show();
                }
            };
        }