Beispiel #1
0
        internal async Task <List <Model.Publish> > GetData()
        {
            var service = new SocialMediaService();

            Android.Support.V7.App.AlertDialog dialog = new EDMTDialogBuilder()
                                                        .SetContext(this).SetMessage(GetString(Resource.String.msg_please_wait)).Build();
            if (!_swipeRefresh.Refreshing)
            {
                dialog.Show();
            }

            var result = await service.GetData(this, CurrentPage);

            TotalPage = result.Result.MetaData.TotalPages;
            if (!result.IsSuccess)
            {
                if (!_swipeRefresh.Refreshing)
                {
                    dialog.Dismiss();
                }
                _swipeRefresh.Refreshing = false;
                Toast.MakeText(this, result.Message, ToastLength.Short).Show();
                return(null);
            }

            if (!_swipeRefresh.Refreshing)
            {
                dialog.Dismiss();
            }
            _swipeRefresh.Refreshing = false;
            return(result.Result.Data);
        }
Beispiel #2
0
        /// <summary>
        /// Get info about the product from API
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void GetIndex(object sender, AdapterView.ItemClickEventArgs e)
        {
            var listview = sender as ListView;

            Android.Support.V7.App.AlertDialog dialog = new EDMTDialogBuilder()
                                                        .SetContext(this)
                                                        .SetMessage("Please wait...")
                                                        .Build();
            if (!dialog.IsShowing)
            {
                dialog.Show();
            }
            string url = "https://api.nutritionix.com/v1_1/item?id=" + root.hits[e.Position].fields.item_id + "&appId=a76fc23d&appKey=7ca7f97a063b60691f2446b4a5b3f543";
            HttpResponseMessage response;
            HttpClient          client = new HttpClient();

            response = await client.GetAsync(url);

            product = JsonConvert.DeserializeObject <Product>(await response.Content.ReadAsStringAsync());
            Intent nextlayout = new Intent(this, typeof(CalcSet));

            kcal += (int)product.nf_calories;
            nextlayout.PutExtra("kcal", (kcal * amount).ToString());
            if (dialog.IsShowing)
            {
                dialog.Dismiss();
            }
            StartActivity(nextlayout);
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            button_data = FindViewById <Button>(Resource.Id.BTN_Users);
            list_users  = FindViewById <ListView>(Resource.Id.LV_Users);

            myAPI = RestService.For <ApiIF>("http://jsonplaceholder.typicode.com");

            button_data.Click += async delegate {
                try
                {
                    Android.Support.V7.App.AlertDialog dialog = new EDMTDialogBuilder()
                                                                .SetContext(this)
                                                                .SetMessage("Patience please!!!")
                                                                .Build();

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

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

                    List <string> user_name = new List <string>();

                    foreach (var user in users)
                    {
                        user_name.Add(user.name);
                    }
                    var adapter = new ArrayAdapter <string>(this,
                                                            Android.Resource.Layout.SimpleListItem1, user_name);
                    list_users.Adapter = adapter;

                    if (dialog.IsShowing)
                    {
                        dialog.Dismiss();
                    }
                }
                catch (Exception ex)
                {
                    Toast.MakeText(this, "" + ex.Message, ToastLength.Long).Show();
                }
            };
        }
Beispiel #4
0
        public async Task RequestRegisterUserAsync(string email, string name, string password)
        {
            if (String.IsNullOrEmpty(email))
            {
                Toast.MakeText(context, "Email cannot be null or empty", ToastLength.Short).Show();
                return;
            }

            if (String.IsNullOrEmpty(name))
            {
                Toast.MakeText(context, "Name cannot be null or empty", ToastLength.Short).Show();
                return;
            }

            if (String.IsNullOrEmpty(password))
            {
                Toast.MakeText(context, "Password cannot be null or empty", ToastLength.Short).Show();
                return;
            }

            //Create Dialog
            AlertDialog dialog = new EDMTDialogBuilder()
                                 .SetContext(context)
                                 .SetMessage("Please wait ..")
                                 .Build();

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

            //Create params to POST request
            Dictionary <string, object> data = new Dictionary <string, object>();

            data.Add("email", email);
            data.Add("name", name);
            data.Add("password", password);

            string result = await myAPI.RegisterUser(data);

            Toast.MakeText(context, result, ToastLength.Short).Show();

            if (dialog.IsShowing)
            {
                dialog.Dismiss();
            }
        }
