Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 91519 articles
Browse latest View live

Firebase Cloud Messaging (When App is closed or just opened)

$
0
0

I was wondering, I have managed to implement the currently in beta xamarin firebase messaging into an PCL app. it works as intended when sending a message while the app is in the foreground and in the background but if the app is closed using background applications task manager the message doesn't seems to miss the app. I was wondering if any one has any pointers or knows how to send a message to an app while closed or if firebase is able to hold a message until the app is opened?


Auto Complete using Xamarin Forms in C#

$
0
0

Hi,

I am trying to create a AutoComplete Text Entry using Xamarin Forms.
Can anybody help me in creating a custom renderer for the auto complete text field in C#.
I am using MVVM concept.

NavigationPage - Remove a page from the "back stack"

$
0
0

Hello everyone!

First of all i would like to say I am loving the new updates!

Ok, so I am working on an application that I do some processing during load of the application so I start on a Splash Screen. Once the processing is complete I take the user to one of two other Pages depending on the results of my processing. This works wonderfully.... except that I push the Splash Screen onto a NavigationPage in my GetMainPage function call as I want to use the Navigation page for the rest of the application. What this allows the user to do is hit their back button from the page I push them on to and it takes them back to the Splash Screen! I am in search of a way to make the navigation page essentially ignore the Splash Screen page. I thought of two ways this is possible but am not sure if either are possible...

  1. Don't use the NavigationPage in the GetMainPage call. Use some other Page type to display the Splash Screen. Once I am ready to move on switch to a NavigationPage then. I think this would be awesome except that I don't know if I can do it... is it possible to change to a NavigationPage after handing a different type on the GetMainPage function call?
  2. Have a function call to either erase the Navigation History or purge a specific page from the history. I did not see any way to do this unless I missed something...

Any help on keeping a page out of the navigation history would be greatly appreciated!

Can you open a native webpage with cookies?

$
0
0

I've currently got a WebView with cookies assigned but I need to change this to open a webpage instead. Is there a way to pass cookies up to the page?

UWP not searching Bluetooth LE

$
0
0

Hi everyone

Currently I'm working on a small test-project that will scan for Bluetooth and Bluetooth Low Energy devices, but the application is not finding any BLE-device. What am I doing wrong?

To search for every device I'm using the following code:

public async Task StartScanning()
{
    var collection = await DeviceInformation.FindAllAsync();

    _devices = new ObservableCollection<MyBluetoothLEDevice>();

    foreach (var item in collection)
    {
        var device = new MyBluetoothLEDevice(item.Name);

        if (DeviceAlreadyDiscovered(device)) continue;

        _devices.Add(device);
    }
}

This is finding a lot of devices, but no BLE. Another approach I tried:

public async Task StartScanningLE()
{
    var collection = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector());

    _devices = new ObservableCollection<MyBluetoothLEDevice>();

    foreach (var item in collection)
    {
        var device = new MyBluetoothLEDevice(item.Name);

        if (DeviceAlreadyDiscovered(device)) continue;

        _devices.Add(device);
    }
}

This time nothing is found. I've also tried the following:

public void StartScanningWatcher()
{
    var watcher = new BluetoothLEAdvertisementWatcher();

    /*
    var manufacturerData = new BluetoothLEManufacturerData()
    {
        CompanyId = 0x010E
    };
    watcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData);
    watcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(500);
    */

    watcher.Received += Watcher_Received;

    watcher.Start();
}

private void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
    /*
    foreach (var item in args.Advertisement.GetManufacturerDataByCompanyId(0x010E))
    {
        using (var dataReader = DataReader.FromBuffer(item.Data))
        {
            var length = dataReader.ReadInt32();

            this.currentRegistration = dataReader.ReadString((uint)length);
            this.currentSignalStrength = args.RawSignalStrengthInDBm;
        }
    }
    */
}

But the event Watcher_Received is never called... How is this possible?

I know my Windows 10-device can find BLE-devices, since they show up in "Settings" of Windows 10... What is wrong with my application?

Forms solution, InternalsVisibleTo attribute in AssemblyInfo.cs, still can't access in iOS project.

$
0
0

