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

Android Camera WebView Image Upload ERR_FILE_NOT_FOUND

$
0
0

I am working on a simple app that views a webpage that has an area for a user to take pictures and upload them to the site.
I found some examples that look like this

 public class CustomWebViewRenderer : WebViewRenderer
    {
        Activity mContext;
        private static int FILECHOOSER_RESULTCODE = 1;
        public CustomWebViewRenderer(Context context) : base(context)
        {
            mContext = context as Activity;
        }
        protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
        {
            try
            {
                base.OnElementChanged(e);

                var chromeClient = new FileChooserWebChromeClient((uploadMsg, acceptType, capture) => {
                    MainActivity.UploadMessage = uploadMsg;

                    // Create MyAppFolder at SD card for saving our images
                    File imageStorageDir = new File(Android.OS.Environment.GetExternalStoragePublicDirectory(
                            Android.OS.Environment.DirectoryPictures), "MyAppFolder");

                    if (!imageStorageDir.Exists())
                    {
                        imageStorageDir.Mkdirs();
                    }

                    // Create camera captured image file path and name, add ticks to make it unique 
                    var file = new File(imageStorageDir + File.Separator + "IMG_"
                        + DateTime.Now.Ticks + ".jpg");

                    MainActivity.mCapturedImageURI = Android.Net.Uri.FromFile(file);

                    // Create camera capture image intent and add it to the chooser
                    var captureIntent = new Intent(MediaStore.ActionImageCapture);
                    captureIntent.PutExtra(MediaStore.ExtraOutput, MainActivity.mCapturedImageURI);

                    var i = new Intent(Intent.ActionGetContent);
                    i.AddCategory(Intent.CategoryOpenable);
                    i.SetType("image/*");

                    var chooserIntent = Intent.CreateChooser(i, "Choose image");
                    chooserIntent.PutExtra(Intent.ExtraInitialIntents, new Intent[] { captureIntent });

                    (mContext).StartActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
                });

                Control.SetWebChromeClient(chromeClient);
            }
            catch (Exception ex)
            {
                var j = ex;                
            }            
        }
    }

 public class FileChooserWebChromeClient : WebChromeClient
    {
        private Action<IValueCallback, Java.Lang.String, Java.Lang.String> callback;

        public FileChooserWebChromeClient(Action<IValueCallback, Java.Lang.String, Java.Lang.String> callBack)
        {
            callback = callBack;
        }

        // For Android < 5.0
        [Java.Interop.Export]
        public void openFileChooser(IValueCallback uploadMsg, Java.Lang.String acceptType, Java.Lang.String capture)
        {
            callback(uploadMsg, acceptType, capture);
        }

        // For Android > 5.0
        public override Boolean OnShowFileChooser(Android.Webkit.WebView webView, IValueCallback uploadMsg, WebChromeClient.FileChooserParams fileChooserParams)
        {
            try
            {
                callback(uploadMsg, null, null);
            }
            catch (Exception ex)
            {
                var j = ex;
            }
            return true;
        }
    }

Added this to the MainActivity

public static Android.Webkit.IValueCallback UploadMessage;
private static int FILECHOOSER_RESULTCODE = 1;
public static Android.Net.Uri mCapturedImageURI;
protected override void OnActivityResult(int requestCode, Result resultCode, Android.Content.Intent data)
        {
            if (requestCode == FILECHOOSER_RESULTCODE)
            {
                if (null == UploadMessage)
                    return;

                Java.Lang.Object result;

                if (data != null && data.Data != null)
                    result = data.Data;
                else
                    result = mCapturedImageURI;

                UploadMessage.OnReceiveValue(new Android.Net.Uri[] { (Android.Net.Uri)result });
                UploadMessage = null;
            }
            else
                base.OnActivityResult(requestCode, resultCode, data);
        }

This works fine on older versions of Android but when I loaded it up on Android 8, I get the message "ERR_FILE_NOT_FOUND" from the website.
I feel like I'm close, but missing something small to make this work.


