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

How to use SQLite with more than one tables

$
0
0

Using the sample and code from the "Xamarin.Forms Local Databases" sample, unable to post link.

The example is using Data/TodoItemDatabase.cs as the connection and CRUD operations.

The method below creates the Table 'TodoItem' if it does not exists.

How do you use this file if you have other tables in the database?

It seems the TableMappings is coming from the file name.

       async Task InitializeAsync()
        {
            if (!initialized)
            {
                if (!Database.TableMappings.Any(m => m.MappedType.Name == typeof(TodoItem).Name))
                {
                    await Database.CreateTablesAsync(CreateFlags.None, typeof(TodoItem)).ConfigureAwait(false);
                    initialized = true;
                }
            }
        }

Doesn't make sense to create such a class for each table, since we want to use one connection to the DB file.


How to pass an Android Intent to another application from Xamarin Forms

$
0
0

// This method makes your ResultReceiver safe for inter-process communication

    private ResultReceiver buildIPCSafeReceiver(ResultReceiver actualReceiver) {
     Parcel parcel = Parcel.obtain();
     actualReceiver.writeToParcel(parcel, 0);
     parcel.setDataPosition(0);
     ResultReceiver receiverForSending = ResultReceiver.CREATOR.createFromParcel(parcel);
     parcel.recycle();
     return receiverForSending;
}

Button templatePrint = (Button) findViewById(R.id.templatePrint);
templatePrint.setOnClickListener(new View.OnClickListener() {
 @Override
    public void onClick(View v) {
        // Define a hash map of variable data
        // Strings used for keys will be replaced by their corresponding values in your template file's ZPL
        HashMap<String, String> variableData = new HashMap<>();
         variableData.put("%PRODUCT_NAME%", "Apples");
         variableData.put("%MSRP%", "$1.00");
         variableData.put("%PCT%", "50");
         variableData.put("%FINAL%", "$0.50");
         variableData.put("%UPC_CODE%", "12345678");
         Intent intent = new Intent();
         intent.setComponent(new ComponentName("com.zebra.printconnect",
        "com.zebra.printconnect.print.TemplatePrintService"));
         intent.putExtra("com.zebra.printconnect.PrintService.TEMPLATE_FILE_NAME", "PriceTagTemplate.zpl");
         intent.putExtra("com.zebra.printconnect.PrintService.VARIABLE_DATA", variableData);
         intent.putExtra("com.zebra.printconnect.PrintService.RESULT_RECEIVER", buildIPCSafeReceiver(new
        ResultReceiver(null) {
            @Override
                 protected void onReceiveResult(int resultCode, Bundle resultData) {
                 if (resultCode == 0) { // Result code 0 indicates success
                 // Handle successful print
                 } else {
                 // Handle unsuccessful print
                // Error message (null on successful print)
                String errorMessage = resultData.getString("com.zebra.printconnect.PrintService.ERROR_MESSAGE");
                }
        }
    }));
    startService(intent);
    }
});

ON/OFF of GPS reception

$
0
0

As shown in the code below, when you press (Start) (GPSStart_Clicked) or end (GPSStop_Clicked), you may not receive, or the reception may not end.

private void GPSStart_Clicked(Object sender, EventArgs e)
{
    _ = StartListening();
}

private void GPSStop_Clicked(Object sender, EventArgs e)
{
    _ = StopListening();
}

public async Task StartListening()
{
    if (CrossGeolocator.Current.IsListening)
        return;
    await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(1000), 1, false);
    CrossGeolocator.Current.PositionChanged += PositionChanged;

}

public async Task StopListening()
{
    if (!CrossGeolocator.Current.IsListening)
        return;
    await CrossGeolocator.Current.StopListeningAsync();
    CrossGeolocator.Current.PositionChanged -= PositionChanged;
}

private void PositionChanged(object sender, PositionEventArgs e)
{
    ~~~~~~~~~~~~~~~~~~~~
}

App deploys to iOS simulator but not to iPad Pro

$
0
0

I've got an App that I would like to test on my iPad Pro 12.9" (first generation, iOS 13.5.1). I am able to deploy it to a simulator but when I try to deploy it to my device Visual Studio 2019 Pro on Windows gives an error when building (not deploy):

Severity Code Description Project File Line Suppression State
Error Error while loading assemblies: /Users/paulsinnema/Library/Caches/Xamarin/mtbs/builds/eTabber.iOS/576cbcad2fb4a8344d3b1823e4c08bc2/bin/iPhone/Debug/git2-106a5f2.dll eTabber.iOS C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Xamarin\iOS\Xamarin.iOS.Common.targets 844

The path /Users/paulsinnema/Library/Xamarin/ exists but there no mtbs inside it.