Endless weird things.

In Visual studio 2015, iOS project can not access internals in Forms portable project. Solution can not build.

Environment:
VS 2015,
Xamarin 4.2.2.6
Xamarin.iOS 10.3.1.7

Repro:
Visual Studio 2015, start a new Xamarin Forms solution.
In Portable project:
Create a static class with a static string field.
Create InternalsVisibleTo attribute in Assembly.cs.
In iOS project:
Simple call that static class just created, error showing "classname is inaccessible due to its protection level". Project can not build with the same error msg.

Anyone has the same issue? Any suggestions please? Thanks in advance.

Btw, I have tried restart VS multi times, delete recreate project multi times.

App1\App.cs

internal static class Helper
{
    internal const string name = "";
}
public class App : Application
{
    public App()
    {
        // The root page of your application
        MainPage = new ContentPage
        {
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                Children = {
                    new Label {
                        HorizontalTextAlignment = TextAlignment.Center,
                        Text = "Welcome to Xamarin Forms!"
                    }
                }
            }
        };
    }

    protected override void OnStart()
    {
        // Handle when your app starts
    }

    protected override void OnSleep()
    {
        // Handle when your app sleeps
    }

    protected override void OnResume()
    {
        // Handle when your app resumes
    }
}

App1\Properties\AssemblyInfo.cs

// Just in case I'm missing something.
[assembly: InternalsVisibleTo( "App1.iOS" )]
[assembly: InternalsVisibleTo( "App1" )]
[assembly: InternalsVisibleTo( "iOS" )]

App1.iOS\Main.cs

public class Application
{
    // This is the main entry point of the application.
    static void Main( string[] args )
    {
        // if you want to use a different Application Delegate class from "AppDelegate"
        // you can specify it here.
        UIApplication.Main( args, null, "AppDelegate" );

        var a = Helper.name;  // Error here.
    }
}

Adding Dropdown with Dynamic data [Picker] Also Getting data through WebAPI

$
0
0

Model is here :
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XamarinWebServices.Models
{
public class CustomerViewModel
{
public int id { get; set; }
public string name { get; set; }
}

// ViewModel:
public class CustomerVM
{
    public CustomerViewModel Data { get; set; }
    public ObservableCollection<CustomerViewModel> CustomerList { get; set; }

    public CustomerVM()
    {
        CustomerList = new ObservableCollection<CustomerViewModel>();
    }
}

}

XAML file for Picker (Dropdown) :
<?xml version="1.0" encoding="utf-8" ?>

</Picker.Items>
</Picker>


And here is the codeBehind with dynamic data through link [Working with Web Api in Xamarin.forms]:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using XamarinWebServices.Models;

namespace XamarinWebServices
{
public partial class DropDown : ContentPage
{
CustomerVM viewModel;
public DropDown()
{
InitializeComponent();

        viewModel = new CustomerVM();
        BindingContext = viewModel;
    }

     async override protected void OnAppearing()
    {
        base.OnAppearing();
        var json = await GetCustomersAsync();
        List<CustomerVM> customers = JsonConvert.DeserializeObject<List<CustomerVM>>(json);
        foreach (CustomerVM c in customers)
        {
            if (c.Data != null)
            {
                string name = c.Data.name;
                int ID = c.Data.id;

                CustomerViewModel v = new CustomerViewModel();
                v.name = name; v.id = ID;
                CustomerList.Items.Add(name);
                viewModel.CustomerList.Add(v);
            }
        }

    }

    async Task<string> GetCustomersAsync()
    {
        var client = new HttpClient();

        client.BaseAddress = new Uri("http://www.doctorksa.com/webservices/");

        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.GetAsync("country");
        if (response.IsSuccessStatusCode)
        {
            string result = await response.Content.ReadAsStringAsync();
            return result;
        }
        else return response.ReasonPhrase;
    }
    void CustomerList_SelectIndexChanged(object sender, EventArgs args)
    {
        DisplayAlert("Test", "Ok", "Cancle", "Confirm");
    }

}

}

Hope this will help you in working with dropdown and Web API

How to set the maximum tabs per page in Xamarin TabbedPage?

$
0
0