How to run Xamarin.Forms on Windows 7?

$
0
0

I used the WPF platform setup // docs.microsoft.com documentation

I created a project based on a Visual Studio template.
I added the WFP project to the solution.
I'm running debugging.
The result: see the Picture-2.

I use.

  • Win 7 x64;
  • Microsoft Visual Studio Community 2019-16.8.4;

AppShell.xaml code

<?xml version="1.0" encoding="UTF-8"?>
<Shell xmlns="http://xamarin.com/schemas/2014/forms" 
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:local="clr-namespace:App1.Views"
       Title="App1"
       x:Class="App1.AppShell">

    <!--
        The overall app visual hierarchy is defined here, along with navigation.

        https://docs.microsoft.com/xamarin/xamarin-forms/app-fundamentals/shell/
    -->

    <Shell.Resources>
        <ResourceDictionary>
            <Style x:Key="BaseStyle" TargetType="Element">
                <Setter Property="Shell.BackgroundColor" Value="{StaticResource Primary}" />
                <Setter Property="Shell.ForegroundColor" Value="White" />
                <Setter Property="Shell.TitleColor" Value="White" />
                <Setter Property="Shell.DisabledColor" Value="#B4FFFFFF" />
                <Setter Property="Shell.UnselectedColor" Value="#95FFFFFF" />
                <Setter Property="Shell.TabBarBackgroundColor" Value="{StaticResource Primary}" />
                <Setter Property="Shell.TabBarForegroundColor" Value="White"/>
                <Setter Property="Shell.TabBarUnselectedColor" Value="#95FFFFFF"/>
                <Setter Property="Shell.TabBarTitleColor" Value="White"/>
            </Style>
            <Style TargetType="TabBar" BasedOn="{StaticResource BaseStyle}" />
            <Style TargetType="FlyoutItem" BasedOn="{StaticResource BaseStyle}" />
        </ResourceDictionary>
    </Shell.Resources>

    <TabBar>
        <ShellContent Title="About" Icon="icon_about.png" Route="AboutPage" ContentTemplate="{DataTemplate local:AboutPage}" />
        <ShellContent Title="Browse" Icon="icon_feed.png" ContentTemplate="{DataTemplate local:ItemsPage}" />
    </TabBar>

    <!--
        If you would like to navigate to this content you can do so by calling
        await Shell.Current.GoToAsync("//LoginPage");
    -->
    <TabBar>
        <ShellContent Route="LoginPage" ContentTemplate="{DataTemplate local:LoginPage}" />
    </TabBar>
</Shell>

Picture-1

Picture-2

Can I sort an ObservbleCollection using linq in a getter?

$
0
0

Hello, I have a list in a custom class, I would like to automatically return a sorted version of the list.
The best way I could accomplish this that I can think of is like this.
The alternative way would be to overload the SetProperty call to perform the sort and reassignment internally, but am not sure if that would cause cyclic loop condition.

public class ItemListDataType : EventParent //Overloads the property event handlers
{
    //These all have property fields but are excluded for space here
    public string szName;
    public string szModel;
    public string szType;
}

public class ItemListDataType : EventParent //Overloads the property event handlers
{
    //these have properties but are excluded for saving space
    private MyItemClass item; 
    private string myItemTitle;

    private ObservableCollection<ItemListDataType>  itemList

    public ObservableCollection<ItemListDataType> ItemList
        {
        //This line is throwing a 'specified cast not valid'
            get => (ObservableCollection<ItemListDataType >)itemList.OrderBy(x => x.item.szType).OrderBy(x => x.item.szModel);

            set
            {
                SetProperty(ref itemList, value, nameof(ItemList));
                OnPropertyChanged(nameof(ItemList));
            }
        }

    public ItemListDataType (MyItemClass t1, string t2)
    {
        this.item.Add(t1);
        this.myItemTitle = t2;
    }

    public ItemListDataType (MyItemClass t1)
    {
        this.item.Add(t1);
        this.myItemTitle = string.Format($"{t1.szType} {t1.szName} {t1.szModel}");
    }
}

