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

NullPointerException in support library: android.support.v4.app.FragmentActivity.mHandler

0
0

I created an app for the software conference I organize, Code on the Beach, with Xamarin Android that was originally targeting v19 for 4.4 KitKat. It worked well. I upgraded Xamarin to use the latest version to get v21 Lollipop support, and added the Toolbar to get the material design style action bar, which required me to implement ActionBarActivity which implements the support FragmentActivity, and trying to use the regular FragmentManager no longer worked. Okay, so I converted it all to use SupportFragmentManager and make sure all my Fragments were of the v4 support variety, despite that I only want to target 4.0+.

Now, I get a Java NullPointerException in the call to base.OnSaveInstanceState(outState) whenever I rotate the screen, even if my OnSaveInstanceState method is trivial and just calls the base class:

Attempt to read from field 'android.os.Handler android.support.v4.app.FragmentActivity.mHandler' on a null object reference

Here's my practically-empty OnSaveInstanceState method, to show I'm not doing anything funky:

protected override void OnSaveInstanceState(Bundle outState)
{
    base.OnSaveInstanceState(outState);
}

Here's what the application output log shows:

[MonoDroid] UNHANDLED EXCEPTION:
[MonoDroid] Java.Lang.NullPointerException: Exception of type 'Java.Lang.NullPointerException' was thrown.
[MonoDroid] at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <IL 0x00011, 0x00068>
[MonoDroid] at Android.Runtime.JNIEnv.CallNonvirtualVoidMethod (intptr,intptr,intptr,Android.Runtime.JValue[]) [0x00084] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.21-series/49a04b96/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:896
[MonoDroid] at Android.App.Activity.OnSaveInstanceState (Android.OS.Bundle) [0x00070] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.21-series/49a04b96/source/monodroid/src/Mono.Android/platforms/android-21/src/generated/Android.App.Activity.cs:3890
[MonoDroid] at CodeOnTheBeach.MobileApp.Android.BaseActivity.OnSaveInstanceState (Android.OS.Bundle) [0x00001] in c:\Users\Paul\Documents\Xamarin\CodeOnTheBeach.MobileApp\CodeOnTheBeach.MobileApp.Android\Activities\BaseActivity.cs:241
[MonoDroid] at Android.App.Activity.n_OnSaveInstanceState_Landroid_os_Bundle_ (intptr,intptr,intptr) [0x00011] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.21-series/49a04b96/source/monodroid/src/Mono.Android/platforms/android-21/src/generated/Android.App.Activity.cs:3875
[MonoDroid] at (wrapper dynamic-method) object.bab595ee-4bb8-44e2-9d58-a36175f89b29 (intptr,intptr,intptr) <IL 0x00017, 0x00043>
[MonoDroid]   --- End of managed exception stack trace ---
[MonoDroid] java.lang.NullPointerException: Attempt to read from field 'android.os.Handler android.support.v4.app.FragmentActivity.mHandler' on a null object reference
[MonoDroid]     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1464)
[MonoDroid]     at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1672)
[MonoDroid]     at android.support.v4.app.FragmentActivity.onSaveInstanceState(FragmentActivity.java:524)
[MonoDroid]     at codeonthebeach.mobileapp.android.BaseActivity.n_onSaveInstanceState(Native Method)
[MonoDroid]     at codeonthebeach.mobileapp.android.BaseActivity.onSaveInstanceState(BaseActivity.java:100)
[MonoDroid]     at android.app.Activity.performSaveInstanceState(Activity.java:1297)
[MonoDroid]     at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1272)
[MonoDroid]     at android.app.ActivityThread.callCallActivityOnSaveInstanceState(ActivityThread.java:3923)
[MonoDroid]     at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3886)
[MonoDroid]     at android.app.ActivityThread.access$900(ActivityThread.java:144)
[MonoDroid]     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
[MonoDroid]     at android.os.Handler.dispatchMessage(Handler.java:102)
[MonoDroid]     at android.os.Looper.loop(Looper.java:135)
[MonoDroid]     at android.app.ActivityThread.main(ActivityThread.java:5221)
[MonoDroid]     at java.lang.reflect.Method.invoke(Native Method)
[MonoDroid]     at java.lang.reflect.Method.invoke(Method.java:372)
[MonoDroid]     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
[MonoDroid]     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
[bileApp.Android] type=1400 audit(0.0:63): avc: denied { read } for name="mem" dev="debugfs" ino=186278 scontext=u:r:untrusted_app:s0 tcontext=u:object_r:debugfs:s0 tclass=file
[bileApp.Android] type=1400 audit(0.0:64): avc: denied { read } for name="mem" dev="debugfs" ino=186278 scontext=u:r:untrusted_app:s0 tcontext=u:object_r:debugfs:s0 tclass=file

