Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all 204402 articles
Browse latest View live

Property not found, and general strangeness

$
0
0

I am at a loss here, so I may ramble a bit.

I have some code that was tested and working under Xamarin Forms 3/VS2017. We updated to Xamarin Forms 4.3/VS2019.

On opening a popup (Rg.Plugins.Popup, using a ContentView), I now see messages in my debug window like:

[0:] Binding: 'Tag_Number' property not found on 'OurCustomDict', target property: 'MyControl.FieldValue'

The messages appear upon setting the BindingContext for the ContentView, which we are doing in the constructor.

In XAML, the binding looks like:
FieldValue="{Binding CurrentPick[Tag_Number]}"
where CurrentPick is the 'OurCustomDict' - which is really a Dictionary<string, object>. 'MyControl.FieldValue' is the property name backing a bindable property on a custom control.

If I set a break after the binding context is set (after seeing the debug messages), all ways that I think of to access this information show valid data, e.g.
?((AppData)this.BindingContext).CurrentPick["Tag_Number"]
966093

When I first noticed this problem, I also realized that the code would actually work in Release mode - just not in Debug mode. After investigating, I tried changing properties on the Android project, such as the linking setting, and fast deployment, etc. Now, I can't get back to the state where Release works.

First, I'm wondering why in the world if Xamarin thinks that my bindings are broken, why doesn't it throw an exception? But anyway...

Beyond that, the only thing I can think of is that for some reason, the binding process doesn't seem to understand what the Type of the object is at the time it tries to bind it.

I'm looking for some input on this - whatever the problem is, it's not as simple as the property not being on the object in question. Can anyone explain why it might work in Release, but fail in Debug?

Any help is appreciated.

Thanks.


TouchTracking input offset

$
0
0

Hey I'm playing around with a combination of Touch tracking and SkiaSharp libraries.

I've got it all working fine but there seems to be a curious situation with the cordinates being returned by the touch input. My little application takes point X and point Y and updates the canvas text object to the cordinates but only at 50% the value they should be.

Here I am gathering the coordinates that have been touched on screen:

        void OnTouchEffectAction(object sender, TouchActionEventArgs args)
        {
            userMadeInput = true;

            xTouch = args.Location.X;
            yTouch = args.Location.Y;
        }

Then I apply it to the text object and refresh the screen:

         yText = yTouch;
         xText = xTouch;

 //Debug Text
            canvas.Save();
            canvas.Clear(SKColors.MediumSeaGreen);

            canvas.DrawText("x: " + xText + "| y: " + yText, xText, yText, textPaint);

            canvas.Restore();

Then in a test, I run my finger down the screen but the values are coming in half of the value they should be.
ie: screen position 50 returns 25
or screen position 250 returns 125

I rectified the issue by multiplying the positions by two and that works great on my physical Android phone.

             yText = yTouch * 2;
             xText = xTouch * 2;

Now if I go to test it in the VS Android emulator I get the same issue. for it to work on the emulator, I now need to multiply it by 3.

What's going on with the resolution here?

Validating AndroidClientHandler

$
0
0

I was trying to use an HttpClient with AndroidClientHandler to send different HTTP requests, some to correctly secured and some to incorrectly secured servers. I wanted to use the ServerCertificateCustomValidationCallback and decide on the client side whether to accept SSL errors, just like you can with the HttpClientHandler, but unfortunately AndroidClientHandler does not support ServerCertificateCustomValidationCallback.

So I ended up extending AndroidClientHandler to support it, here's a gist with what I came up with (can't post links...):
gist.github.com/nirbil/1e1b6a57eed721eab9d9a55c34fbe378

It works, but I'm facing issues, any clarifications/insight will be great!

Current issues:
1. Originally I tried using my custom TrustManager to authenticate the chain and throw the relevant exception on failure (after verifying with the validation callback), but I got some an unexpected behavior, just as explained here:
forums.xamarin.com/discussion/90314/custom-trustmanager-with-okhttp3 , basically either the app crashes or the client does not get a response.
2. So I ended up performing the entire verification process within the my custom HostnameVerifier. Namely, any error in the certificate chain or hostname missmatch ends up with a hostname exception for the client, not great but minor.
3. I'm trying to build a X509Chain to forward to the ServerCertificateCustomValidationCallback but I can't build a valid chain. In my current attempt I added all the CA certificates from the default TrustManager (_defaultTrustManager.GetAcceptedIssuers()) to the chain's extra store, but the chain build still fails.
4. On some requests (noticed it on some site I was using for testing - www.mocky.io ) the default TrustManager CheckServerTrusted fails to validate the chain on first attempt but succeeds on subsequent ones, which is odd as by my understanding this is actually performed by Android OS and the result should be stable