I am using this class for populating a combobox with custom labels to custom my data type.
This code gets used like this

//I do this in this manner to cause the call to wait for the refresh to finish to ensure that the list is fully populated
//I am considering consolidation the assignment into the function, but am worried it will return before the list is populated
viewModel.ItemsInventoryList= await viewModel.RefreshItemDataList();

var list = new ItemListDataType (viewModel.ItemsInventoryList);

    cbInventory.DataSource = list.ItemsList;
    cbInventory.DisplayMemberPath = "MyItemTitle";

the prototype for the ItemsInventoryList is this

public async Task<ObservableCollection<MyItemClass >> RefreshItemDataList()
    {
        return await itemRepo.GetItems();
    }

So I guess this technically is two questions in one.
I'm sure that there is some simple cast that I am overlooking...

Xamarin forms Exoplayer set pitch little higher and little lower from default.

$
0
0

I am working with xamarin forms ,used Exoplayer to play audio. I want to set pitch (default, little lower & little higher).
My code:

float pitch=1f;
float speed=1f;
PlayerEventListener listerner;
SimpleExoPlayer _player = ExoPlayerFactory.NewSimpleInstance(_context, defaultTrackSelector);
_player.AddListener(listerner);
_player.Prepare(extractorMediaSource);
_player.PlayWhenReady = true;
PlaybackParameters param = new PlaybackParameters(speed,pitch);
_player.PlaybackParameters=param;

My code working successfully.
But for default, little lower & little higher, can any one tell me what are these pitch values?
Thanks...

Trying to implement Ads in a Forms project (Android for now, iOS down the road)

$
0
0

I'm trying to implement ads in my app, and eventually in-app purchases (to register a full version upgrade from free)

I've been following the tutorial from this site
https://www.c-sharpcorner.com/article/google-admob-display-ads-in-xamarin-forms/

I've created my AdMob Account, and added my app, I have the adUnitID, and from what I can tell that part is completed properly.

The problem I am having is when I try to compile the code, I get missing AndroidX assemblies,

Here is the specific error I am getting

Could not find 8 Android X assemblies, make sure to install the following NuGet packages:
 - Xamarin.AndroidX.Lifecycle.LiveData
 - Xamarin.Google.Android.Material
 - Xamarin.AndroidX.Legacy.Support.V4

(Please note it says 8 but only lists 3 assemblies)

I've tried installing those assemblies. Once they are installed I get two errors when I try to build.

one is
1>C:\Users\jesse\OneDrive\Documents\Source\...\obj\Debug\90\lp\124\jl\res\values\values.xml(1778): error APT2000: expected enum but got (raw string) slide.

Which is this line in the code

<item name="animationMode">slide</item>

And the other error is
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Xamarin\Android\Xamarin.Android.Aapt2.targets(164,3): error APT2062: failed linking references.

This is the linking reference it refers to.

<Aapt2Link
      Condition=" '$(_AndroidResourceDesignerFile)' != '' And '$(_AndroidUseAapt2)' == 'True' "
      ContinueOnError="$(DesignTimeBuild)"
      DaemonMaxInstanceCount="$(Aapt2DaemonMaxInstanceCount)"
      DaemonKeepInDomain="$(_Aapt2DaemonKeepInDomain)"
      ResourceNameCaseMap="$(_AndroidResourceNameCaseMap)"
      AssemblyIdentityMapFile="$(_AndroidLibrayProjectAssemblyMapFile)"
      ImportsDirectory="$(_LibraryProjectImportsDirectoryName)"
      UseShortFileNames="$(UseShortFileNames)"
      OutputImportDirectory="$(_AndroidLibrayProjectIntermediatePath)"
      OutputFile="$(ResgenTemporaryDirectory)\resources.apk"
      PackageName="$(_AndroidPackage)"
      ApplicationName="$(_AndroidPackage)"
      JavaPlatformJarPath="$(JavaPlatformJarPath)"
      JavaDesignerOutputDirectory="$(ResgenTemporaryDirectory)"
      CompiledResourceFlatFiles="@(_CompiledFlatFiles)"
      ManifestFiles="$(ResgenTemporaryDirectory)\AndroidManifest.xml"
      AdditionalAndroidResourcePaths="@(_LibraryResourceDirectories)"
      YieldDuringToolExecution="$(YieldDuringToolExecution)"
      ResourceSymbolsTextFile="$(IntermediateOutputPath)R.txt"
      ResourceDirectories="$(MonoAndroidResDirIntermediate)"
      ExtraArgs="$(AndroidAapt2LinkExtraArgs)"
      ToolPath="$(Aapt2ToolPath)"
      ToolExe="$(Aapt2ToolExe)"
      UncompressedFileExtensions="$(AndroidStoreUncompressedFileExtensions)"
      ProguardRuleOutput="$(_Aapt2ProguardRules)"
  />

