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

Android not persisting App.Current.Properties

$
0
0

Hi,

I'm currently stuck with a bug using App.Current.Properties.
I have an application deployed to iOs and Android. I have a common project containing View, Viewmodels...
Into my first screen, I have a login/password form. When the user logs in, I save its values into App.Current.Properties and then call SavePropertiesAsync.
The user do what he has to do and then quits the application.
Later, he comes back to the app and then, i load values into the different textboxes.

This works well on iOs app but not in Android one. Saving and Loading values is done by the same class (shared into a portable class library) and these calls are done into the same ViewModel for both app so the code is exactly the same in iOs and Android apps.

Another detail that is important : it works on Android when debugging. It doesn't work when I create the apk package, sign it and then install it manually.

Environment :

  • Developping with Visual Studio 2015 Enterprise Update 2
  • Xamarin versions for the Android app :

    • Xamarin.Forms 2.2.0.31
    • Xamarin.Android.* : 23.3.0
  • Xamarin version for the portable class library that owns Views and viewmodels : Xamarin.Forms 2.2.0.31

Steps to NOT reproduce the bug :
All these steps must be done in debug mode

  • Open the application
  • fill login/password fields and validate the connection
  • (here, the connection is verified and the values are saved into app.current.properties)
  • quit the application
  • restart the application
  • All the fields are filled

Steps to reproduce the bug :
Do the same steps but not in debug mode (just create apk, sign it, install it manually).

Do you know why I got this bug ?


Forms>Android: Cant get tabs to fill (use full width) in landscape and tablets

$
0
0

I'm using Icons for my tabs on Android, using this trick
https://forums.xamarin.com/discussion/17654/tabbedpage-icons-not-visible-android

However, tilting the phone to landscape or using a tablet will make the tabs align in the start (left) of the tab-bar.
This looks a bit silly...

I want the tabs to use the full with or at least center on the tabbar, like they do on the ipad.
I have tried to add tabs.axml and toolbar.axml like described here
https://blog.xamarin.com/material-design-for-your-xamarin-forms-android-apps/
but with no luck. Do I need to do something more? Or is there Another way?

Regards Andreas

Help Converting an Image to Stream and submitting to rest service

$
0
0

So I am trying to convert an Image (android implementation) to a stream in order to Submit to a rest service, here is the method signature:

Task<Contract.Emotion[]> RecognizeAsync(Stream imageStream);

When I call the method I get the following error:
"System.InvalidOperationException: The request URI must either be an absolute URI or BaseAddress must be set"

Please help!

How do I Convert a local file to a stream that can be submitted to a rest service?

Here is my android FileHelper implementation:

public Task GetFileStream(string filename)
{
try
{
var s = new FileStream(filename, FileMode.Open);
StreamReader r = new StreamReader(s);
return Task.FromResult(r.BaseStream);
}
catch
{
throw;
}
}

Detect idle screen

$
0
0

Hello,
I'm wondering when my application is inactive, say I want when spending 1 minute without using the User, can display a screen with several images, for example a random banner. But so far without success
can anybody help me?

My thread

  public class Waiter: Thread
    {
        private static string TAG = "Waiter";
        private long _lastUsed;
        private long _period;
        public bool stop;

        private DateTime _last;
        public Waiter (long period)
        {
            this._period = period;

        }

        public override void Run ()
        {
            long idle = 0;
            this.Touch ();
            do {

                TimeSpan span = DateTime.Now - _last;
                idle = (long)span.TotalMilliseconds;
                Console.WriteLine ("Application is idle for " + idle + " ms");
                try {

                    //Thread.Sleep (5000);
                } catch {
                    Console.WriteLine ("Waiter interrupted!");
                }
                if (idle > _period) {
                    idle = 0;


                }
            } while (!stop);
            Console.WriteLine ("Finishing Waiter thread");
        }

        [MethodImpl (MethodImplOptions.Synchronized)]
        public  void Touch ()
        {
            //_lastUsed = DateTime.Now.Millisecond;
            _last = DateTime.Now;
        }

        [MethodImpl (MethodImplOptions.Synchronized)]
        public void ForceInterrupt ()
        {
            this.Interrupt ();
        }

        [MethodImpl (MethodImplOptions.Synchronized)]
        public new void Stop ()
        {
            stop = true;
        }

        [MethodImpl (MethodImplOptions.Synchronized)]
        public void SetPeriod(long period)
        {
            this._period = period;
        }

    }
}