how can i update a listview with a button?

$
0
0

I am making a clone of a social network and in a list of comments.
I want to register one and instantly the list is updated and the record I made appears.

App crashes immediately at startup on device below API 16 - is API 15 not supported any more?

$
0
0

My app crashes immediately when the splash screen is shown on the Android 4.0.3 (API 15) device.
For other devices above API 15 it works.

android:minSdkVersion="15"
android:targetSdkVersion="28"
android:compileSdkVersion="28"

Logcat Error on device:
monodroid(7765): shared runtime initialization error: Cannot load library: reloc_library[1314]: 112 cannot locate 'posix_memalign'...

Warning in Build Log
10>F:\PS_NativeApps\Android\Apps\PracticeBird\Properties\AndroidManifest.xml : warning XA4216: AndroidManifest.xml //uses-sdk/@android:minSdkVersion '15' is less than API-16, this configuration is not supported.

Debug Log
This debug engine does not support exception conditions. The condition(s) will be ignored.
Couldn't connect to logcat, GetProcessId returned: 0
Couldn't connect debugger. You can see more details in Xamarin Diagnostic output and the full exception on logs.

Are APIs below 16 really simply not supported any longer by Xamarin.Android?
Is there a way to make it still work on API 15?

Basic question about Xamarin Form

$
0
0

Hello everyone. I have one question to ask. I want to develop my mobile application using "Mobile App(Xamarin Forms)". I want to retrieve data from firebase realtime database and display the data on label. The label is inside MainPage.xaml which is inside the Xamarin Forms. The connection to the firebase and the EventListeners is inside the Xamarin. Android. What should i do to get the value displayed on the label?

Any Xamarin.Forms support for Android Wear and Watch OS?

$
0
0

I find only Xamarin.Android and Xamarin.iOS samples and docs supporting wearables. How can we use Xamarin.Forms app support wearables?

Xamarin Shell ToolBarItem Image from storage

$
0
0

Hi,

I am a newbie at Xamarin…. So I would appreciate any help…

My app allows a user to select a profile picture - using instructions from:
ttps://lalorosas.com/blog/xamarin-forms-selecting-image-from-the-gallery

My app then saves the image and is able to reload the image into an ImageButton successfully using:
ttps://stackoverflow.com/questions/51038251/how-to-download-image-and-save-it-in-local-storage-using-xamarin-forms

I want to be able to reload the image from the database and put the image into the SHELL 
TOOLBARITEM and I haven’t been able to find instructions on that.

Can someone point me in the right direction.


Getting Mono.AndroidTools.RequiresUninstallException on Android

$
0
0

Today I started getting this deployment error on android:

Severity Code Description Project File Line Suppression State
Error ADB0030: Mono.AndroidTools.RequiresUninstallException: The installed package is incompatible. Please manually uninstall and try again.
at Mono.AndroidTools.Internal.AdbOutputParsing.CheckInstallSuccess(String output, String packageName) in E:\A_work\267\s\External\androidtools\Mono.AndroidTools\Internal\AdbOutputParsing.cs:line 339
at Mono.AndroidTools.AndroidDevice.<>c__DisplayClass95_0.b__0(Task1 t) in E:\A\_work\267\s\External\androidtools\Mono.AndroidTools\AndroidDevice.cs:line 753 at System.Threading.Tasks.ContinuationTaskFromResultTask1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at AndroidDeviceExtensions.d__11.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Devices\AndroidDeviceExtensions.cs:line 187
--- End of stack trace from previous location where exception was thrown ---
at AndroidDeviceExtensions.d__11.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Devices\AndroidDeviceExtensions.cs:line 194
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at AndroidDeviceExtensions.d__11.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Devices\AndroidDeviceExtensions.cs:line 203
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Xamarin.AndroidTools.AndroidDeploySession.d__112.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Sessions\AndroidDeploySession.cs:line 414
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Xamarin.AndroidTools.AndroidDeploySession.d__106.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Sessions\AndroidDeploySession.cs:line 217
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Xamarin.AndroidTools.AndroidDeploySession.d__104.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Sessions\AndroidDeploySession.cs:line 119 0

It only happens in Debug, but in Release i can deploy and run the app just fine.
Why is this happening?