In my Tabbed page titles are too long..

So I want to restrict the maximum tabs count=4 to maximum count=2.

How to set the maximum tabs per page in Xamarin TabbedPage?


Check whether GPS is Enabled or not on each Platform? If not then Open Setting on device?

$
0
0

Hello, I am new with Xamarin.Forms. I am using plugin Plugin.Geolocator . I want to check whether GPS is enabled or not? If not then Open Settings on devices. How to achieve it?
Code is here

` public async void GetGPSLocation()
        {
            try
            {
                var locator = CrossGeolocator.Current;
                locator.DesiredAccuracy = 50;

                var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
                var latitude = position.Latitude;
                var longitude = position.Longitude;
                await DisplayAlert("Notification ", "Latitude is " + latitude + " Longitude is " + longitude, "Ok");
            }
            catch (Exception ex)
            {
                await DisplayAlert("Notification", "Unable to get GPS Location " + ex, "Ok");
            }
        }`

Pressing buttons multiple times loads multiple pages (Android)

$
0
0

I'm having an issue with Android navigation. I have a list view that contains a bunch of items that have tapped events. These tapped events look like this:

    async void Tab_ItemSelected(object sender, ItemSelectedEventArgs e)
    {
        var details = new DetailPage(e.SelectedItem.ID);
        await Navigation.PushAsync(details);
    }

This works on iOS and Windows Phone just fine, but if you're quick enough, it will load two detail pages onto the stack. This also seems to occur quite a few places on our Android application. Is there any way around this?

Xamarin.Forms with MVC Web API

$
0
0

Hello, I am having a hard time figuring out how to communicate back and forth between Xamarin.Forms and my Web API controller. I am able to hit my controller, but do not know how to use the response. Am I on the right track? I've had a hard time finding examples for controller back mobile project code. Here are the relevant snippets:

    //Project Mobile Side
    public void onLoginClicked (object sender, EventArgs e)
            {
                var url = BaseUrl + "/loginapi/login?username=" + eUserName.Text + "&password=" + ePassword.Text;

                var request = WebRequest.Create(url);
                request.BeginGetResponse(loginReturn, request);

            }

    //API Controller in MVC project
    public HttpResponseMessage Login(string userName, string password)
            {
                t_user user = new t_user();
                try
                {
                    var vUser = (from u in db.t_user
                                where u.email == userName && u.password == password
                                select new { u }).FirstOrDefault();

                    if (vUser == null)
                    {
                        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
                    }
                    FormsAuthentication.SetAuthCookie(userName, true);
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, vUser);
                    return response;
                    //return Json(vUser);
                }
                catch (Exception x)
                {
                    return null;
                }
            }

    //Project Mobile Side
    void loginReturn(IAsyncResult result)
            {
                var request = result.AsyncState as HttpWebRequest;
                HttpWebRequest test = (HttpWebRequest)result.AsyncState;

                try
                {
            //Tried multiple things here but get nothing I can use.
                    //var response = request.EndGetResponse(result);
                    //Stream test2 = response.GetResponseStream();
                    ////test2.Read();
                    //ad.RenderStream(response.GetResponseStream());
                }
                catch(Exception e)
                {
                    Debug.WriteLine(e);
                }
            }

How to catch a user entering the child of a tabbed page?

$
0
0

I've got a potentially quite simple question:

How do catch the event when a user enters a particular child in a tabbed page?

In my case I've got one tabbed page (SetFoundationPage) who is the parent of three children (CreateFoundation, UpdateFoundation and DeleteFoundation).

I want to display a DisplayAlert when a user enters the DeleteFoundation and in that case ONLY.

I've got this code in DeteleFoundation.xaml.cs:

namespace App3
{
    public partial class DeleteFoundation : ContentPage
    {
        public DeleteFoundation()
        {
            InitializeComponent();
            DisplayAlert("Danger zone", "You are entering the danger zone. Be fucking careful here.\nLive data ahead.", "OK");
        }
    }
}

I assumed that InitializeComponent() would be invoked when the user enters the page. But it would seem as if it gets invoked as the user goes into the parent (ie. the UI thread initializes all children when the parent has been entered).