If I change the SDK version to Android10, all of the errors go away, the package gets deployed, but will not show up in the app launcher, and will not start when I try to debug it.

I'm terrified at what it's going to be like to add the in app purchase for my app... (actually just considering making a separate app in the store and making a new build target / alternate code base to build it from)

Please, there has to be some way to implement ads in a Xamarin.Forms app, that supports Android 9...

Anyone who's implemented AdMob to a Xamarin.Forms app (I don't even care if it supports iOS for now. I would be nice for the future, but for now I just want to get my Android app up and running)

Please help!?

ImageButton Command not executed in CarouselView

$
0
0

hi, im trying to implement CaroulselView and add command to imagebutton in template.

            <CarouselView ItemsSource="{Binding weblinks}"
              PeekAreaInsets="100" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2"
                              VerticalOptions="FillAndExpand"
                              HeightRequest="210">
                    <CarouselView.ItemTemplate>
                        <DataTemplate>
                            <StackLayout>
                                <Frame HasShadow="True"
                       BorderColor="DarkMagenta"
                       CornerRadius="2"
                       Margin="5"
                       HeightRequest="200"
                       WidthRequest="200"
                       >
                                    <StackLayout>
                                        <ImageButton Source="{Binding ImageUrl}" Aspect="AspectFill"
                               HeightRequest="200"
                               WidthRequest="200"
                               HorizontalOptions="EndAndExpand" Command="{Binding TapImgCommand}"></ImageButton>

                                    </StackLayout>

                                </Frame>
                            </StackLayout>
                        </DataTemplate>
                    </CarouselView.ItemTemplate>
                </CarouselView>

in viewmodel :
public DelegateCommand TapImgCommand => new DelegateCommand(NavigateWebview);

async void NavigateWebview()
{
await SLDialog.AlertAsync("Test!!!!!");
await Browser.OpenAsync("http://www.google.com", BrowserLaunchMode.SystemPreferred);
}

TapImgCommand never executed in mvvm if use in carouselview (as template data). i tried to put imagebutton outside carouselview to test and it able to execute command.

How to connect specific database if there are 2 or more data models in one database xamarin?

$
0
0

previously I have created a data model as below. I have successfully loaded the data into a listView for the public class student.

Then, how do you connect data from a public class school that is only input once without using a listView and PrimaryKey?

using SQLite;
using System;

namespace SchoolData.Models
{
    public class Student
    {   
        [PrimaryKey, AutoIncrement]
        public int IdSis { get; set; }
        public DateTime Date { get; set; }
        public string PicStudent { get; set; }
    }

    public class School
    {
        public string SchoolName { get; set; } //without primary key or single entry
        public string Address { get; set; }
        public string Vision { get; set; }
    }
}

XamlPage code overview:

<StackLayout>
    <Label Text="School Name:"/>
    <Entry Text="{Binding SchoolName}"/>
    <Label Text="Address:"/>
    <Entry Text="{Binding Address}"/>
    <Label Text="Vision:"/>
    <Entry Text="{Binding Vision}"/>

    <Button Text="Save" Clicked="SaveClick"/> //save all entry
    <Button Text="Clear" Clicked="ClearClick"/> //clear all entry