This morning i installed the Android SDK 10.0 and I suspect it started after that, so now I uninstalled it, but I still can't deploy because of the same error.
Other apps from the same PC can be deployed just fine, so I don't get it...

I did check this out
https://docs.microsoft.com/en-us/xamarin/android/errors-and-warnings/adb0030

but I don't even have my app installed on the device...

Thanks

How can I disable animation on a switch when the state changes.

$
0
0

I need to cancel the animation to a switch when its on / off state changes, I have a list with reusable cells and this animation does not look good when you scroll.

Adding event handlers in XML

$
0
0

I have a series of Button(s) in my xml file, all of which I want to use the same handler for their Click event. I have written the handler in the activity file. Is there a way to connect the handler to the Button(s) using an attribute in XML? In UWP I was able to do this using an attribute like Click="EditScore_Click", is there anything like this for Android? I would prefer to do it this way, since I have multiple Button(s) that I do not need to access, so I have no need to give them all Ids. Any ideas? Thanks.

Error when creating repeated local notifications using Xamarin.Forms on Android

$
0
0

I have been searching for how to create repeated local notifications, for instance a reminders app, I want to implement this logic on my xamarin.forms app so I have been testing with this piece of code (and understanding it) that I found on the web but the following error just I dont understand it.

Failed to create JavaTypeInfo for class: Android.Support.V4.View.Accessibility.AccessibilityManagerCompat/IAccessibilityStateChangeListenerImplementor due to MAX_PATH: System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\andre\source\repos\LocalRepeatedNotificationsApp\LocalRepeatedNotificationsApp\LocalRepeatedNotificationsApp.Android\obj\Debug\90\android\src\mono\android\support\v4\view\accessibility\AccessibilityManagerCompat_AccessibilityStateChangeListenerImplementor.java'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.InternalDelete(String path, Boolean checkHost)
   at System.IO.File.Delete(String path)
   at Xamarin.Android.Tools.Files.CopyIfStreamChanged(Stream stream, String destination)
   at Xamarin.Android.Tasks.Generator.CreateJavaSources(TaskLoggingHelper log, IEnumerable`1 javaTypes, String outputPath, String applicationJavaClass, String androidSdkPlatform, Boolean useSharedRuntime, Boolean generateOnCreateOverrides, Boolean hasExportReference) LocalRepeatedNotificationsApp.Android           

My code for sending local notifications in a repeated way:

public class LocalNotificationService : ILocalNotificationService
    {
        int _notificationIconId { get; set; }
        readonly DateTime _jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        internal string _randomNumber;

        public void LocalNotification(string title, string body, int id, DateTime notifyTime)
        {

            //long repeateDay = 1000 * 60 * 60 * 24;    
            long repeateForMinute = 60000; // In milliseconds   
            long totalMilliSeconds = (long)(notifyTime.ToUniversalTime() - _jan1st1970).TotalMilliseconds;
            if (totalMilliSeconds < JavaSystem.CurrentTimeMillis())
            {
                totalMilliSeconds = totalMilliSeconds + repeateForMinute;
            }

            var intent = CreateIntent(id);
            var localNotification = new LocalNotification();
            localNotification.Title = title;
            localNotification.Body = body;
            localNotification.Id = id;
            localNotification.NotifyTime = notifyTime;

            if (_notificationIconId != 0)
            {
                localNotification.IconId = _notificationIconId;
            }
            else
            {
                localNotification.IconId = Resource.Drawable.OlympiaLogo;
            }

            var serializedNotification = SerializeNotification(localNotification);
            intent.PutExtra(ScheduledAlarmHandler.LocalNotificationKey, serializedNotification);

            Random generator = new Random();
            _randomNumber = generator.Next(100000, 999999).ToString("D6");

            var pendingIntent = PendingIntent.GetBroadcast(Application.Context, Convert.ToInt32(_randomNumber), intent, PendingIntentFlags.Immutable);
            var alarmManager = GetAlarmManager();
            alarmManager.SetRepeating(AlarmType.RtcWakeup, totalMilliSeconds, repeateForMinute, pendingIntent);
        }

        public void Cancel(int id)
        {

            var intent = CreateIntent(id);
            var pendingIntent = PendingIntent.GetBroadcast(Application.Context, Convert.ToInt32(_randomNumber), intent, PendingIntentFlags.Immutable);
            var alarmManager = GetAlarmManager();
            alarmManager.Cancel(pendingIntent);
            var notificationManager = NotificationManagerCompat.From(Application.Context);
            notificationManager.CancelAll();
            notificationManager.Cancel(id);
        }

        public static Intent GetLauncherActivity()
        {

            var packageName = Application.Context.PackageName;
            return Application.Context.PackageManager.GetLaunchIntentForPackage(packageName);
        }


        private Intent CreateIntent(int id)
        {

            return new Intent(Application.Context, typeof(ScheduledAlarmHandler))
                .SetAction("LocalNotifierIntent" + id);
        }

        private AlarmManager GetAlarmManager()
        {

            var alarmManager = Application.Context.GetSystemService(Context.AlarmService) as AlarmManager;
            return alarmManager;
        }

        private string SerializeNotification(LocalNotification notification)
        {

            var xmlSerializer = new XmlSerializer(notification.GetType());

            using (var stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, notification);
                return stringWriter.ToString();
            }
        }
    }

    [BroadcastReceiver(Enabled = true, Label = "Local Notifications Broadcast Receiver")]
    public class ScheduledAlarmHandler : BroadcastReceiver
    {

        public const string LocalNotificationKey = "LocalNotification";

        public override void OnReceive(Context context, Intent intent)
        {
            var extra = intent.GetStringExtra(LocalNotificationKey);
            var notification = DeserializeNotification(extra);
            //Generating notification    
            var builder = new NotificationCompat.Builder(Application.Context)
                .SetContentTitle(notification.Title)
                .SetContentText(notification.Body)
                .SetSmallIcon(notification.IconId)
                .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Ringtone))
                .SetAutoCancel(true);

            var resultIntent = LocalNotificationService.GetLauncherActivity();
            resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
            var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(Application.Context);
            stackBuilder.AddNextIntent(resultIntent);

            Random random = new Random();
            int randomNumber = random.Next(9999 - 1000) + 1000;

            var resultPendingIntent =
                stackBuilder.GetPendingIntent(randomNumber, (int)PendingIntentFlags.Immutable);
            builder.SetContentIntent(resultPendingIntent);
            // Sending notification    
            var notificationManager = NotificationManagerCompat.From(Application.Context);
            notificationManager.Notify(randomNumber, builder.Build());
        }

        private LocalNotification DeserializeNotification(string notificationString)
        {

            var xmlSerializer = new XmlSerializer(typeof(LocalNotification));
            using (var stringReader = new StringReader(notificationString))
            {
                var notification = (LocalNotification)xmlSerializer.Deserialize(stringReader);
                return notification;
            }
        }
    }

I am usign DependencyService to achieve this (my assembly is defined on the scope of my namespace but I havent included it for showing the problem)
Any help please?

Xamarin.Android - Java Native Invoke (JNI)

$
0
0

In this tutorial how one can integrate google map in java file

Does the "ListView" have a double-click event handler for a ListItem?

$
0
0

I'm having a very difficult time understanding how to define and use click/tap event handlers for a ListView control. Are clicks/taps the same thing? Or are they distinct? It looks like you can setup a tap event handler and define the number of taps to trigger the event. So, we can set up double-tap event handlers. But where's the equivalent double-click for a mouse?

Somebody please explain whether clicks/taps are the same and if not, why isn't there a double-click event handler for the double-clicked ListItem's in a ListView?

Also, it seems like setting GestureRecognizers on a control actually breaks the click-event handlers. I'm not 100% sure what's going on but this is the impression I'm getting from my code testing.

Oh, and lastly, before I forget. It seems like a single "tap" event handler will not properly highlight the tapped ListView Item when it occurs. Is this control in this much need of a rewrite or am I just completely lost?

Looking for advice on iOS platform for Xamarin.Form development

$
0
0

Hello there,

We are getting into Xamarin.Form mobile app development. To build iOS apps we need iOS platform. We are considering the following options

  • Renting a cloud MAC
  • MacBook Air
  • MacBook Pro

Development will be done using Visual Studio for Mac, Community edition. Being new to MAC platform I'm not sure what would be an ideal system configuration for MAC. Can Xamarin.Andriod development be done on MAC using Visual Studio for Mac?

Joe


How do you set On-Demand Resources URL for Xamarin.iOS builds?

$
0
0

I am trying to use Apple On-Demand Resources in our Xamarin app but are running into some issues. According to Apple's documentation, ODR asset packs can either be stored locally or on a remote server of your choosing when testing your app. In production, any files set up for ODR requests are stored on Apple's own servers. But for testing, we would like our assets stored remotely and pulled down by the app instead of being stored locally.

We have ODR seemingly set up correctly for accessing asset packs when stored remotely. But when it comes to linking up your own remote server, I have yet to find anything that works for Xamarin.iOS and Visual Studio for Mac. If this was native iOS, in XCode, you can set the Asset Pack Manifest URL Prefix build setting for a target to specify the location of where the asset packs are stored.

However, there doesn't seem to be an easily accessible, equivalent build setting for Xamarin.iOS in VS. The closest we have found is on line 2162 of the Xamarin.iOS.Tasks.Core/Xamarin.iOS.Common.targets (sorry for the lack of source links, the forum won't let me post them with an account so new). This line references a property 'OnDemandResourcesUrl', but it is unclear how to set this. Maybe through some build parameter? How exactly is this .targets file generated?

Thank you for any help, greatly appreciate it!

Random FirebaseApp.InitializeApp Failure Causes?

$
0
0

During OnCreate, on calling FirebaseApp.InitializeApp, I am experiencing random errors:

ava.Lang.RuntimeException: 'Unable to instantiate service md51205915cfaa299c43c140xxxxxxxx.FirebaseService: java.lang.ClassNotFoundException: Didn't find class "md51205915cfaa299c43c14012b2cf5d8c8.FirebaseService" on path: DexPathList[[zip file "/data/app/com.identitycheckpoint.sentry-PHjVUEubnFXUIUCH9PBDkg==/base.apk"],nativeLibraryDirectories=[/data/app/com.identitycheckpoint.sentry-PHjVUEubnFXUIUCH9PBDkg==/lib/arm64, /data/app/com.identitycheckpoint.sentry-PHjVUEubnFXUIUCH9PBDkg==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]'

The next debugging may or may not succeed. Any ideas?

Native Forms in UWP app - why doesn't it resize with the window?

$
0
0

I have a very basic UWP page with a Native Forms Content Page in it with an image. I want the image to fill the width of the UWP page. The image fills nicely when the app first starts, but when you resize the window the image doesn't change size. I was able to find a workaround to cause the image to resize, but I feel like it shouldn't be necessary. Below find the very basic page code, with the workaround bits notated by comments. It looks like the SizeChanged events are not firing as I would expect. Some examples:

  • Without the workaround lines included, frameworkElement.SizeChanged only fires when the window gets bigger than the initial size
  • formsPage.SizeChanged only fires when the Content = frameworkElement; line of the workaround is included, but if only that is included (and NOT formsPage.Layout(new Rectangle(0,0,-1,-1));) the image does resize but it only gets larger as you resize, it never gets smaller

Of course I'll file a bug for this if I'm not missing anything, but I wanted to check here first.

public MainPage()
{
    InitializeComponent();
    var formsPage = new ContentPage
    {
        BackgroundColor = Color.Yellow,
        Content = new StackLayout
        {
            BackgroundColor = Color.Blue,
            Children =
            {
                new Image
                {
                    Source = ImageSource.FromFile("Assets/xamLogo.png"),
                    BackgroundColor = Color.White
                }
            }
        }
    };
    var frameworkElement = formsPage.CreateFrameworkElement();
    formsPage.SizeChanged += (sender, args) =>
    {
        Debug.WriteLine("plain forms page size change called");
    };
    frameworkElement.SizeChanged += (sender, args) =>
    {
        Debug.WriteLine("forms page (as framework element) size change called");
    };
    SizeChanged += (sender, args) =>
    {
        Debug.WriteLine("top level uwp page size change called ");

        // BELOW two lines are a workaround, should this be needed!?
        formsPage.Layout(new Rectangle(0,0,-1,-1));
        Content = frameworkElement;
        //
    };
    Content = frameworkElement;
}

How to display all my userid questions on the forum.

$
0
0

When I search for my entries on the forum I get a list of 5 entries. How do I expland and view all my entries?

Solution can't deploy to emulator in VS2019, works fine in VS2017

$
0
0

I have a Xamarin solution that was initially created in VS2017 in Windows. Everything works as expected, can build and deploy to a emulator for debugging with no issues.

I want to use VS2019 in Windows but have been having some issues with this particular solution. I am able to open and build the Xamarin solution, but when I try to deploy to a Emulator I get this error:

MSB4044: The "CopyGeneratedJavaResourceClasses" task was not given a value for the required parameter "SourceTopDirectory".

It is odd because the Android Device Manager shares the same emulators with VS2017 and VS2019, so I don't think the emulator is the issue. Is there anything I need to do to migrate a VS2017 solution to be compatible with VS2019?

Viewing all 204402 articles
Browse latest View live


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