Appodeal integration

$
0
0

Has anyone integrated Appodeal into their Xamarin Forms projects? They seem to provide an example for native Xamarin Android but not for Cross Platform. Any help will be appreciated :)

Can I Use ViewModel as Owner of Animation.Commit?

$
0
0

I want to animate a property in ViewModel using Animation.
Can I use it?

var animation = new Animation(x => this.Angle = x, 0, 360, Easing.CubicInOut);
animation.Commit(this, "Animation"); // "this" is a view model class

In Commit, owner must be IAnimatable and it has 2 methods BatchBegin() and BatchCommit(). What should I implement in these both methods?

Xamarin.Forms Map how can we change pin position after its being added to the map?

$
0
0

we are tracking users location and we want to update pin position each time user location is changed, could we get the real pin reference that's on map?.
we need to refresh map without clearing it and re-add pins again.

any help is appreciated.

Any chance of Nightly builds for forms?

$
0
0

Some bugs are completely breaking on certain operating systems like the current case with the toolbar exception on UWP and Windows 10 desktop. Is there any hope that maybe in the future there will be another channel after Alpha for say Nightly Builds from GitHub? Something in the meantime till all the packages are able to be compiled and ran locally?


using StackLayout Children.Add many label,but the label.x,label.bound.location.x all 0,why

$
0
0

my smiple code

StackLayout layout

for(int i=0;i<10;i++)
{
layout.Children.Add(label);
}

and get control code.

control = layout.Children[newValue]

i using control.x,control.Bounds.Location.X always is 0,how can i get Actual X.

tks

FilePath from MediaPicker randomly fails

$
0
0

Hi,

I'm using the failry standard MediaPicker to select Media from iOS:

            var mediaPicker = new MediaPicker();
                    await mediaPicker.PickPhotoAsync().ContinueWith(t =>
                    {
                        MediaFile file = t.Result;

                        if (file != null)
                        {
                            _viewModel.ImagePath = file.Path;
                            chosenImg.Source = ImageSource.FromFile(file.Path);
                        }

                    }, TaskScheduler.FromCurrentSynchronizationContext());

The strange thing here is that chosenImg, which is just an Image Control, will ALWAYS display the correct image so I know the image selected is there and the path must be right in some form. However, I then use the Dependency Service to take the image and resize it before the user uploads.

This is where the problem lies, when the platform specific code attempts to resize the image, it sometimes finds the file and sometimes doesn't. At first I thought it was a simulator bug, but the same behaviour occurs on my device as well.

The code is really simple for resizing, it just takes pathToFile (which I know must be correct in some form because the Image Control displays it), and a targetPath and a max length/width:

public async Task ResizeImage(string sourceFile, string targetFile, float maxWidth, float maxHeight)
        {
            try
            {
                if (File.Exists(sourceFile) && !File.Exists(targetFile))
                {
                    using (UIImage sourceImage = UIImage.FromFile(sourceFile))
                    {
                        var sourceSize = sourceImage.Size;
                        var maxResizeFactor = Math.Min(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);

                        if (!Directory.Exists(Path.GetDirectoryName(targetFile)))
                            Directory.CreateDirectory(Path.GetDirectoryName(targetFile));

                        if (maxResizeFactor > 0.9)
                        {
                            File.Copy(sourceFile, targetFile);
                        }
                        else
                        {
                            var width = maxResizeFactor * sourceSize.Width;
                            var height = maxResizeFactor * sourceSize.Height;

                            UIGraphics.BeginImageContextWithOptions(new CGSize((float)width, (float)height), true, 1.0f);
                            //  UIGraphics.GetCurrentContext().RotateCTM(90 / Math.PI);
                            sourceImage.Draw(new CGRect(0, 0, (float)width, (float)height));

                            var resultImage = UIGraphics.GetImageFromCurrentImageContext();
                            UIGraphics.EndImageContext();


                            if (targetFile.ToLower().EndsWith("png"))
                                resultImage.AsPNG().Save(targetFile, true);
                            else
                                resultImage.AsJPEG().Save(targetFile, true);
                        }
                    }
                }
            }
            catch (Exception x)
            {
                //TODO:
            }
        }