</StackLayout>

Thank's.

GPS Location Enable in Xamarin forms

$
0
0

In Xamarin forms ,I have to enable GPS like as below image not in settings page


XF5: Fixed Header, different Pages

$
0
0

I don´t know how to describe it correctly, but I try:

I would like to have on a single Page a kind of Header-Section with a Menu. Depending on which Menu-Item is selected I would like to load another page underneath my header. Kind of a Splitscreen. All Pages will have the same ViewModel.
Actually I have all my "Pages" in the same XAML-File, but this is very confusing and it contains too much code. I make them visible my setting a StackLayout visibility to True or False, but I am not happy about that solution.

Any ideas ?

image not show image from url

$
0
0

Hello

i have 2 image
see Source="https://ic.pics.livejournal.com/koparev/70195450/27486/27486_600.jpg"/>
not Source="https://zhenskoe-mnenie.ru/upload/information_system_14/1/3/2/item_13266/information_items_13266.jpg"/>

for example, this image also not see
not Source="https://101kote.ru/upload/resize_cache/iblock/459/770_500_240cd750bba9870f18aada2478b24840a/manul.jpg"/>

first image show correctly.
second image not show.
But I can easily see these pictures from the browser.

Or how do I know that this particular image will not be shown?

Thanks

Avoiding Automatic Button Capitalization

$
0
0

I have noticed that by default Xamarin.Forms Buttons automatically capitalizes the button text. I do not want this. I have found several postings both here and other sites suggesting creating custom renderers or modifying certain files, however, because I am new to Xamarin, I was having trouble completely understanding how to do this. Can anybody give me more detailed or step by step instructions on avoiding capitalization? Thanks.

Is opening a file in page constructor possible?

$
0
0

I'm trying to open a file for read in the MainPage() constructor MainPage.xaml.cs and for some reason

namespace FileReadTest
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            string fileName = @"c:\Temp\test.txt";
            bool exists = File.Exists(fileName);
            if (exists)
            {
                Console.Write("file exists");
            }

        }
    }
}

The breakpoint on if (exists) shows it's false, while the file for sure exists (see below, anyway the same function returns true in the Console app).

c:\>dir c:\temp\test.txt
 Volume in drive C has no label.
 Volume Serial Number is 94E8-0563

 Directory of c:\temp

17/01/2021  22:13                 4 test.txt
               1 File(s)              4 bytes
               0 Dir(s)  139,594,780,672 bytes free

c:\>                            

Is Xamarin.Forms blocking IO somehow?

AdMob and Xamarin.forms

$
0
0

I have been through the forums and searches online and I have yet to find any samples or tutorials that work to get AdMob working with Xamarin Forms.

Does anyone know of a current admob tutorial, within the last... say 9 months... tutorial or sample that works with xamarin forms?

Netflix-like loop scrolling through a CollectionView?

$
0
0

Hi,

Is it possible to have a loop scrolling through a CollectionView for my mobile app (Android, iOS only)? Meaning after I reached the last element it would show me the first one again. Just like we know it from Netflix. I would like to avoid simply adding the same elements to the ItemSource and thus potentially increasing the ItemSource size infinitely.

I know CarouselView has a property called loop for that. But for our use case CarouselView was too buggy which is why I have to use CollectionView.

Any help is much appreciated.

VisualState : animate element when state changes

$
0
0

Hello,

I know the forum moved to Microsoft's forum but I feel like not everyone has moved and there is still a lot of people reading message here.

I'm playing with the CarouselView (awesome release by the way :wink:).
I'd like to animate the element while scrolling between elements.

Right now, Storyboard is still not in the box (maybe it will be there once MAUI is released ?)
In MS Xaml, I would have add a storyboard in the visual state "CurrentItem" "NextItem" "PreviousItem" "DefaultItem" to animate the scale with an animation.