Beispiel #5
0
        private async Task GetData()
        {
            var service = new Service.MyALService();

            Android.Support.V7.App.AlertDialog dialog = new EDMTDialogBuilder()
                                                        .SetContext(this)
                                                        .SetMessage(GetString(Resource.String.msg_please_wait)).Build();
            dialog.Show();
            var response = await service.GetFavoritesByUser(this, "Judasibe3991");

            if (!response.IsSuccess)
            {
                dialog.Dismiss();
                Toast.MakeText(this, response.Message, ToastLength.Short).Show();
                return;
            }
            Toast.MakeText(this, response.Result[0].Name, ToastLength.Short).Show();
            LoadData(response.Result);
            dialog.Dismiss();
        }
Beispiel #6
0
        /// <summary>
        /// API request
        /// </summary>
        public async void GetAPI()
        {
            if (cal > 305)
            {
                Android.Support.V7.App.AlertDialog dialog = new EDMTDialogBuilder()
                                                            .SetContext(this)
                                                            .SetMessage("Please wait...")
                                                            .Build();
                if (!dialog.IsShowing)
                {
                    dialog.Show();
                }
                string kcal = cal.ToString().Replace(",", ".");
                string url  = $"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/mealplans/generate?targetCalories=" + kcal + "&timeFrame=day";
                HttpResponseMessage response;
                HttpClient          client = new HttpClient();
                client.DefaultRequestHeaders.Add("X-RapidAPI-Host", "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com");
                client.DefaultRequestHeaders.Add("X-RapidAPI-Key", "01c79e8e04msh077fcd2b054ada6p1f3778jsn478f5faa097b");
                response = await client.GetAsync(url);

                meals = JsonConvert.DeserializeObject <Meals>(await response.Content.ReadAsStringAsync());
                Intent nextActivity = new Intent(this, typeof(GetDiet));
                nextActivity.PutExtra("calories", cal.ToString());
                nextActivity.PutExtra("bname", meals.meals[0].title);
                nextActivity.PutExtra("btime", meals.meals[0].readyInMinutes);
                nextActivity.PutExtra("lname", meals.meals[1].title);
                nextActivity.PutExtra("ltime", meals.meals[1].readyInMinutes);
                nextActivity.PutExtra("dname", meals.meals[2].title);
                nextActivity.PutExtra("dtime", meals.meals[2].readyInMinutes);
                if (dialog.IsShowing)
                {
                    dialog.Dismiss();
                }
                StartActivity(nextActivity);
            }
            else
            {
                Toast.MakeText(this, "Ошибка вычисления!", ToastLength.Long).Show();
            }
        }
Beispiel #7
0
        /// <summary>
        /// Get product id from API
        /// </summary>
        public async void GetProducts()
        {
            Android.Support.V7.App.AlertDialog dialog = new EDMTDialogBuilder()
                                                        .SetContext(this)
                                                        .SetMessage("Please wait...")
                                                        .Build();
            if (!dialog.IsShowing)
            {
                dialog.Show();
            }

            string url = "https://api.nutritionix.com/v1_1/search/" + item_name + "?brand_id=" + id + "&results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=a76fc23d&appKey=7ca7f97a063b60691f2446b4a5b3f543";
            HttpResponseMessage response;
            HttpClient          client = new HttpClient();

            response = await client.GetAsync(url);

            root = JsonConvert.DeserializeObject <RootObject>(await response.Content.ReadAsStringAsync());
            List <string> pList = new List <string>();

            foreach (var elem in root.hits)
            {
                pList.Add(elem.fields.item_name);
            }
            if (pList.Count == 0)
            {
                Toast.MakeText(this, "Ничего не найдено!", ToastLength.Long).Show();
            }
            else
            {
                var adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, pList);
                list.Adapter = adapter;
            }

            if (dialog.IsShowing)
            {
                dialog.Dismiss();
            }
        }
Beispiel #8
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            IHealthAPI healthAPI;

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

            SetContentView(Resource.Layout.bloodsugar_layout);

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

            LoadData();


            var btn_addBS    = FindViewById <Button>(Resource.Id.btn_addBloodSugar);
            var btn_deleteBS = FindViewById <Button>(Resource.Id.btn_deleteBloodSugar);
            var btn_loadBS   = FindViewById <Button>(Resource.Id.btn_loadBloodSugars);

            btn_loadBS.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 <BloodSugar> bs = await healthAPI.GetBloodSugars();

                    lstSource = bs.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_deleteBS.Enabled = true;
            };

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

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

                LoadData();
            };
        }
Beispiel #9
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)
            {
            }
        }
Beispiel #10
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();
            }
        }
        /// <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 #12
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();
                }
            };
        }