If I do not override OnSaveInstanceState, it still crashes, but it just says "Shutting down VM" in the logs and doesn't break inside Xamarin Studio, then it shows those last 2 lines from whatever bileApp.Android is.

Thinking critically about this, a field called mHandler being null would imply that a Handler of some kind needs to be set. Is this something I should be doing? But I can't determine from the source code what is going on here, and this stack trace is the only visibility I can see into this crash from within Xamarin Studio. Googling for the field name and NullPointerException, or NPEs on OnSaveInstanceState, didn't get me anywhere.

Are there any other special workarounds I need to be doing to use the support v4 FragmentActivity/FragmentManager? Is there any other workaround for using Material design Toolbar on 4.x without having to use the v4 support library?

Thanks in advance! Let me know if you need me to provide anything else. This happens on both a Nexus 5 with 5.0.1 and a BLU Dash Jr with 4.4. Also I tried switching to the Xamarin Beta channel to see if a fix was in the pipeline, and it's the same result.


Another AppCompat Build Problem

0
0

I've looked at the previous problems and solutions that appear to me to be related to this and either they are not related or I'm not applying the fixes correctly. My project, a Forms project using Xamarin Studio, was building fine until yesterday. Some updates were applied and then I would get the following build error:

/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets: Error: Tool exited with code: 1. Output: max res 19, skipping values-v21
/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/drawable-hdpi/abc_ab_share_pack_holo_dark.9.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/drawable-mdpi/abc_ab_share_pack_holo_dark.9.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/drawable-xhdpi/abc_ab_share_pack_holo_dark.9.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/drawable-hdpi/abc_ab_share_pack_holo_light.9.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/drawable-xhdpi/abc_ab_share_pack_holo_light.9.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/drawable-hdpi/abc_spinner_mtrl_am_alpha.9.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
obj/Debug/res/drawable-ldpi/ic_launcher.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
obj/Debug/res/drawable-hdpi/ic_launcher.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/values-v11/values.xml:50: error: Error: No resource found that matches the given name: attr 'android:actionModeShareDrawable'.

/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/values-v14/values.xml:9: error: Error: No resource found that matches the given name: attr 'android:actionModeShareDrawable'.

/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/values-v11/values.xml:57: error: Error: No resource found that matches the given name: attr 'android:actionModeShareDrawable'.

/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/values-v14/values.xml:17: error: Error: No resource found that matches the given name: attr 'android:actionModeShareDrawable'.

/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/values-v11/values.xml:64: error: Error: No resource found that matches the given name: attr 'android:actionModeShareDrawable'.

/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/values-v14/values.xml:25: error: Error: No resource found that matches the given name: attr 'android:actionModeShareDrawable'.

/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/values-v11/values.xml:71: error: Error: No resource found that matches the given name: attr 'android:actionModeShareDrawable'.

/Users/steve.andrews/.local/share/Xamarin/Android.Support.v7.AppCompat/21.0.3/embedded/./res/values-v14/values.xml:33: error: Error: No resource found that matches the given name: attr 'android:actionModeShareDrawable'.

Under project options, Build > General I have target framework set to 4.4

I've tried the following:

  1. Removed my nuget packages and reinstalled them.
  2. Changed the "Target Android Version" to use API v21. This actually gives me 100+ errors and won't allow me to debug on my G3.
  3. Changed Build > General > Target Framework set to 5.0 and then in manifest Target Android Version set to 4.4. Gives 100+ errors.
  4. Changed manifest to 5.0, gives 100+ errors.

Does anyone have any suggestions to address this? I'm very new to the Android side of things so please be gentle.

System.IO.FileNotFoundException

0
0

I m trying to read xml file using xmlreader but it gives FileNotFoundException.

Windows phone upgrade to 1.3 problem

0
0