The carouselView exposes a visual state for all kind of element (like I said : previous, current, next, default) but the control expose a property for those objects.

Without storyboard, what is the best way to achieve that ?

Any idea would be much appreciated.

I wish you all the best and thank you for reading so far !


Tabbed Page - Dynamically changing page calls First Page OnAppearing

$
0
0

Hello,

I am having an unexpected behaviour when dynamically changing current tabbed page with new page.

Below is XAML that has 4 pages

<TabbedPage.Children>
    <local:Page1 />
    <local:Page2 />
    <local:Page3 />
    <local:Page4 />
</TabbedPage.Children>

On runtime, based on some codition and if user selected Page3 from Page4, I wanted to present Page5 as below instead of Page3

    protected override void OnCurrentPageChanged()
    {
        base.OnCurrentPageChanged();
        if (someCondition && CurrentPage is Page3)
        {
            Page5 page5 = new Page5() ;
            Children[2] = page5; 
        }
      }

What happening is that on Children[2] = page5 statement,
1) It calls OnAppearing of Page1,
2) Then calls OnCurrentPageChanged() (at this stage CurrentPage becomes Page1)
3) Then calls OnAppearing of Page5
4) Then calls OnCurrentPageChanged() (at this stage CurrentPage becomes Page5)

What I am expecting is that on Children[2] = page5 statement,
1) To calls OnAppearing of Page5
2) Then calls OnCurrentPageChanged() (at this stage CurrentPage to be Page5)

Due to additionally calling of Page1, this gives bad user experience as on Page1 OnAppearing there already code work being done that results in slow app when user switches to tab.
Second, it gives bad user experinece as its quite noticable the tab indactor moving from Tab1 to Tab3 even though user moved to Tab3 from Tab4

Is it really expected execution cycle? Or something I am doing wrong or any better way to load dynamic page on current tab position?
Or Atleast how to avoid second user experience that tab indicator is moving from Page1 to Page3 location?

Thanks.

can not set scalex to float.nan?

$
0
0

I want to animate the view but there is an error.

I am using the ScaleTo function.

no matter await myView.ScaleTo(1);
or myView.ScaleTo(1); not async

there will be the error.

what is the right size of the icon in each folder in android?

$
0
0

in android there are folders like mipmap-hdpi mipmap-mdpi,mipmap-xhdpi

I want put the icon to it but what is the right size ?

my size is 144144 in hdpi but the default launcher_foreground.png is 162162

I use launcher_foreground all is ok but use my icon which is 44*144 the icon is not displayed and there will be a default icon.

what is the right size?

Need help determining the crashing problem when deployed to TestFlight

$
0
0

Hi devs,

I have a released the app in TestFlight but it crashes immediately after tapping on Open button. I downloaded the crashreport zip file and I cannot figure out what's causing it.

First and foremost,
The app works in Debug and in Release
Linker is set to to SDK only in Release
It's on Automatic Provisioning
I have the correct Distribution profile and not using those Development and Wildcard provisions

The crash log is too big so I attached the crashlog file here.

I am hoping someone can help me

[Android] Maps not working on Google Play store

$
0
0

I am using the Xamarin.Forms.GoogleMaps plugin, but the same happens with Xamarin.Forms.Maps.

  • I created a Google API Key, and I restricted it for android, using the package name and SHA1 from the keystore that I use to publish the app to Google Play.
  • I archived the android app, signed with my keystore.
  • It saved the APK to the computer.
  • I installed that APK to the phone, and maps work just fine.

  • I manually uploaded that same APK to Google Play and created a new alpha release.

  • I deleted the app (with the working maps) from my phone.
  • I installed the app from Google Play
  • The maps are blank!

NOTE
When I go to Google Play Console and download the APK and try it on my phone, I get these results:

  • Original APK: maps work
  • Derived APK: maps are blank

I don't understand what's wrong, can anyone please advise?
Thanks

Viewing all 77050 articles
Browse latest View live


Latest Images

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