Using: iPad connected via network (not cable, because the Mac Mini I'm using is in the Attic).

iOS Build
SDK Version: Automatic
Linker behavior: Link All
Supported Architecture: ARM64
HttpClient implementation: Managed (default)
Use LVVM optimizing compiler: false
Enable the Mono interpreter: true
Perform all32-bit float operations as 64-bit float: true
Strip native debugging symbols: true
Enable incremental builds: false
Use the concurrent garbage collector: true
Enable device-specific builds: false

iOS Bundle signing
Scheme: Automatic Provisioning

Build
Platform target: x64
Output path: bin\iPhone\Debug\

My Xamarin app crash after 5 secedes

$
0
0

06-07 19:01:32.416 I/ame.shobiklobi(14434): Explicit concurrent copying GC freed 3(16KB) AllocSpace objects, 0(0B) LOS objects, 75% free, 1988KB/8132KB, paused 39us total 11.546ms
06-07 19:01:32.417 D/Mono (14434): GC_TAR_BRIDGE bridges 32 objects 32 opaque 0 colors 32 colors-bridged 32 colors-visible 32 xref 0 cache-hit 0 cache-semihit 0 cache-miss 0 setup 0.07ms tarjan 0.01ms scc-setup 0.01ms gather-xref 0.00ms xref-setup 0.00ms cleanup 0.03ms
06-07 19:01:32.417 D/Mono (14434): GC_BRIDGE: Complete, was running for 12.37ms
06-07 19:01:32.417 D/Mono (14434): GC_MAJOR_CONCURRENT_FINISH: (finishing) time 323.55ms, stw 113.13ms los size: 2048K in use: 1036K
06-07 19:01:32.417 D/Mono (14434): GC_MAJOR_SWEEP: major size: 102400K in use: 92364K

Android and iOS scale totally different. Do I need styling?

$
0
0

I've created an App I call eTabber and it show guitar tabs in Android, iOS en UWP. I currently working on the iOS version and it seems to scale totally different from the Android version. That is not what I expected at all. Here are two samples. It is a complex application using a ChordPro parser that parses a text file containing ChordPro text. It then passes control to a TabContainer class that evaluates the ChordPro tree and creates a Xamarin.Forms control with content coming from code. The Andoid version has a bit too much spacing but further look allright. The iOS version doesn't look good at all.

To make a bit more clear what is what. The colored images show a ColumnLayout (which is one of my own layout classes) in Green and a FlexLayout in Yellow. The ColumnLayout is working fine b.t.w.

Here's the Android layout:

and here's the iOS layout:

Here's the code for the word with or without a Chord (the black background blocks).

        private void HandleBlocks(ILine line, Layout<View> layout, IEnumerable<Block> blocks, bool inline = false)
        {
            if (!blocks.Any())
            {
                var label = CreateLabel(line, string.Empty, UseColor);
                layout.Children.Add(label);
            }
            else
            {
                foreach (var block in blocks)
                {
                    switch (block.GetType().Name)
                    {
                        case nameof(Chord):
                            HandleChord(line, layout, (Chord)block);
                            break;

                        case nameof(Word):
                            HandleWord(line, layout, (Word)block, inline);
                            break;

                        default:
                            break;
                    }
                }
            }
        }

        private void AddSpace(ILine line, Layout<View> layout)
        {
            Label label = CreateLabel(line, string.Empty, UseColor);
            label.Padding = new Thickness(0, 0, 2, 0);
            layout.Children.Add(label);
        }

        private void HandleWord(ILine line, Layout<View> layout, Word word, bool inline)
        {
            foreach (var syllabe in word.Syllables)
            {
                var chordLayout = new StackLayout
                {
                    Orientation = StackOrientation.Vertical,
                    Spacing = 0,
                    StyleClass = new List<string> { "WordContainer" }
                };

                if (syllabe.Chord != null)
                {
                    HandleChord(line, chordLayout, syllabe.Chord);
                }
                else
                {
                    if (!inline)
                    {
                        var emptyLabel = CreateLabel(line, string.Empty, UseColor);
                        chordLayout.Children.Add(emptyLabel);
                    }
                }

                var label = CreateLabel(line, syllabe.Text ?? string.Empty, UseColor);
                chordLayout.Children.Add(label);

                layout.Children.Add(chordLayout);
            }

            AddSpace(line, layout);
        }

        private void HandleChord(ILine line, Layout<View> layout, Chord chord)
        {
            var text = chord.Text == null ? string.Empty : $" {chord.Text}";
            var label = CreateLabel(line, text, bold: true, textColor: ChordColor);
            layout.Children.Add(label);
        }

TouchEffect is not raised when TapGestureRecognizer is enabled

$
0
0

Hi all,

I my "Custom" View I have the following TapGestureRecognizer:

            var tapGestureRecognizer = new TapGestureRecognizer();
            tapGestureRecognizer.Tapped += async (s, e) =>
            {
                await this.BlinkAnimation();
                Clicked?.Invoke(s, e);
            };
            GestureRecognizers.Add(tapGestureRecognizer);

But when I add this code View becomes untouchable !!
TouchEffect is used from https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/effects/touch-tracking

But when I comment out this code TouchEffect has been raised ...

But I need TapGestureRecognizer and TouchEffect to work simultaneously !!

Is there a way to do this ?

low speed site

$
0
0

I have a problem with my site: www.irpolymer.com/
The GTMetrix shows that something is slowing it down. But no matter how hard I tried, I couldn't find it if I didn't have this problem on other sites


Is there a way to send data from View Model to code behind?

$
0
0

Is there a way to send data from View Model to code behind?

PDFSharp.netstandard - XFont Operation is not supported on this platform.

$
0
0

Hi all,

I want to use PDFSharp.netstandard on Android and iOS to create and save a PDF-file (not viewing), but I get a error which I cannot place.

I have the following example code:

But now I get the following error when I want to create this PDF:

Does someone know how to use this on Android and iOS?

Corner radius in relative layout

$
0
0

Hello, I am using a relative layout to display round buttons. I use the width property to make it responsive, but I don't get the corner radius responsive. It looks good on the iPhone 11 Pro, but on the iPhone SE is the radius too high. How can I make it reponsive? Here a screenshot of the iPhone 11 Pro and SE:

Here is my code:

        <RelativeLayout x:Name="mainLayout">

            <Button Text="Button" TextColor="White" CornerRadius="40" BackgroundColor="Gray" RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.2}" RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.2}"/>

    </RelativeLayout>