Are there any particular events or similar methods I can catch to (a)wait until the childpage (DeleteFoundation) has been properly entered?

Rest API call with xamarin.forms

$
0
0

Hi I'm a newbie to xamarin.forms. I need to make a REST API call with simple json request as username and password which has been entered by the user.
Can anyone guide me how to do that ? What are all the components or tools i need to import to make a API Call.

Drop down control

$
0
0

How can I get a drop down control as the attached image shows in Xamarin Forms ?

Regards

Rolf Hjemdahl

RadioButton And DropDown List

$
0
0

In Xamarin.Forms, Which control is used for RadioButton, Group RadioButton And DropDown List?


SearchBar and FloatingActionButton

$
0
0

I use FloatingActionButton on the listing page of my application, I also want to add a searchBar. But I could not show them that page. My codes and screenshot are down. How can I show the searchBar?

FAB Github

My Codes:


DataTemplate>
TextCell
Text="{Binding .}"
DataTemplate>
ListView.ItemTemplate
ListView
ContentView
fab:FloatingActionButton
x:Name="fabBtn"
Source="plus.png"
Size="Normal"
Clicked="Handle_FabClicked"
NormalColor="Green"
RippleColor="Red"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1, Constant=-75}"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=1, Constant=-75}"
RelativeLayout
ContentPage.Content
ContentPage>

Application.Properties and custom types

$
0
0

I have a custom type that's basically just a bunch of string properties. If I try to persist the object using Application.Properties (which is a Dictionary<string, object>) in Xamarin Forms, it doesn't work. I would try marking it as Serializable, but that isn't available in a PCL.

What are the requirements for these objects? Or am I limited to simple strings?

Multiline Title in Navigation Bar

$
0
0

Hello,

Is it possible to tweek navigation tool bar to have two line title (e.g. using custom page renderer)?

I need this only for Android platform.

Regards,
Novak

How to change "Back button" to "Menu" on MasterDetailPage? [Android]

$
0
0

Hi there! I'm facing the following issue:

I have a drawer menu (implemented with MasterDetailPage) with 3 items. When you first run the app you see an hamburger menu icon on top left.
When you click in one of these items, the page loads with an back arrow.
I'm trying to accomplish that these three pages must still have the hamburger menu item on its Action Bar. And the navigation after those, loads with the back button.

I ended up thinking that the Icon property for MasterPage won't work for Android.

I made it work on iOS but nothing I do seems to work on Android.

My code:

MainPage.cs

public class MainPage : MasterDetailPage
 {
        protected override void OnAppearing()
        {
            base.OnAppearing();
            this.GetMenuPage().ListView.ItemSelected += OnItemSelected;
        }
       private void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
       {
            var item = e.SelectedItem as Menu;
            if (item == null) return;
           // this.GetNavigationPage().PushAsync((Page)Activator.CreateInstance(item.Pagina));
            ((NavigationPage)this.Detail).PushAsync((Page)Activator.CreateInstance(item.Pagina));
            this.GetMenuPage().ListView.SelectedItem = null;
            IsPresented = false;
        }
  }

MenuPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="BNB.CapturaGeodesica.MenuPage"
             Padding="0,40,0,0"
             BackgroundColor ="#A5183C"
             Title="Menu "
             Icon="ic_hamburguer_menu"> <!-- ##  This works on iOS. But on Android, it won't show up. ##-->

DetailPage1.cs

public DetailPage1()
        {
            NavigationPage.SetHasBackButton(this, false); // Here I get rid of the back button. But I can't manage to show the menu icon on Android.
            InitializeComponent();
        }

I'm attaching the result on iOS and Android. Just to clarify, to reach "Second page" on iOS or Android, assume that I opened the drawer menu and selected "Second page".

OBS: I need to have the page history.

Thank you for any help!

  • this is my first post, if I messed it up, sorry -

Carousel View stop swipe

$
0
0

Hi all,

I do a carousel view with a map page. So on my map page i need to navigate on map but when i do a swipe my carousel change page.

So i need to disable swipe of carousel, but how i can do that ? GestureRecognizer of carousel view is empty .

Thanks in advance !

Viewing all 91519 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>