When breaking at the catch, it randomly can't find the file. I can't pin down the randomness but the behaviour is the same on the simulator and the device so there's something going on.

Does file path have to be manipulated when using the DependencyService and platform specific code?

Thanks

Trouble with custom WCF headers (Android xamarin forms application)

$
0
0

Hi

I'm building an android application that talks to our existing WCF service layer and we use a custom header to pass data from the client to the service layer

On the client side I have tried we use the following code to inject into the outbound message header

       //// use reflection to get the Inner Channel
            PropertyInfo Channel = client.GetType().GetProperty("InnerChannel");
            IClientChannel chn = (IClientChannel)Channel.GetValue(client, null);
            var scope = new OperationContextScope(chn);
            // set session into header
            var typedHeader = new MessageHeader<RALHeader>(header);
            var untypedHeader = typedHeader.GetUntypedHeader(_RAL_HEADER, _RAL_HEADER_NS);
            // inject RALHeader into outgoing message header
            OperationContext.Current.OutgoingMessageHeaders.Add(untypedHeader);

and on the server side we use the following code

        //Retrieve incomming message properties collection
             MessageProperties msgProperties = OperationContext.Current.IncomingMessageProperties;
              //Get the header and extract required data
              if (msgProperties.ContainsKey(RalHeader))
              {
                    var header = msgProperties.FirstOrDefault(f => f.Key == RalHeader).Value as RALHeader;
            etc ...

This works with a normal windows console application, but when I debug my android application .. I get nothing in my header by the time i get to the service layer

I'm obviously doing something wrong, can anyone help?

Thanks in Advance

Wrong orientation with MediaPicker

$
0
0

I've seen solution for this problem with rotating manually, but problem I'm facing is that compression for getting stream from bitmap is slow, is there any other solution for this? or is there any other way to get stream from bitmap faster?

bitmap.Compress(compression, 100, stream);

Thanks!

The App Simulator Showing Blur contents

$
0
0

Hi

After creating the pure Xamarin.Forms project, I tried to view the app in the simulator, But its contents are showing blur effect, Why showing like this any idea?

Loop through Xamarin Forms Behaviors from ViewModel

$
0
0

Hello, I'm looking to validate a page by checking if all of the Xamarin Behaviors attached to each control are valid. I currently have a property called IsValid on each behavior which gets set to true/false depending on what is entered into the Entry. I'm attaching the behaviors like so:

<Entry Placeholder="Name">
      <Entry.Behaviors>
        <behaviors:RequiredBehavior/>
        <behaviors:NameBehavior/>
      </Entry.Behaviors>
</Entry>

I'm also setting the BindingContext of this page to one of my ViewModels. What would be the best way to loop through these behaviors within my viewmodel to check if the page is valid? Or is there a better route to validating all fields before proceeding to another page?

How to validate multiple controls on a form before allowing user to leave a content page?

$
0
0

I have used behaviors and triggers to validate individual controls and highlight text in red if invalid, for example. However what is the best approach to validate multiple controls and prevent the user from leaving the page until the invalid entires/settings are corrected? I know that behaviors can be bindable and was wondering if somehow this is the way to go but I'm not sure how to combine them to create an overall validation state. Any advice or sample code that people can provide or direct me to for reference would be greatly appreciated. Thanks.


Xamarin Forms and XLabs.Forms

$
0
0

I've started a new "Blank App (Xamarin.Forms Portable)" from the default templates that comes with Xamarin.
Went to my NuGet Manager in VS and updated XF and then installed the newest XLabs.Forms.

After this I cant get my Android project to build. It says it is missed a ton of resources (attributes, colors, dimensions, drawables, ids, string, styles etc.).

My current setup:
Windows 10 Pro
Visual Studio Professional 2015 v. 14.0.24720.00 Update 1
VS Extension: Xamarin for Visual Studio v. 4.0.3
VS Extension: NuGet Package Manager for Visual Studio 2015 v. 3.4.3.855
Xamarin software v. 4.0.3.214

Libraries in the project:
Xamarin.Forms v. 2.2.0.31
XLabs.Forms v. 2.0.5782

In the Android SDK Manager i have installed the following:
All packages in API 14 - 23
All packages in tools
All packages in Extras
The "SDK Platform Android N Preview" in "Android N (API 23, N preview)"

Any help would be appreciated.

PopModalAsync loses functionality of underlying ContentPage

$
0
0

Hi, I have a Xamarin Forms app using Mvvm and testing on an iOS device, and when, in a ViewModel, I PushModalAsync a new page, naturally a new page pops up. But when I PopModalAsync - and the modal page pops and leaves the original page there - the commanding in that Page's ViewModel no longer works.

If, before popping, I PushAsync a new page, and then PopModalAsync, the new page is revealed when the modal is popped, and it's commanding works perfectly.

Any ideas why a Page would lose it's commanding when all that has happened is PushModalAsync and then PopModalAsync? (Keeping in mind that if a new page had been PushAsynced befopre PopModalAsyncing that it would be functional.)

Kind regards,

Anthony

WebView height as HTML content

$
0
0

Hi I have this XAML, where I have a WebView that loads a html page with 3 gif .
I would like the WebView become as big as the HTML content . It's possible?

<?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="XXXApp.Views.Basic.FinalCheck">
  <ContentPage.Padding>
    <OnPlatform x:TypeArguments="Thickness"
                iOS="5, 20, 5, 0"
                Android="5, 0, 5, 0"
                WinPhone="0, 0, 0, 0" />
  </ContentPage.Padding>
  <Grid>
    <Grid>
      <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
      </Grid.RowDefinitions>
      <Grid Grid.Row="0" >
        <Grid.RowDefinitions>
          <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*"/>
          <ColumnDefinition Width="*"/>
          <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Button Text="Menu" Clicked="OnButtonClickedMenu" Grid.Column="0" Grid.Row="0" BackgroundColor="Transparent" HorizontalOptions="Start" x:Name="btnMenu"></Button>
        <Label Text="FinalCheck" Grid.Row="0" Grid.Column="1" HorizontalOptions="Center" FontSize="Medium" VerticalOptions="Center" x:Name="lblFinalCheck" />
      </Grid>
      <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <WebView x:Name="webw1" Grid.Row="0" Grid.Column="0"></WebView>
      </Grid>
      <Grid Grid.Row="2" >
        <Grid.RowDefinitions>
          <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <ScrollView Grid.Row="0" Grid.Column="0">
          <Label Text="LastExplanation" x:Name="lblLastExplanation" />
        </ScrollView>
      </Grid>
    </Grid>
  </Grid>
</ContentPage>

public FinalCheck()
        {
            InitializeComponent();
            webw1.Source = DependencyService.Get<IBaseUrl>().Get() + "instruction.html";
        }

Thanks in advanced.

File locations and File.Exists

$
0
0

Hi,

I've tried every conceivable way (I think), to determine if a file exists, and I can't produce consistent results. It randomly works/fails.

I've tried:

//testing only
                var documentsPathOne = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                var filePathOne = Path.Combine(documentsPathOne, fileName);
                bool doesTypeOneExist = File.Exists(filePathOne);

                if (!UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    var OtherDocumentsPath = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User)[0];
                    var filePathTwo = Path.Combine(OtherDocumentsPath.AbsoluteUrl.ToString(), fileName);
                    bool doesTypeTwoExist = File.Exists(filePathTwo);
                }

                bool doesTypeThreeExist = File.Exists(filePath);

The strange thing is this typeThree is a DIRECT result from the media picker, and using it in the context of an Image Control works, i.e.:

Image.Source = filePath Works perfectly and the image is displayed - so I know it exists and is there.

Can anyone help me with using files in iOS? It's crazy!

Thanks

Application that tracks multiple users on a map

$
0
0

Hello world,

I would like to make an application that tracks multiple people on a map and allows the user to track which person he wants.

So all i want to do is track multiple people and plot them on a user map, so if the user wanted to see where his friends where at it would show on his cell phone.

Is this faisible using xamarin forms ?

I thought to make moving pins on the map but it seems we have to drop and make a new pin to change his position.

Thank you for your help

Viewing all 58056 articles
Browse latest View live


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