Is there any solution for this? Thanks in advance.

Two listviews on one page

$
0
0

Hi All,

I've seen several topics on this, but none of them worked for me (or I cannot make it work for me): how to add two listviews with separate data on one page?

In my case, I want two listviews under each other. I have one listview already inside a grid. The code for this listview is:

How can I add a second listview under this current listview?

How generate a layout with a Button ?

$
0
0
Hello, I'm looking for a way to generate on a page (let's call it ArticlePage) a stacklayout that would have entries thanks to a button (let's call it Add), and when generating it, we stay on the ArticlePage, the stack is added with the Add button underneath and so on... I don't really see how I can make something clean, an idea ? Thank you!

How can I set StyleSheet by platform?

$
0
0

How can I set StyleSheet by platform?

Code:
<StyleSheet Source="{OnPlatform iOS=Styles/AppStylesIos.css, Android=Styles/AppStylesAndroid.css}"/>

Error: Position 6:10. Source property is not a string literal

How to Play Vimeo Video with Webview in Xamarin Forms (Issue with Andriod)

$
0
0

Hello,

I would like to play Vimeo video using Webview in xamarin forms. I have taken iframe and using it load in webview.Video started however I'm facing two issues only in Andriod while for IOS it working fine.
1. Full Screen option missing.
2. After 2-3 sec play stop button hide and then after I'm not able to stop the video.

I have tried two approaches:
1. In Form view taken webview and in xaml.cs give the source in iframe and html.
2. I have created custom webview.

I'm Attaching both approach's code here.

Please have a look and help me to find the solution.

Thanks,
Ankit Gandhi.


Xamarin.Forms videoplayer - how to do a loop?

$
0
0

I am looking at the new Video Player in Xamarin.Forms and I am wondering how do you make a video keep looping?

Thanks.

OnResume/OnSleep do not fire on UWP

$
0
0

I have a cross-plat app that i have created (load a webview by passing lat/long)
I would like to refresh my app by sending latest position each time the user resumes the app.
The code below works fine on iPad, but on my lumia 950 the onresume/onsleep never fires when i hit back button or hit home button on my phone.
The only time the onsleep fires is when i hold the back button and terminate the app using the X

Also is there a better way to refresh the webview by passing new position then doing it onresume?

public class App : Application
{
    public App()
    {


        var navPage = new NavigationPage(new WebPage());

        MainPage = navPage;
    }


    protected override void OnStart()
    {

        NavigationPage.SetHasNavigationBar(this, false);

        Debug.WriteLine("Started");

    }

    protected override void OnSleep()
    {
        Debug.WriteLine("Slept");

    }

    protected override void OnResume()
    {
        Debug.WriteLine("Resumed");
        var navPage = new NavigationPage(new WebPage());

        MainPage = navPage;

    }

}

Xamarin Webview Cookies property

$
0
0

Hi,
in the docs I read that "which is then set as the value of the WebView.Cookies bindable property":

webView.Cookies = cookieContainer;

But I get an error, since there's no Cookies property for WebView... I found that setting cookies can only be achieved with Custom Renderer, but then WHY says the docs otherwise?
Sorry I can't post a link, but here's the URL
https:// docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/webview?tabs=windows#cookies

SelectionChangedCommand issue on CollectionView

$
0
0

In my app from main page when I select an Item it navigates to next page as per selected Item ID, but when I return back to main page and try select same Item again, I can't select same Item,
Note: this is happening only with Xamarin Forms CollectionView, but with ListView it works fine,
Latest version I;m using
Microsoft Visual Studio Enterprise 2019
Version 16.6.2
Xamarin 16.6.40
Android SDK 10.3.1.4
XamariniOS 13.18.2

AppThemeBinding not working

$
0
0

Hi,
Using latest Xamarin Forms 4.7.0.968.
SfButton.BackgroundColor="{AppThemeBinding Light={StaticResource PrimaryColorLight}, Dark={StaticResource PrimaryColorDark }}"
is not working.
Thank you

Viewing all 79144 articles
Browse latest View live


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