I just done the upgrade to 1.3(following http://developer.xamarin.com/guides/cross-platform/macios/updating-xamarin-forms-apps/ guide) stable version, Android and IOS are compiling but WP not, it's showing two errors:

Cannot resolve dependency to assembly 'Xamarin.Forms.Core, Version=1.2.3.0, Culture=neutral, PublicKeyToken=null' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.

Cannot resolve dependency to assembly 'Xamarin.Forms.Core, Version=1.2.3.0, Culture=neutral, PublicKeyToken=null' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.

Any help?

ToolbarItems for Android not behaving as expected after 1.3 update

0
0

Hi team,

On click of a ToolBarItem, we were removing few other toolbar items and later we used to add it back. This page in question is of type Content Page

ToolbarItems.Remove and ToolbarItems.Add is not working as expected now. Once we reach to the page using a push async.

Though the same code will work fine if we go to anther page with Push Model Async and comes back to the same page using Pop Model Async.

Looks like initially the ToolBarItems are unable to associate with the ContentPage, though once we comes back to the same page after a POP Model async, it seems to be working...

Sample Code:

var tbiFilter = new ToolbarItem(Vernacular.Catalog.GetString("FilterLabel"), Vernacular.Catalog.GetString("DownImage"), () =>
            {
                ......
        if (_filterLayout.IsVisible)
        {
                ......
                #if __ANDROID__
                                    ToolbarItems.Add(_searchIcon);
                                    ToolbarItems.Add(_refreshIcon);
                #endif
        }
        else
        {
                ......
                #if __ANDROID__
                                    ToolbarItems.Remove(_searchIcon);
                                    ToolbarItems.Remove(_refreshIcon);
                #endif
        }
                ......
});

My phone is not discovered as a device. [OnePlus One]

0
0

Hello! I was trying to debug my app with my new OnePlus One but it didn't get discovered. How do I solve this?

Xamarin.Forms 1.3.0 Released

0
0

Important notes:

  • Generators for XAML pages should to be updated to use the new tool MSBuild:UpdateDesignTimeXaml instead of MSBuild:Compile
  • Grid default is now *
  • This release does not contain support for iOS 64bit. If you need iOS 64bit support please use Xamarin.Forms 1.3.1-pre1. It is otherwise identical to 1.3.0, however it requires Xamarin.iOS 8.6, which is available in the beta channel.

New API and Enhancements

  • Add MasterDetailPage.ShouldShowToolbarButton method to enable control over the appearance of the toolbar button.
  • Device.GetNamedSize (NamedSize size, Type targetType); Same as Device.GetnamedSize (NamedSize size, Element element) but doesn't require an instance.
  • MasterDetailPage.MasterBehavior : Used to control how the MasterDetailPage renderers the split view between the Master and Detail. Allowed values are:

public enum MasterBehavior
{
    Default,
    SplitOnLandscape,
    Split,
    Popover,
    SplitOnPortrait
}
  • VisualElement.Navigation now contains overloads for all Pushing and Popping methods that accept a boolean parameter to enable/disable animations.
  • INavigation contains methods needed for more complex navigation scenarios:

    public interface INavigation
    {
        IReadOnlyList<Page> NavigationStack { get; }
        IReadOnlyList<Page> ModalStack { get; }
    
        void RemovePage (Page page);
        void InsertPageBefore (Page page, Page before);
    
        Task PushAsync (Page page);
        Task<Page> PopAsync ();
        Task PopToRootAsync ();
        Task PushModalAsync (Page page);
        Task<Page> PopModalAsync ();
    
        Task PushAsync (Page page, bool animated);
        Task<Page> PopAsync (bool animated);
        Task PopToRootAsync (bool animated);
        Task PushModalAsync (Page page, bool animated);
        Task<Page> PopModalAsync (bool animated);
    }
    
  • New Application class to replace previous methods of turning a Page into a platform specific object.

  • New member on Page: protected virtual bool OnBackButtonPressed (): Override in order to handle physical back button press events. Events bubble down from root page and back up. Unhandled back button events will cause the app to exit. NavigationPage and the Platform still handle the back button as expected, however it is now possible to intercept and modify these behaviors. Not overriding this method retains the existing back button behavior.
  • DependencyService now has Register methods for users needing more advanced ways to register dependencies.
  • WidthRequest, HeightRequest, MinimumWidthRequest, and MinimumHeightRequest are now BindableProperties
  • IViewController, IVisualElementController, and IElementController now available and explicitly implemented on VisualElement. These interfaces will eventually replace all internal API's currently used to communicate between platform renderers and the frontend API.
  • IElementController.SetValueFromRenderer allows for updating of BindableProperties from renderers without accidentally clearing bindings.
  • XAML now supports text as the content node in Label: <Label>Hello World</Label>
  • Pin now has a Clicked property for detecting when the user taps or clicks on a Map pin after the information window is visible.
  • Layout constructor is now marked protected and not internal
  • Styles support Behaviors and Triggers
  • DataTrigger and MultiTrigger added
  • VisualElement.IsFocused is now a BindableProperty
  • Use * as default grid size
  • StaticResource searches in Application.Current.Resources too
  • Add NavigationPage.HasBackButton
  • Fix Fuchsia spelling, Obsolete the old spelling
  • TypeConverter on FontSize
  • SearchBar.CancelButtonColor (currently only supported on iOS)
  • ListView context actions

Bug Fixes

Core

  • Bindings are culture unaware
  • SetValue now properly overrides settings from a Style when the Style is applied later.
  • Grid now has more nuanced reflow logic for things like labels. This fixes some cases where grid would end up either too small or too large for its content.
  • Fix crash in XAML with DataTemplates and event subscription.
  • ListView/TableView respect WidthRequest/HeightRequest again (regression in 1.3.0-pre2)
  • No longer crash when trying to download/access the same UriImageSource on hundreds of images (System.IOException).
  • Fix issue where Grid sometimes measured out taller than it should, especially in ListView/StackLayout. Grid now prefers to expand in the direction of a "defined" constraint, which tends to match expected behavior when measuring. If both constraints are Infinite, previous behavior is retained.
  • BindableObject.SetValue will now properly perform loss-less conversions on base types. e.g. Calling slider.SetValue (Slider.ValueProperty, 6.0f) will now work correctly.
  • Fix issue where StackLayout in a Horizontal orientation would return an incorrect MinimumHeight in GetSizeRequest.
  • Adding a bad Path to a UriImageSource no longer crashes
  • Improved XAML error reporting
  • Fix crash where calling Navigation.PushAsync from re-initialized View sometimes crashed
  • Fix error where cloning a Binding did not clone the Source parameter
  • IsPresented is now respected correctly when using MasterDetailPage. May throw exception now if IsPresented is set to a disallowed value with MasterBehavior.
  • Several bugs relating to culture invariance in XAML parsing.
  • ThicknessConverter no longer depends on device culture
  • Label properly resizes after setting Label.FontSize/Font/FontAttributes Bug
  • XAML InitializeComponent calls in some apps this will result in a massive performance improvement when loading pages.
  • Serialization now property supports DataMemberAttributes
  • ListView and TableView now return consistent sizing across all platforms. This change should not affect most apps, however some apps suffering from inconsistent sizing with ListViews/TableViews should find the situation better.
  • Small set of changes to Layout to enable performance optimization with unneeded measure invalidation.
  • Don't throw NRE in ResourceDictionaries when reparenting
  • Fix map issue with IsShowingUser and location
  • fix binding against arrays (https://bugzilla.xamarin.com/show_bug.cgi?id=24263)
  • Resolve issue where Labels didn't reflow correctly inside of grids
  • RelativeLayout now gives sane error when relative to non-child view
  • fix NRE on removing ListView items (https://bugzilla.xamarin.com/show_bug.cgi?id=23778)
  • x:Reference now works inside other markup extensions.

Android

  • Pressing back and re-entering the app now cleans up the old Activity and associated renderers. This fixes both memory leak issues and some crashes.
  • Label.FontSize = 18 no longer accidentally gives a font size of 14 on any devices.
  • Fix another case where ScrollView content could flow outside of bounds (yay).
  • Fix crash in WebView when being removed from the visual tree.
  • Map no longer re-centers on Layout.
  • MasterDetailPage container width now matches android design guidelines on tablets. (No longer insanely wide).
  • SwitchCell height is no longer squished
  • No longer crashes on Android 5.0
  • No longer renders with a black bar at the bottom of Android 5.0 devices
  • Other compatibility fixes with Android 5.0
  • WebViewRenderer now uses correct path for finding resources
  • Fix issue where calling SetPage multiple times would throw an exception
  • Fix crash when restarting the Activity introduced in last pre-release
  • Fix issue where ListView.SelectedItem = null sometimes did not work as expected.
  • Fix issues where Switch did not show on some Samsung devices
  • Fix issue where rotation ignored the anchor point
  • Fix Button text allignment issue (https://bugzilla.xamarin.com/show_bug.cgi?id=21138, https://bugzilla.xamarin.com/show_bug.cgi?id=21368)

iOS

  • Renderers are now properly re-used in ListView. Performance enhancement.
  • iOS 8 now uses UIAlertController for alerts.
  • Fix a case where the keyboard could end up overlapping the input area.
  • Mixing swipe to go back and press to go back no longer results in a blank page.
  • ContextAction More/Cancel buttons now translate properly
  • ImageCell no longer flashes old image on cell re-use.
  • Slider now updates bindings correctly due to conversion fix.
  • Button.Image is now rendered with original image to match other platforms
  • Editor now scrolls to the correct location when a keyboard is shown
  • Fix NullReferenceException when assigning to SearchBar.BackgroundColor
  • Fix issue where PushModalAsync could sometimes result in a unhandled exception from UIKit.
  • MasterDetailPage now disposes of child renderers correctly, resolves a memory leak.
  • Fix issue where cells could not be unselected using blank rows.
  • WebViewRenderer now uses correct path for finding resources
  • Resolve issue where calling CreateViewController multiple times would cause an exception
  • Use proxy when downloading images if configured on device.
  • Partial swipes on a NavigationPage no longer cause the NavigationPage to get out of sync with the UINavigationController
  • ActionSheet now correctly shows on iOS 8
  • ActionSheet no longer gets incorrectly positions when rotating while visible.
  • Fix issue on Translating views of zero size
  • Select picker first item (https://bugzilla.xamarin.com/show_bug.cgi?id=22352)
  • TabbedPage now updates icons correctly
  • Fix several memory leaks
  • Modal dialog scrolls to far (https://bugzilla.xamarin.com/show_bug.cgi?id=23904)
  • Fix NRE when disposing some renderers.

WinPhone

  • Fix crash when pressing back button with active ActionSheet.
  • TableView no longer selects wrong item when in Landscape mode.
  • OpenUriAction now uses LaunchUriAsync.
  • Back button now closes ActionSheets and Alerts before attempting Navigation.
  • Picker no longer shows a bunch of blank entries.
  • ListView selection now properly shows up.
  • ListView allows selection of items multiple times in a row if the user calls SelectedItem = null. This behavior matches other platforms correctly now.
  • Label now reports the correct minimum width to match other platforms.
  • Fix crash in Picker

Two-finger touchpad scroll is way too fast in Xamarin Studio on Windows

0
0

I have a Samsung 9 Series Windows 8.1 laptop with two-finger scroll touchpad which works nice in all applications but Xamarin Studio. Even a short gesture scrolls a whole document while in say Chrome same thing scrolls just a few lines. Same time scroll from a mouse works well. I feel there is something in GTK but can't find a solution.

Here is what Spy++ shows:

<002192> 0070080C P WM_MOUSEWHEEL fwKeys:0000 zDelta:-120 xPos:787 yPos:587 - scroll from a mouse, zDelta is always +120 or -120 <002191> 0070080C P WM_MOUSEWHEEL fwKeys:0000 zDelta:-3 xPos:938 yPos:562 - scroll from a touchpad, zDelta varies according to gesture speed, usually it is +3 or -3.


Converting from Starter to trail

Issues with InApp Purchase component

0
0

Hi

I’m trying to implement InApp Purchases in my app by using the InApp Purchase component.

The problem is that I can’t download the content for the non-consumable product when I hosts it at Apple. If I dont host it at apple I can purchase the item without any problems (as I can see it ).

After I have called

_purchaseManager.BuyProduct (ITunesIdentifier);

The event for download InAppPurchaseContentDownloadInProgress is published, but after a while, less than a second in this case the event InAppPurchaseContentDownloadFailed is published. I can’t get much information about from the download instance. So not sure where to start looking.

`_purchaseManager.TransactionObserver.InAppPurchaseContentDownloadFailed += ((download) => {

Console.Out.Write("error"); });`

Added the content by using this guide. http://www.techotopia.com/index.php/Configuring_and_Creating_App_Store_Hosted_Content_for_iOS_6_In-App_Purchases and using the latest version of the component (v2.2).

If I query the inventory after it has failed, the product is marked as not purchased but receipt has a value. I have noticed that the ProductType is “Unknown”. Havent noticed any persistens error.

Any ideas?

How to add the content of a Frame as a Subview in an UIView? (Add Views as subviews of UIView?)

0
0

I'm using the RoundedBoxViewRenderer example from here (http://developer.xamarin.com/guides/cross-platform/xamarin-forms/custom-renderer/) and I updated it to inherit from Frame and not BoxView because I want a rounded Frame. The frame is rendering rounded.

The problem is that the custom renderer is drawn on top of the content thus the Frame's content is hidden.

So my question is: how to customise a Frame while keeping the content? Or a generic question would be: How to add Xamarin.Form Views as subviews of UIView or Android Views?

This is the Box custom renderer:

        var rbv = e.NewElement;

        if (rbv != null) {
            var shadowView = new UIView();

            childView = new UIView() {
                BackgroundColor = rbv.Stroke.ToUIColor(),
                Layer = {
                    CornerRadius = (float)rbv.CornerRadius,
                    BorderColor = rbv.Stroke.ToCGColor(),
                    BorderWidth = (float)rbv.StrokeThickness,
                    MasksToBounds = true
                },
                AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
            };

            shadowView.Add(childView);

            if (rbv.HasShadow) {
                shadowView.Layer.ShadowColor = UIColor.Black.CGColor;
                shadowView.Layer.ShadowOffset = new SizeF(3, 3);
                shadowView.Layer.ShadowOpacity = 1;
                shadowView.Layer.ShadowRadius = 5;
            }

            SetNativeControl(shadowView);
        }

How can I do something like this?

            shadowView.Add(rbv.Content);
            // or
            childView.AddSubview (rbv.Content);

Managing App lifecycle for Xamarin.Forms 1.3

Invalid number of rows in section

0
0

I trying to bind a ListView with an ObservableCollection. It works on both Windows Phone and Android but when running it on iOS I get an exception. The message says:

MonoTouch.Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (130) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

 public partial class TransfersView : ContentPage
     {
         public TransfersView(TransfersViewModel model)
         {
             InitializeComponent();

             BindingContext = model;  
         }
     }


  <ListView x:Name="Transfers" ItemsSource="{Binding Transfers}">
     <ListView.ItemTemplate>
       <DataTemplate>
         <TextCell Text="{Binding Player}" />
       </DataTemplate>
     </ListView.ItemTemplate>
   </ListView>

Does anyone has a solution?

ToolbarItem appearance iOS

0
0

I want to add a ToolbarItem with a custom image to the toolbar.

The code I use to accomplish this: ToolbarItems.Add (new ToolbarItem ("Hint", "ToolbarIcon.png", () => { //Do something
}));

The image of the ToolbarItem is correctly shown on Android. Unfortunately it won't show correctly on iOS. I see a blue color instead of the original image colors. Look at the screenshots to see the result. (first screenshot is iOS and second is Android)

What can I do to get the ToolbarItem show correctly on iOS? So without a color on top of the original image.

I already tried to add the following snippet to the FinishedLaunching method in AppDelegate.cs (= iOS specific) UIBarButtonItem.Appearance.TintColor = UIColor.FromWhiteAlpha (1f, 0f);

Although this won't do the trick.

iOS ListView broke with 1.3 Upgrade

0
0

Ever since upgrading to Xamarin.Forms 1.3 I get the following exception when I try to populate my ListView from data retrieved from a REST apt

MonoTouch.Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (4), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

I have seen a couple other references to this problem and seen the following solutions suggested: 1. Use List instead of ObservableCollection 2. Use Device.BeginInvokeOnMainThread to update collections from the UI thread 3. Call BindingBase.EnableCollectionSynchronization when setting up the collection

I have tried these all and they have not worked for me (or I have applied them incorrectly) so I am asking for the communities help with this.

Below is the relevant code as it was working in 1.2 but not in 1.3 (on iOS; Android works fine)

FolderViewPage.xaml.cs

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        if(BindingContext != null)
            return;

        if (!RestClient.IsInitialized) 
        {
            await Navigation.PushModalAsync(LoginPage.GetLoginPage(OnAppearing));
        }
        else
        {
            InitializeVm();
        }
    }


    private void InitializeVm()
    {
        var vm = new FolderViewModel(_name);
        _folderVm = vm;
        BindingContext = _folderVm;
        _folderVm.LoadFolder(_id);
        FolderListView.ItemsSource = _folderVm.CredentialGroups;
    }

FolderViewModel.cs

   public ObservableCollection<CredentialListViewModel> CredentialGroups;

    public FolderViewModel(string name)
    {
        FolderName = name ?? "Root";
        IsEmpty = false;
        CredentialGroups = new ObservableCollection<CredentialListViewModel>();
    }

    public async Task LoadFolder(Guid id)
    {
        IsBusy = true;

        try
        {
            if (id == Guid.Empty)
            {
                IsRoot = true;
                id = await RestClient.GetRootCredentialGroupId();
            }
            else
            {
                IsRoot = false;
            }

            //if id is not present here then something has gone wrong.
            if (id == Guid.Empty)
            {
                MessagingCenter.Send(this, App.ErrorMessage, "Could not get root folder identifier");
                return;
            }

            var group = await RestClient.GetCrendentialGroup(id);

            CredentialGroups.Clear();
            var vms = group.Children.OrderBy(c => c.Name).Select(CredentialListViewModel.FromGroup).Concat(group.Credentials.OrderBy(c => c.Name).Select(CredentialListViewModel.FromCredential));
            foreach (var vm in vms)
            {
                CredentialGroups.Add(vm);
            }
            IsBusy = false;

            if (!CredentialGroups.Any())
                IsEmpty = true;
        }
        catch (TokenExpiredExecption)
        {
            MessagingCenter.Send(this, App.TokenExpiredMessage, new Action(() => LoadFolder(id)));
        }
        catch (BusinessWebException ex)
        {
            string message;
            switch (ex.FailureCode)
            {
                case HttpStatusCode.BadRequest:
                    message = "Bad Request";
                    break;
                case HttpStatusCode.Unauthorized:
                    message = "Authentication failed";
                    break;
                case HttpStatusCode.Forbidden:
                    message = "You do not have access to this folder";
                    break;
                case HttpStatusCode.NotFound:
                    message = id == Guid.Empty ? "Unable to locate root folder" : "Unable to locate this folder";
                    break;
                case HttpStatusCode.InternalServerError:
                    message = "Internal server error";
                    break;
                default:
                    message = "No further information available";
                    break;
            }
            MessagingCenter.Send(this, App.ErrorMessage, message);

        }
        catch (BusinessException ex)
        {
            MessagingCenter.Send(this, App.ErrorMessage, ex.Message);
        }

    }

Can anyone offer any assistance in this matter?


Zxing not working on iOS 8

0
0

HI I am was using zing for bar code scanner. Before upgrade to iOS 8.0, it was working fine. But after update its throwing below error though I am using a actual device.

Starting to scan... StartScanning No input - this won't work on the simulator, try a physical device Capture Session FAILED

Same code has been used. I tried using latest version of zing but no luck. Does any body faced same problem?

Thanks in advance.

Application requested unusual termination error

0
0

Hi, I restarted Xamarin Studio today and I'm now getting the attached error.

I uninstalled and reinstalled with latest version, no luck. Uninstalled an reinstalled oldest available version (XamarinStudio-5.3.0.441-0.msi). Both produce same error.

Do I have to reinstall Windows (7 x86) to get round this?

Regards

Error XA9021: Invalid license. Please reactivate

0
0

Hi All, I'm on OSX and I have just upgraded my Android from Starter Edition to Indie, but now I can't build any Android project due to the error in the title. I have deleted my MonoAndroid folder in Library.. I've tried running Xamarin Studio as Administrator... pretty much out of ideas here, but not overly impressed that paying for an Indie license has actually just left me worse off, overall.

Oh and I also deleted Android API 19, just in case that was the problem (saw some post about that from a year or so ago)...

Thanks in advance for your help!

InAppPurchaseManager not Persisting

0
0

Hi guys,

I am unable to restore my previous purchases using the InAppPurchaseManager , once I have closed the application down and loaded it again on an actual iPhone.

When I run the debugger in simulation mode, it works as expected. If I restart the Debugger, it checks to see if the product has been purchased, and it has. Great. However, once I run it against iTunes on a device, it fails to realize that I have persisted the previous purchases to the phone. There doesn't seem to be any persist errors occurring either. Just to note, it successfully makes the iTunes purchase in the Sandbox environment.

Here is my Persistance logic within the AppDelegate method.

    private void InitializeInAppPurchaseManager()
    {
        // Assembly public key
        string value = Security.Unify(
            new string[] { "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtpopeFYhDOOsufNhYe2PY97azBQBJoqGSP/XxsgzQgj3M0MQQ0WE0WDwPKoxlo/MIuoadVR5q2ZRs3rTl", 
                "UsH9vYUPr/z0/O8kn5anQHshQkHkeHsA8wbyJGGmwcXqvZr1fnzFOFyHL46s47vOJBLc5x30oieJ02dNxdBcy0oFEJtJS5Ng5sm6YUv9ifgxYOqMr/K61HNw6tP0j", 
                "vi6vLv2ro/KXO0ADVxcDxEg+Pk16xVNKgnei8M09PJCgA9bWNyeSsD+85Jj9+OZGsS/DN7O7nrGuKx8oAg/lE6a2eCQHh9lXxSPlAFAMH2FB8aNxUeJxkByW+6l/S", 
                "yqvVlOeYxAwIDAQAB" },
            new int[] { 0, 1, 2, 3 });

        // Initialize the In App Purchase Manager
        _purchaseManager.SimulateiTunesAppStore = false;
        _purchaseManager.PublicKey = value;
        _purchaseManager.CheckInternetConnection = true;

        // Warn user that the store is not available
        if (_purchaseManager.CanMakePayments)
        {
            Console.WriteLine("Xamarin.InAppBilling: User can make payments to iTunes App Store.");
        }
        else
        {
            //Display Alert Dialog Box
            using (var alert = new UIAlertView("Apple Store", "Sorry but you cannot make purchases from the In App Billing store. Please try again later.", null, "OK", null))
            {
                alert.Show();
            }
        }

        // Warn user if the Purchase Manager is unable to connect to
        // the network.
        _purchaseManager.NoInternetConnectionAvailable += () =>
        {
            Console.WriteLine("No open internet connection is available");
        };

        // Show any invalid product queries
        _purchaseManager.ReceivedInvalidProducts += (productIDs) =>
        {
            // Display any invalid product IDs to the console
            Console.WriteLine("The following IDs were rejected by the iTunes App Store:");
            foreach (string ID in productIDs)
            {
                Console.WriteLine(ID);
            }
            Console.WriteLine(" ");
        };

        // Report the results of the user restoring previous purchases
        _purchaseManager.InAppPurchasesRestored += (count) =>
        {

        };

        // Report miscellanous processing errors
        _purchaseManager.InAppPurchaseProcessingError += (message) =>
        {
            Console.WriteLine(message);
        };

        // Report any issues with persistence
        _purchaseManager.InAppProductPersistenceError += (message) =>
        {
            Console.WriteLine(message);
        };

        // Setup automatic purchase persistance and load any previous purchases
        _purchaseManager.AutomaticPersistenceType = InAppPurchasePersistenceType.LocalFile;
        _purchaseManager.AutoPersistAfterPurchase = true;
        _purchaseManager.PersistenceFilename = "AtomicData";
        _purchaseManager.ShuffleProductsOnPersistence = false;
        _purchaseManager.RestoreProducts();

        // Setup the list of simulated purchases to restore when doing a simulated restore of pruchases
        // from the iTunes App Store
        _purchaseManager.SimulatedRestoredPurchaseProducts = AppStoreProducts[0];
    }

If I then call this method and check an already purchased product, it returns false

//create the in app purchase manager InitializeInAppPurchaseManager();

//had the user purchased the consumable? var hasBeenPurchased = _purchaseManager.ProductPurchased("com.test.nonconsumable.product);

Always returns false on the iPhone/iPad.

Will this work once its been deployed to the App store, or is this just default behavior once you test in on an actual Phone?

Has anyone else had experience with this component? What am I not doing?

Regards Justin

Google Play Services 22.0.0.0

0
0

I am unable to install this component into Xamarin Studio Version 5.5.4 on Mac OS X 10.10.1

I get the following error - "Error downloading component: Manifest file is missing Retry" Clicking the Retry link just repeats the problem.

My target framework is Android 4.0.3

What does this mean? How can I resolve this issue?

Viewing all 204402 articles
Browse latest View live




Latest Images