Showing posts with label xamarin.android. Show all posts
Showing posts with label xamarin.android. Show all posts

Sunday, October 14, 2018

How to implement TabLayout.IOnTabSelectedListener.OnTabUnselected with TabbedPage.ToolbarPlacement=“Bottom” - Xamarin Forms?

Leave a Comment

I just recently used android:TabbedPage.ToolbarPlacement="Bottom". I used to have the following code:

void TabLayout.IOnTabSelectedListener.OnTabUnselected(TabLayout.Tab tab) {    var playPage = Element.CurrentPage as NavigationPage;    if (!(playPage.RootPage is PhrasesFrame))       return;     var tabLayout = (TabLayout)ViewGroup.GetChildAt(1);    var playTab = tabLayout.GetTabAt(4);    tab.SetText("Play");    tab.SetIcon(Resource.Drawable.ionicons_2_0_1_play_outline_25);    App.pauseCard = true; } 

Anyone knows how can I implement this with ToolbarPlacement="Bottom" ? I have implemented both BottomNavigationView.IOnNavigationItemSelectedListener, BottomNavigationView.IOnNavigationItemReselectedListener but can't find any reference for UnselectedTab if there is any.

Edit:

Previous custom renderer using the default tab position and implementing TabLayout:

namespace Japanese.Droid {     public class MyTabbedPageRenderer: TabbedPageRenderer, TabLayout.IOnTabSelectedListener     {         ViewPager viewPager;         TabLayout tabLayout;         bool setup;          public MyTabbedPageRenderer(Context context): base(context){ }          protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)         {             // More codes here         }          void TabLayout.IOnTabSelectedListener.OnTabReselected(TabLayout.Tab tab)         {             UpdateTab(tab);         }          void TabLayout.IOnTabSelectedListener.OnTabSelected(TabLayout.Tab tab)         {             UpdateTab(tab);         }          void TabLayout.IOnTabSelectedListener.OnTabUnselected(TabLayout.Tab tab)         {             var playPage = Element.CurrentPage as NavigationPage;             if (!(playPage.RootPage is PhrasesFrame))                 return;              var tabLayout = (TabLayout)ViewGroup.GetChildAt(1);             var playTab = tabLayout.GetTabAt(4);             tab.SetText("Play");             tab.SetIcon(Resource.Drawable.ionicons_2_0_1_play_outline_25);             App.pauseCard = true;         }          void UpdateTab(TabLayout.Tab tab)          {             // To have the logic only on he tab on position 1             if (tab == null || tab.Position != 4)             {                 return;             }              if (tab.Text == "Play")             {                 tab.SetText("Pause");                 tab.SetIcon(Resource.Drawable.ionicons_2_0_1_pause_outline_22);                 App.pauseCard = false;             }             else             {                 tab.SetText("Play");                 tab.SetIcon(Resource.Drawable.ionicons_2_0_1_play_outline_25);                 App.pauseCard = true;             }         }     } } 

Current custom renderer using the ToolbarPlacement="Bottom":

namespace Japanese.Droid {     public class BottomTabPageRenderer : TabbedPageRenderer, BottomNavigationView.IOnNavigationItemSelectedListener, BottomNavigationView.IOnNavigationItemReselectedListener     {         public BottomTabPageRenderer(Context context) : base(context) { }          protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)         {             base.OnElementChanged(e);              // More codes here         }          bool BottomNavigationView.IOnNavigationItemSelectedListener.OnNavigationItemSelected(IMenuItem item)         {             base.OnNavigationItemSelected(item);              UpdateTab(item)         }          void BottomNavigationView.IOnNavigationItemReselectedListener.OnNavigationItemReselected(IMenuItem item)         {             UpdateTab(item);         }          void UpdateTab(IMenuItem item)         {             var playTabId = 4;              var title = item.TitleFormatted.ToString();             if (item == null || item.ItemId != playTabId)             {                 return;             }              if (item.ItemId == playTabId)             {                 if (title == "Play")                 {                     item.SetTitle("Pause");                     item.SetIcon(Resource.Drawable.ionicons_2_0_1_pause_outline_22);                     App.pauseCard = false;                 }                 else                 {                     item.SetTitle("Play");                     item.SetIcon(Resource.Drawable.ionicons_2_0_1_play_outline_25);                     App.pauseCard = true;                 }             }          }      } } 

So now my problem is I don't have any idea how will I implement the TabLayout.IOnTabSelectedListener.OnTabUnselected in the new custom renderer.

2 Answers

Answers 1

There is no official stuff for OnTabReselected event for TabbedPage's bottom navigation or BottomNavigationView because It doesn't use TabLayout.Tab for a start. Many overridden methods of TabbedPageRenderer not being called like SetTabIcon. If you are using IOnTabSelectedListener interface(As your first part of code) you have three methods to use.

void OnTabReselected(Tab tab); void OnTabSelected(Tab tab);           void OnTabUnselected(Tab tab); 

But when it comes to BottomNavigationView interface you have only two methods

void OnNavigationItemReselected bool OnNavigationItemSelected 

So we don't have built in OnTabUnselected method. Here you need to write custom code to make unseleted event.

I have tried this code without using custom renderer using 4 tabs pages & the xaml of tabbed written in MailPage.xaml file. First declare List<string> in App.xaml.cs file to store Title of all tabs

public static List<string> Titles {get;set;} 

Add tabs pages title in above list from MainPage.xaml.cs file's OnAppearing method

protected override void OnAppearing() {     for (int i = 0; i < this.Children.Count; i++)     {         App.Titles.Add(this.Children[i].Title);     } } 

Now go to your MyTabbedPage class in which is available in shared project.

public class MyTabbedPage : Xamarin.Forms.TabbedPage {     string selectedTab = string.Empty;     string unSelectedTab = string.Empty;     bool isValid;      public MyTabbedPage()     {         On<Xamarin.Forms.PlatformConfiguration.Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);          this.CurrentPageChanged += delegate         {             unSelectedTab = selectedTab;             selectedTab = CurrentPage.Title;             if (App.Titles != null)                 isValid = true;             else                 App.Titles = new List<string>();             if (isValid)             {                 MoveTitles(selectedTab);                //Pass 0 index for tab selected & 1 for tab unselected                 var unSelecteTabTitle = App.Titles[1];                //TabEvents(1); here you know which tab unseleted call any method             }         };     }      //This method is for to moving selected title on top of App.Titles list & unseleted tab title automatic shifts at index 1     void MoveTitles(string selected)     {         var holdTitles = App.Titles;         if (holdTitles.Count > 0)         {             int indexSel = holdTitles.FindIndex(x => x.StartsWith(selected));             holdTitles.RemoveAt(indexSel);             holdTitles.Insert(0, selected);         }         App.Titles = holdTitles;     }      } 

Or you can make swith case like this

void TabEvents(int index) {   switch (index)   {     case 0:         //Tab selected         break;     case 1:          //Tab unselected         break;   } } 

Few things I should mention that MainPage.xaml.cs file inheriting MyTabbedPage

public partial class MainPage : MyTabbedPage 

Structure of MainPage.xaml file

<?xml version="1.0" encoding="utf-8" ?> <local:MyTabbedPage         <TabbedPage.Children>          <NavigationPage Title="Browse">              </NavigationPage>         </TabbedPage.Children> </local:MyTabbedPage> 

Answer seems long but hope it help you.

Answers 2

As per G.Hakim's suggestion, I was able to do what I wanted to do by capturing the tab item I wanted to work on and do the necessary actions in BottomNavigationView.IOnNavigationItemSelectedListener.OnNavigationItemSelected.

namespace Japanese.Droid {     public class BottomTabPageRenderer : TabbedPageRenderer, BottomNavigationView.IOnNavigationItemSelectedListener, BottomNavigationView.IOnNavigationItemReselectedListener     {         // same as above          bool BottomNavigationView.IOnNavigationItemSelectedListener.OnNavigationItemSelected(IMenuItem item)         {             base.OnNavigationItemSelected(item);              if(item.ItemId == 4 && item.TitleFormatted.ToString() == "Play")              {                 item.SetTitle("Pause");                 item.SetIcon(Resource.Drawable.ionicons_2_0_1_pause_outline_22);                 App.pauseCard = false;                 playTab = item;             }               if(item.ItemId !=4 && playTab.TitleFormatted.ToString() == "Pause")              {                 playTab.SetTitle("Play");                 playTab.SetIcon(Resource.Drawable.ionicons_2_0_1_play_outline_25);                 App.pauseCard = true;             }             return true;         }          // same as above      } } 
Read More

Saturday, October 13, 2018

Select multiple bitmaps using OnTouchEvent

Leave a Comment

I am developing a card based game, in which user can select one or multiple cards from its deck and replace the cards with cards of other decks. I am using onTouchEvent to detect whether the user has selected any bitmap or not and replace that Bitmap with Bitmap of other deck. However OnTouchEvent only allows me to select one bitmap at a time. How can I select multiple bitmaps from my deck? Also I want to know if there is any better approach to swap bitmaps other than the one I used.

Thread Class:

 class MySurfaceViewThread:BaseThread {     private MySurfaceView mysurfaceview;     private ISurfaceHolder myThreadSurfaceHolder;     bool running;      public MySurfaceViewThread(ISurfaceHolder paramSurfaceHolder, MySurfaceView paramSurfaceView)     {         mysurfaceview = paramSurfaceView;         myThreadSurfaceHolder = paramSurfaceHolder;      }     public override void RunThread()     {          Canvas c;         while (running)         {             c = null;             try             {               c = myThreadSurfaceHolder.LockCanvas(null);                  mysurfaceview.Render(c);            //  mysurfaceview.PostInvalidate();              }             catch (Exception ex)             {                 System.Diagnostics.Debug.WriteLine(ex.ToString());             }             finally             {                 if (c != null)                 {                     myThreadSurfaceHolder.UnlockCanvasAndPost(c);                    }              //   running = false;             }          }      }     public override void SetRunning(bool paramBoolean)     {         running = paramBoolean;     } } 

OnTouchEvent:

 public override bool OnTouchEvent(MotionEvent e)     {         Log.Debug(Tag, "Inside" + System.Reflection.MethodBase.GetCurrentMethod().Name + "Method");         float lasttouched_X, lasttouched_Y;         Cards localcard;         int index=-1;          //switch (e.Action) {          //    case MotionEventActions.Up: Log.Info(Tag, "Up Event is Triggered");         //        break;         //    case MotionEventActions.Move: Log.Info(Tag, "Move Event is Triggered");         //        break;         //    case MotionEventActions.Down: Log.Info(Tag, "Down Event is triggered");          //        break;          //}         MotionEventActions action = e.Action;         if (e.Action == MotionEventActions.Down || e.Action== MotionEventActions.Move)         {             Log.Info(Tag, "Down Event is triggered");             lasttouched_X = e.GetX();             lasttouched_Y = e.GetY();             if (TouchedCard == null)             {                 index = CardTouched((int)lasttouched_X, (int)lasttouched_Y);                 TouchedCard = MainPlayer.getCard(index);                 cardindex = index;             }             else             {                 if (TouchedCard != null && ((lasttouched_X >= DiscardDeck_CurrentX && lasttouched_X < (DiscardDeck_CurrentX + DiscardedDeck.getCard().Image.Width)) && (lasttouched_Y >= DiscardDeck_CurrentY && lasttouched_Y < (DiscardDeck_CurrentY + DiscardedDeck.getCard().Image.Width))))                 {                     ReplacedCard = DiscardedDeck.getCard();                 }                  if (ReplacedCard != null)                     SwapCards(ReplacedCard, MainPlayer, cardindex);             }          }         return true;     }      private void SwapCards(Cards replacedCard, Deck mainPlayer, int index)     {          Cards temp = mainPlayer.getCard(index);         mainPlayer.SetCurrentCard(replacedCard, index);         DiscardedDeck.SetCurrentCard(temp, DiscardedDeck.CardsLeft()-1);         TouchedCard = null;         cardindex = -1;      }      private int CardTouched(int lasttouched_X, int lasttouched_Y)     {         int index = 0;         Cards localcard = null;         while (index < MainPlayer.CardsLeft())         {             localcard = MainPlayer.getCard(index);             if (lasttouched_X >= localcard.current_X && lasttouched_X < (localcard.current_X + localcard.Image.Width) && (lasttouched_Y>=localcard.current_Y && lasttouched_Y<(localcard.current_Y+localcard.Image.Width)))                 return index;             index++;         }          return -1;     } 

0 Answers

Read More

Sunday, September 9, 2018

How to update progressbar from customwebview renderer in xamarin forms for android?

Leave a Comment

I'm currently developing an app in Xamarin Forms with an Android background so I wanted to create an Android app first and an iOS app later.

I'm new to Xamarin Forms and I'm struggling on how to update a ProgressBar from a WebView using a custom renderer for the WebView.

In Android, you can do something like this, with the ProgressBar and WebView that are in the main_layout.xml

public class MainActivity extends Activity {      private ProgressBar progressBar;     private WebView webView;          @Override     protected void onCreate(Bundle savedInstanceState) {              super.onCreate(savedInstanceState);         setContentView(R.layout.main_layout);          progressBar = (ProgressBar) findViewById(R.id.progress);         webView = (AdvancedWebView) findViewById(R.id.webView);         // webview initialisation         webView.setWebChromeClient(new WebChromeClient(){             @Override             public void onProgressChanged(WebView view, int newProgress) {                 // update progressbar progress                 progressBar.setProgress(newProgress);            }        });         webView.setWebViewClient(new WebViewClient(this) {             @Override             public void onPageFinished(WebView view, String url) {                 // hide progressbar when it's done                 progressBar.setVisibility(View.GONE);             }         });     } } 

In Xamarin Forms I have this layout in MainPage.xaml in the shared project

<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="MainPage" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" NavigationPage.HasNavigationBar="False">  <Grid>     <Grid.RowDefinitions>         <RowDefinition Height="*" />         <RowDefinition Height="*" />         <RowDefinition Height="*" />         <RowDefinition Height="*" />     </Grid.RowDefinitions>      <ProgressBar         x:Name="progress"         Grid.Row="3"         HorizontalOptions="FillAndExpand"         Progress="0"         VerticalOptions="Center" />      <WebView         x:Name="webview"         Grid.Row="0"         Grid.RowSpan="4"         Grid.Column="0"         HorizontalOptions="FillAndExpand"         IsVisible="False"         Source="https://google.com"         VerticalOptions="FillAndExpand" />  </Grid> 

public partial class App : Application {     public App ()     {         InitializeComponent();          MainPage = new MainPage();      } } 

And this custom WebView render for android in the android project

[assembly: ExportRenderer(typeof(WebView), typeof(CustomWebviewRenderer))] namespace MyApp.Droid {     public class CustomWebviewRenderer: WebViewRenderer     {         private readonly Context context;          public CustomWebviewRenderer(Context context) : base(context)         {             this.context = context;         }          protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)         {             base.OnElementChanged(e);             var formsWebView = e.NewElement as Xamarin.Forms.WebView;              if (formsWebView != null)             {                 var webView = Control as Android.Webkit.WebView;                 webView.SetWebViewClient(new CustomWebViewClient());                  webView.SetWebChromeClient(new CustomWebChromeClient());                      webView.Settings.LoadWithOverviewMode = true;                 webView.Settings.UseWideViewPort = true;                 SetNativeControl(webView);             }         }          private class ScoritoWebChromeClient : WebChromeClient         {             public override void OnProgressChanged(Android.Webkit.WebView view, int newProgress)             {                 // how to update progressbar progress?                 base.OnProgressChanged(view, newProgress);                            }         }          private class CustomWebViewClient : WebViewClient         {             public override void OnPageFinished(Android.Webkit.WebView view, string url)             {                 // how to hide progressbar?                 base.OnPageFinished(view, url);             }              public override void OnPageStarted(Android.Webkit.WebView view, string url, Bitmap favicon)             {                 base.OnPageStarted(view, url, favicon);             }              public override bool ShouldOverrideUrlLoading(Android.Webkit.WebView view, IWebResourceRequest request)             {                 return base.ShouldOverrideUrlLoading(view, request);             }         }     } } 

How can I update the ProgressBar that I have in my MainPage.xaml from the OnPageFinished in the CustomWebviewRenderer class to show the webpage has finished loading? Should I use the MainActivity.cs in the Android project?

Can someone point me in the right direction on how to solve this?

1 Answers

Answers 1

You don't need custom renderers for what you are doing first and foremost.

Why don't you use the Navigating & Navigated Binding's in your Xamarin forms Webview?

<WebView x:Name="Webview"                          Navigating="OnNavigating"            Navigated="OnNavigated"            VerticalOptions="FillAndExpand"/>   

And then do this in your xaml.cs:

 protected async override void OnAppearing()       {           base.OnAppearing();            await progress.ProgressTo(0.9, 900, Easing.SpringIn);       }     private void OnNavigated(object sender, Xamarin.Forms.WebNavigatedEventArgs e)     {       progress.IsVisible = false;       }      private void OnNavigating(object sender, Xamarin.Forms.WebNavigatingEventArgs e)     {        progress.IsVisible = true;     } 

And this should be enough

But if you still insist to use your renderer what you can do is update the progress bar using the element property and get a callback or change a property something like below:

[assembly: ExportRenderer(typeof(WebView), typeof(CustomWebviewRenderer))]  namespace MyApp.Droid { public class CustomWebviewRenderer: WebViewRenderer {     private readonly Context context;    private MainPage MainPage     {         get         {             var mainPage = Element as MainPage;             return mainPage == null                 ? null                 : mainPage;         }     }     public CustomWebviewRenderer(Context context) : base(context)     {         this.context = context;     }      protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)     {         base.OnElementChanged(e);         var formsWebView = e.NewElement as Xamarin.Forms.WebView;          if (formsWebView != null)         {             var webView = Control as Android.Webkit.WebView;             webView.SetWebViewClient(new CustomWebViewClient());              webView.SetWebChromeClient(new CustomWebChromeClient());                  webView.Settings.LoadWithOverviewMode = true;             webView.Settings.UseWideViewPort = true;             SetNativeControl(webView);         }     }      private class ScoritoWebChromeClient : WebChromeClient     {         public override void OnProgressChanged(Android.Webkit.WebView view, int newProgress)         {             // how to update progressbar progress?             base.OnProgressChanged(view, newProgress);                        }     }      private class CustomWebViewClient : WebViewClient     {         public override void OnPageFinished(Android.Webkit.WebView view, string url)         {             // how to hide progressbar?             MainPage.yourCallbackFunc();             base.OnPageFinished(view, url);         }          public override void OnPageStarted(Android.Webkit.WebView view, string url, Bitmap favicon)         {             base.OnPageStarted(view, url, favicon);         }          public override bool ShouldOverrideUrlLoading(Android.Webkit.WebView view, IWebResourceRequest request)         {             return base.ShouldOverrideUrlLoading(view, request);         }     }   } } 

And get the callback in that xamarin forms page:

  public partial class MainPage: ContentPage  {      public MainPage()      {          InitializeComponent();       }      public void yourCallbackFunc()      {       .       . // Do some functionality       .       }  } 

In case it doesn't work or you have queries revert!

Read More

Friday, September 7, 2018

Xamarin iOS images overlapping inside Grid

Leave a Comment

Heyo,

So in Xamarin I have a <Grid> with an <Image> and a couple <Label>s inside it, all wrapped inside a <ViewCell>. This looks totally fine in Xamarin.Android, however in Xamarin.iOS the images overlap the labels. I'm not sure what the difference could be - why does it look good in Xamarin.Android but in iOS its all wonky?

Below is my XAML and a couple mockups to show what I mean.

<ListView.ItemTemplate>     <DataTemplate>         <ViewCell>             <ViewCell.View>             <Grid>                 <Grid.ColumnDefinitions>                 </Grid.ColumnDefinitions>                 <Grid.RowDefinitions>                 <RowDefinition Height="Auto" />                 <RowDefinition Height="Auto" />                 </Grid.RowDefinitions>                  <Image Grid.Column="0" Grid.Row="0" Aspect="AspectFill" Source="{Binding ImageOverlayEN}" />                 <Label Grid.Column="0" Grid.Row="1" VerticalTextAlignment="Start" LineBreakMode="WordWrap" Text="{Binding DynamicOfferText}" FontSize="18">                     <Label.FontFamily>                         <OnPlatform x:TypeArguments="x:String">                         <OnPlatform.iOS>RobotoCondensed-Regular</OnPlatform.iOS>                         <OnPlatform.Android>RobotoCondensed-Regular.ttf#RobotoCondensed-Regular</OnPlatform.Android>                         <OnPlatform.WinPhone>RobotoCondensed-Regular.ttf#RobotoCondensed</OnPlatform.WinPhone>                     </OnPlatform>                     </Label.FontFamily>                 </Label>                 <Label Grid.Column="0" Grid.Row="2" VerticalTextAlignment="Start" LineBreakMode="WordWrap" Text="{Binding DynamicOfferDetail}" FontSize="16">                     <Label.FontFamily>                         <OnPlatform x:TypeArguments="x:String">                         <OnPlatform.iOS>RobotoCondensed-Regular</OnPlatform.iOS>                         <OnPlatform.Android>RobotoCondensed-Regular.ttf#RobotoCondensed-Regular</OnPlatform.Android>                         <OnPlatform.WinPhone>RobotoCondensed-Regular.ttf#RobotoCondensed</OnPlatform.WinPhone>                     </OnPlatform>                     </Label.FontFamily>                 </Label>                 </Grid>             </ViewCell.View>         </ViewCell>     </DataTemplate> </ListView.ItemTemplate> 

I tried setting the HeightRequest but that didn't seem to make a difference:

#if __IOS__     if (viewModel.Items.Count > 0)     {         MyListView.HeightRequest = 300 * viewModel.Items.Count;     } #endif 

Here is a visual representation of what is happening:

enter image description here

1 Answers

Answers 1

Figured it out - had to do with my RowDefinitions being all set to Auto

This got it looking just right:

<RowDefinition Height="1*" /> <RowDefinition Height="0.18*" /> <RowDefinition Height="0.77*" /> 

I think what was happening is the ListView renders first, the Auto row definition heights set the height of each row before the image is done loading, then the image finishes loading and overlaps the rest of the list view's item (including the labels). This might just be a quirk of iOS, where as Android calculates the row heights after the images are done loading (explaining why it looked fine in Android)

Read More

Wednesday, September 5, 2018

NullReferenceException in System.Threading.Tasks.RangeWorker.FindNewWork in Android Xamarin app

Leave a Comment

In my Android native app created with Xamarin, I get the following crash report in HockeyApp:

Xamarin caused by: android.runtime.JavaProxyThrowable: System.NullReferenceException: Object reference not set to an instance of an object   at System.Threading.Tasks.RangeWorker.FindNewWork (System.Int64& nFromInclusiveLocal, System.Int64& nToExclusiveLocal) [0x00000] in <8f1acca5a43d45c5b8d35add5a11806a>:0    at System.Threading.Tasks.RangeWorker.FindNewWork32 (System.Int32& nFromInclusiveLocal32, System.Int32& nToExclusiveLocal32) [0x00000] in <8f1acca5a43d45c5b8d35add5a11806a>:0    at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () <0xec919968 + 0x00033> in <8f1acca5a43d45c5b8d35add5a11806a>:0 

I cannot figure out what is causing this exception since the stack trace only contains .net code. I have looked at the framework's source code to see if I could make sense of it but to no avail.

I have also tried many different searches in my favorites search engines without finding any posts/articles about similar issues.

From the data associated with those crashes, it seems to be an issue happening exclusively on Samsung devices (S8, S8+ and Note8). I cannot be 100% sure that it doesn't affect other devices but I only have crash reports for those.

Any idea what could cause those crashes? Am I doing something wrong with threading, maybe with cancellation tokens? Are there conditions I am not handling correctly?

Any help to further troubleshoot this issue would be very welcomed.

Thank you

EDIT:

I understand that there is not much to go by but being that this is the only stacktrace I get in HockeyApp and I cannot repro, I have no idea what code causes this.

What I am looking for is more a clue about what could cause Mono threading code to have a null reference exception when I am not managing the threads myself. Or maybe this stacktrace is just a red herring and I need to be looking in other places?

3 Answers

Answers 1

What caught my attention was the FindNewWork32 call -- link for the .NET implementation. Your app may be compiled for 32-bit architecture, and those Samsung devices you mentioned have a 64-bit processor.

This Microsoft paper shows how to target an app to one or more Android-supported CPU architectures. You may need to target multiple platforms:

To target multiple CPU architectures, you can select more than one ABI (at the expense of larger APK file size). You can use the Generate one package (.apk) per selected ABI option (described in Set Packaging Properties) to create a separate APK for each supported architecture.

You do not have to select arm64-v8a or x86_64 to target 64-bit devices; 64-bit support is not required to run your app on 64-bit hardware. For example, 64-bit ARM devices (such as the Nexus 9) can run apps configured for armeabi-v7a. The primary advantage of enabling 64-bit support is to make it possible for your app to address more memory.

Answers 2

I know this answer is not specific for your issue, but when you are dealing with an exception message, which is so brief, it's always a good idea to check system-wide logging. In case of Android, you might get more information using dmesg command (which is giving you the content of /var/log/messages file).

Good luck

Answers 3

You should call .IsCompleted or .Wait() soon after callback. If you do it before the Context objects might go away and if your code is accessing those Context objects will be arbitrarily null (removed). If you call Task.Wait() it would block the thread and then throw an AggregateException once the worker throws it. Try using try catch block to handle exception.

Issue JavaProxyThrowable not always happening due to calling service there might be your activity null some where. You should check null before using activity context.

Read More

Xamarin.Forms app crashes after update

Leave a Comment

I have checked all the questions raised in SO like this and i couldn't find answer to my issue.

We had an app in PlayStore which is developed in Xamarin.Android with code shared with Xamarin.iOS via Shared Project.

Now we are switching to Xamarin.Forms. We have changed , Some UI Login mechanism with AutoLogin based on Token stored in local device.

The app working fine in Devices and Simulators.

We have uploaded our app to playstore. If the user have old version in their device, after update the app crashing after showing splashscreen for few seconds. If we uninstall the old version, it is working fine.

Error in google console:

    java.lang.RuntimeException:  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2955)  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java030)  at android.app.ActivityThread.-wrap11 (Unknown Source)  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1696)  at android.os.Handler.dispatchMessage (Handler.java:105)  at android.os.Looper.loop (Looper.java:164)  at android.app.ActivityThread.main (ActivityThread.java:6938)  at java.lang.reflect.Method.invoke (Native Method)  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java27)  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)  Caused by: java.lang.ClassCastException:  at android.app.SharedPreferencesImpl.getLong (SharedPreferencesImpl.java:279)  at md56c96bd185bfbb3ebebdd94ef17444e8f.MainActivity.n_onCreate (Native Method)  at md56c96bd185bfbb3ebebdd94ef17444e8f.MainActivity.onCreate (MainActivity.java1)  at android.app.Activity.performCreate (Activity.java:7174)  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1220)  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2908) 

We are not sure why this is happening. Can any one let me know, why this happening and how to prevent it. Also, is it possible reproduce this issue in VisualStudio?

Thanks

1 Answers

Answers 1

Probably your SharedPreferences parameters have incompatible types. And I didn't found a proof that it could be xamarin.Forms problem. If you look at the source code SharedPreferencesImpl.java to the getLong method you will see the following cast:

Long v = (Long)mMap.get(key); 

This means that on old versions there was parameter with the same name but with type different from Long. You read this parameter in onCreate method of your MainActivity, but parameter type is incompatible.

Read More

Thursday, August 23, 2018

Keep wifi active in foreground service after phone goes to sleep

Leave a Comment

I want to receive packets from wifi when my phone is locked. The problem is that when I lock my screen, my foreground service stops receiving packets. I'm using Foreground Service like this:

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) {     var notification = new Notification.Builder(this)         .SetContentTitle(Resources.GetString(Resource.String.app_name))         .SetContentText(Resources.GetString(Resource.String.notification_text))         .SetSmallIcon(Resource.Drawable.ic_stat_name)         .SetContentIntent(BuildIntentToShowMainActivity())         .SetOngoing(true)         .AddAction(BuildRestartTimerAction())         .AddAction(BuildStopServiceAction())         .Build();       // Enlist this instance of the service as a foreground service     StartForeground(Constants.SERVICE_RUNNING_NOTIFICATION_ID, notification);      /*DO THIS EVEN WHEN SCREEN IS LOCKED*/      var powerManager = (PowerManager)GetSystemService(PowerService);     _wakeLock = powerManager.NewWakeLock(WakeLockFlags.Partial, "WakeLockTag");     _wakeLock.Acquire();      var wifiManager = (WifiManager)GetSystemService(WifiService);     _wifiLock = wifiManager.CreateWifiLock(WifiMode.FullHighPerf, "xamarin_wifi_lock");     _wifiLock.Acquire();      if (!powerManager.IsIgnoringBatteryOptimizations("com.xamarin.xample.foregroundservicedemo") ||         !_wakeLock.IsHeld || !_wifiLock.IsHeld)         throw new InvalidOperationException("OPTIMIZATIONS NOT ACTIVE");      string msg = timestamper.GetFormattedTimestamp();     Log.Debug(TAG, msg);     Intent intent = new Intent(Constants.NOTIFICATION_BROADCAST_ACTION);     intent.SetAction(Android.Provider.Settings.ActionIgnoreBatteryOptimizationSettings);     intent.PutExtra(Constants.BROADCAST_MESSAGE_KEY, msg);     LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);     Task.Run(() =>     {         using (var client = new UdpClient(12345))         {             while (true)             {                 var result = client.ReceiveAsync().Result;                 Console.WriteLine($"RECEIVED: {result.Buffer.Length}");             }         }     });      return StartCommandResult.Sticky; } 

I'm doing the following things to make sure it is not killed:

  1. Starting Foreground Service
  2. Using StartCommandResult.Sticky
  3. Using Wake Lock
  4. Using Wifi Lock
  5. Setting WifiSleepPolicy to Never (I have it setup in my phone settings)
  6. Setting ActionIgnoreBatteryOptimizationSettings in intent
  7. Whitelisting my app through adb command prompt while debugging

What else am I missing? I am using Samsung A5 with Android 6.0 - API 23.

I looked into logs from adb command prompt and I checked that my service is in fact running as Foreground Service and all locks are held.

1 Answers

Answers 1

What you're doing is just great, all is good. However!!

Let us take a look at devleport.android.com's post:

Google Play policies prohibit apps from requesting direct exemption from Power Management features in Android 6.0+ (Doze and App Standby) unless the core function of the app is adversely affected.

You stated:

I am using Samsung A5 with Android 6.0 - API 23.

Meaning, you won't be able to keep your foreground service when the phone goes to sleep because the core function of the app is not adversely affected.

This the reason why you notice you stopped receiving packets when the phone is asleep.

please explore the entire link I attached and also us the Power Manager guide.

edit: I now noticed that furthermore:

If a user leaves a device unplugged and stationary for a period of time, with the screen off, the device enters Doze mode. In Doze mode, the system attempts to conserve battery by restricting apps' access to network and CPU-intensive services. It also prevents apps from accessing the network and defers their jobs, syncs, and standard alarms.

Doze restrictions:

  • Network access is suspended.
  • The system ignores wake locks.
  • Standard AlarmManager alarms (including setExact() and setWindow()) are deferred to the next maintenance window.
  • If you need to set alarms that fire while in Doze, use setAndAllowWhileIdle() or setExactAndAllowWhileIdle().
  • Alarms set with setAlarmClock() continue to fire normally — the system exits Doze shortly before those alarms fire.
  • The system does not perform Wi-Fi scans.
  • The system does not allow sync adapters to run.
  • The system does not allow JobScheduler to run.

This will conclude my answer to all of your queries.

EDIT 2:

I investigated a little further, there is an entire post regarding this issue in Xamarin.Android.

there is also a solution to wake the phone every 10 minutes to bypass it here.

Read More

Monday, August 13, 2018

Google play console does not reduce app download size

Leave a Comment

I'm developing an Android app using Xamarin latest version and Visual Studio latest version aiming Android SDK 8.0. The app is in Beta track (no release yet). I've been publishing updates of my app for 2 months using Google Play console, but something weird happened on my last update, because download size of my app growed from 14.16 MB to 29.80 MB and I haven't done anything different in my last update.

My app apk has always been 28 - 29 MB on disk (.apk size) and download size 14 MB aprox. In my last update I haven't done anything particulary big, just changed code logic and added 4 new resources (pngs total size: 43KB), no new dlls o references, no new componentes. If I use Android Studio apk analyzer on my last apk update, it says my download size should be 13,4 MB, but it seems that Google Play console does not want to reduce download size any more.

Android Studio shows download size should be 13,4 MB, but download size is actually 29 MB:

Pls your help. Thanks.

2 Answers

Answers 1

I updated Visual Studio from version 15.7.1 to 15.7.3

Visual Studio 15.7.1 to 15.7.3 = Xamarin.Android 8.3.0.19 to 8.3.3.2, consult releases.xamarin.com for details.

So the Mono runtime shared library got updated, thus the basically the whole apk is being downloaded again.

Answers 2

Have you tried Linking your app on release ?

Xamarin.Android applications use a linker to reduce the size of the application. The linker employes static analysis of your application to determine which assemblies are actually used, which types are actually used, and which members are actually used.

Used correctly it can cut your app size in half.

You can get more information here

enter image description here

Read More

Monday, July 9, 2018

Starting app from other app's entry point android

Leave a Comment

I have xamarin.android project Client1 & 1 CommonApp project(within the same solution) which have all common code. From Client1 project I need to start CommonApp, my code to do so in Client1 app

public class MainActivity : AppCompatActivity {     protected override void OnCreate(Bundle savedInstanceState)     {         base.OnCreate(savedInstanceState);         SetContentView(Resource.Layout.activity_main);         FindViewById<Button>(Resource.Id.btn1).Click += delegate {              //Starting CommonApp project             StartActivity(new Intent(Application.Context, typeof(CommonApp.MainActivity)));         };     } } 

Below 1 is CommonApp MainActivity where debugger point going but not starting new activity but the same activity getting added in backstack when i am pressing physical back button it is getting removed.

protected override void OnCreate(Bundle savedInstanceState) {     base.OnCreate(savedInstanceState);     //This is CommonApp     SetContentView(Resource.Layout.activity_main); } 

CommonApp activity_main have

 <TextView      android:layout_width="match_parent"      android:layout_height="match_parent"      android:text="This is CommonApp"> </TextView> 

Description: I have I solution with 2 android app. 1 CommonApp & 2nd Client1. Cleint1 is startup projet having .dll of type CommonApp. From Cleint1 app I am starting CommonApp by importing CommonApp namespace. I can have many project Client1, Client2, Client3...etc with their own icons, app name, splash screen & google-service.json. When I set Client2 on startup it becomes Client2 project & all common code available in CommonApp.

Requirement: Here

Output screenshot enter image description here

App Log

Log

Updated screenshot:

enter image description here

3 Answers

Answers 1

If you know the package name of the another application than you can achieve your goal by calling intent.

String appName = "appName"; String packageName = "package.of.another.application"; openApp(context, appName, packageName);  public static void openApp(Context context, String appName, String packageName) {     if (isAppInstalled(context, packageName))         if (isAppEnabled(context, packageName))             context.startActivity(context.getPackageManager().getLaunchIntentForPackage(packageName));         else Toast.makeText(context, appName + " app is not enabled.", Toast.LENGTH_SHORT).show();     else Toast.makeText(context, appName + " app is not installed.", Toast.LENGTH_SHORT).show(); }  private static boolean isAppInstalled(Context context, String packageName) {     PackageManager pm = context.getPackageManager();     try {         pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);         return true;     } catch (PackageManager.NameNotFoundException ignored) {     }     return false; }  private static boolean isAppEnabled(Context context, String packageName) {     boolean appStatus = false;     try {         ApplicationInfo ai = context.getPackageManager().getApplicationInfo(packageName, 0);         if (ai != null) {             appStatus = ai.enabled;         }     } catch (PackageManager.NameNotFoundException e) {         e.printStackTrace();     }     return appStatus; } 

Answers 2

Make sure your common app is installed are not. if already installed you can try this

 Intent intent = PackageManager.GetLaunchIntentForPackage("Com.CommonAPP.CommonAPP");  if (intent != null)  {     StartActivity(intent);  } 

Hope this will helps you.

Answers 3

I think that the CommonApp Activity is actually started (as shown by the debugger) but it doesn't use the correct layout file. Both MainActivitys (the one from CommonApp and the one from Client1) use a layout named activity_main. So both projects contain a activity_main.xml file and it seems that one (from Client1 project) overwrite the other.

There is no namespace for resources, you need to rename the layouts (and any other resources that you want to remain distinct) to avoid the collision. You could add a prefix, e.g. common_activity_main and client_activity_main

Read More

Monday, June 18, 2018

HorizontalTextAlignment is ignored after navigation

Leave a Comment

I have created a simple app, where users can see more information in section, if they tab a Label, which is seen on the pictures below.

The text is hidden

The text is shown

The problem is, that after navigating to AnotherPage and back, the text moves to left, even though I have set the HorizontalTextAlignment to End.
This only happens, when I have shown the section and hiding it again (by tapping on the Label twice). The problem is illustrated on the picture below, where y is located at the left side.

After navigation

My source code for showing a simple app with this problem, can be downloaded from this Dropbox link.

EDIT Added code example

The ContentPage is as simple as

<StackLayout>    <Grid>       <Grid.ColumnDefinitions>          <ColumnDefinition Width="*" />       </Grid.ColumnDefinitions>       <Label Text="Test" VerticalOptions="Start" />       <Label Text="{Binding Text}" HorizontalTextAlignment="End" TextColor="Red" HorizontalOptions="FillAndExpand" BackgroundColor="Yellow">          <Label.GestureRecognizers>             <TapGestureRecognizer Command="{Binding ChangeVisibilityCommand}" />          </Label.GestureRecognizers>       </Label>    </Grid>     <StackLayout IsVisible="{Binding IsVisible}">       <Label Text="Text 1" />       <Label Text="Text 2" />    </StackLayout>     <Button Command="{Binding OpenAnotherPageCommand}" Text="Open Another Page" />  </StackLayout> 

And the ViewModel is shown below

public class MainPageViewModel : INotifyPropertyChanged {    public event PropertyChangedEventHandler PropertyChanged;     private ICommand _changeVisibilityCommand;    public ICommand ChangeVisibilityCommand    {       get => _changeVisibilityCommand;       set       {          if (value != _changeVisibilityCommand)          {             _changeVisibilityCommand = value;             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ChangeVisibilityCommand)));          }       }    }     private bool _isVisible;    public bool IsVisible    {       get => _isVisible;       set       {          if (value != _isVisible)          {             _isVisible = value;             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsVisible)));          }       }    }     private ICommand _openAnotherPageCommand;    public ICommand OpenAnotherPageCommand    {       get => _openAnotherPageCommand;       set       {          if (value != _openAnotherPageCommand)          {             _openAnotherPageCommand = value;             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(OpenAnotherPageCommand)));          }       }    }     private string _text = "u";    public string Text    {       get => _text;       set       {          if (!string.Equals(_text, value, StringComparison.InvariantCultureIgnoreCase))          {             _text = value;             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Text)));          }       }    }     public MainPageViewModel()    {       ChangeVisibilityCommand = new Command(() =>       {          IsVisible = !IsVisible;          Text = IsVisible ? "x" : "y";       });        OpenAnotherPageCommand = new Command(() =>       {          (Application.Current.MainPage as NavigationPage)?.PushAsync(new AnotherPage());       });    } } 

And the AnotherPage is simply showing a text for example

2 Answers

Answers 1

First of all, i wasn't able to reproduce your issue using the latest version of Xamarin. Maybe simply upgrading Xamarin (Forms) will remove the unwanted behavior in your case as well.

If not, you have two options:

1 - Use HorizontalOptions instead

HorizontalOptions="EndAndExpand"

since HorizontalOptions has a higher priority in the layout engine. Not the most elegant way but surely the most reliable.

2 - Use DataBinding

In your model just add the following property:

    public TextAlignment LabelAlignment     {         get => labelAlignment;         set         {             labelAlignment = value;             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(LabelAlignment)));         }     }     private TextAlignment labelAlignment = TextAlignment.End; 

And in your Xaml you change HorizontalAlignment to

HorizontalTextAlignment="{Binding LabelAlignment}"

That will work because after your screen has been created, the values in the model will be loaded and updated afterwards.

Answers 2

Change HorizontalOptions="FillAndExpand"

To HorizontalOptions="CenterAndExpand"

This will force the text to expand from the center and be placed at the end.

To force the text to the right, you can add a another column definition to your grid:

<Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> 

Place and emtpy object into the first cell, the one to the left:

  • number from the top (0)
  • number from the left (0)

and your label into the second cell, the one to the right:

  • number from the top (0)
  • number from the left (1)

The text area will adjust to the text length and will always be to the right.

I hope this information helps!

You can read more about grid in the documentation: https://docs.microsoft.com/en-us/xamarin/android/user-interface/layouts/grid-layout

Read More

Tuesday, May 22, 2018

ExpandableListView with ViewPager combination as its child

Leave a Comment

UPDATE - Added experimentation result

Is it possible to implement an ExpandableListView to have a viewpager child?

I tried to put viewpager as a child in ExpandableListView but it is not showing :( I also tried to add it under ScrollView but same result so I think it is a problem being under a scrollable view? But when I removed ScrollView it showed up. What can I do so they can go together?


This is what I am aiming for to do

Original Pic

And this is what happen when I tried to implement on my own code.
P.S. This is just a sampler and not yet finished. I have 3 children and my layout displayed thrice also with each item inside

enter image description here

2 Answers

Answers 1

I made a sample with Java. Hope that helps!

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">      <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:orientation="horizontal">              <Button                 android:id="@+id/btnClearChecks"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:layout_weight="1"                 android:text="Clear Checks" />              <Button                 android:id="@+id/btnPutOrder"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:layout_weight="1"                 android:text="Put Order" />     </LinearLayout>      <ExpandableListView         android:id="@+id/expandedListView"         android:layout_width="match_parent"         android:layout_height="match_parent">     </ExpandableListView> </LinearLayout> 

expanded_list_group.xml:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:descendantFocusability="blocksDescendants" >  <CheckBox     android:id="@+id/cb_group"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:layout_marginLeft="40dp"     android:layout_gravity="center_vertical" />  <TextView     android:id="@+id/tv_group"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="Text"     android:textSize="30sp" /> </LinearLayout> 

list_child_pager.xml:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingStart="60dp">  <android.support.v4.view.ViewPager     android:id="@+id/layout_child"     android:layout_width="match_parent"     android:layout_height="200dp" /> </LinearLayout> 

list_pager_item.xml:

<?xml version="1.0" encoding="utf-8"?> <GridLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:columnCount="@integer/pager_col_count" android:rowCount="@integer/pager_row_count">  </GridLayout> 

integers.xml:

<?xml version="1.0" encoding="utf-8"?> <resources> <integer name="pager_col_count">3</integer> <integer name="pager_row_count">3</integer> </resources> 

ChildItemSample.java

public class ChildItemSample { private boolean checked = false; private String name; private int qty;  public int getQty() {     return qty; }  public void setQty(int qty) {     this.qty = qty; }  public boolean isChecked() {     return checked; }  public void setChecked(boolean checked) {     this.checked = checked; }  public String getName() {     return name; }  public ChildItemSample(String name, int qty){     this.name = name;     this.qty = qty; } } 

MainActivity.java:

public class MainActivity extends AppCompatActivity { Button clearChecks, putOrder; ExpandableListView expandableListView; ExpandableListPagerAdapter expandableListAdapter; int lastExpandedPosition = -1;  @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);      expandableListView = findViewById(R.id.expandedListView);     clearChecks = findViewById(R.id.btnClearChecks);     putOrder = findViewById(R.id.btnPutOrder);      List<String> listTitle = genGroupList();     expandableListAdapter = new ExpandableListPagerAdapter(this, getSupportFragmentManager(), listTitle, genChildList(listTitle));     expandableListView.setAdapter(expandableListAdapter);      expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {         @Override         public void onGroupExpand(int groupPosition) {             if(lastExpandedPosition != -1 && (lastExpandedPosition != groupPosition)){                 expandableListView.collapseGroup(lastExpandedPosition);             }             lastExpandedPosition = groupPosition;         }     });     clearChecks.setOnClickListener(new View.OnClickListener() {         @Override         public void onClick(View view) {             expandableListAdapter.clearChecks();         }     });     putOrder.setOnClickListener(new View.OnClickListener() {         @Override         public void onClick(View view) {             ArrayList<String> putOrder = expandableListAdapter.getOrderList();             StringBuilder msg = new StringBuilder();             for(int i=0; i<putOrder.size(); i++){                 msg.append(putOrder.get(i));                 msg.append("\n");             }             Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();         }     }); }  private ArrayList<String> genGroupList(){     ArrayList<String> listGroup = new ArrayList<>();     for(int i=1; i<10; i++){         listGroup.add("Group: " + i);     }     return listGroup; }  private Map<String, List<ChildItemSample>> genChildList(List<String> header){     Map<String, List<ChildItemSample>> listChild = new HashMap<>();     for(int i=0; i<header.size(); i++){         List<ChildItemSample> testDataList = new ArrayList<>();         int a = (int)(Math.random()*28);         for(int j=0; j<a; j++){             ChildItemSample testItem = new ChildItemSample("Child " + (j + 1), 0);             testDataList.add(testItem);         }         listChild.put(header.get(i), testDataList);     }     return listChild; } } 

ExpandableListPagerAdapter.java:

public class ExpandableListPagerAdapter extends BaseExpandableListAdapter { private int child_items_per_page;  private Context context; private FragmentManager fm; private List<String> listGroup; private Map<String, List<ChildItemSample>> listChild; private static int checkedBoxesCount; private boolean[] checkedGroup;  ExpandableListPagerAdapter(Context context, FragmentManager manager, List<String> listGroup, Map<String,         List<ChildItemSample>> listChild) {     this.context = context;     fm = manager;     this.listGroup = listGroup;     this.listChild = listChild;     checkedBoxesCount = 0;     checkedGroup = new boolean[listGroup.size()];     child_items_per_page = context.getResources().getInteger(R.integer.pager_col_count) *             context.getResources().getInteger(R.integer.pager_row_count); }  @Override public int getGroupCount() {     return listGroup.size(); }  @Override //******* Special ******* public int getChildrenCount(int groupPosition) {     return 1; }  @Override public String getGroup(int groupPosition) {     return listGroup.get(groupPosition); }  @Override public ChildItemSample getChild(int groupPosition, int childPosition) {     return listChild.get(listGroup.get(groupPosition)).get(childPosition); }  @Override public long getGroupId(int groupPosition) {     return groupPosition; }  @Override public long getChildId(int groupPosition, int childPosition) {     return childPosition; }  @Override public boolean hasStableIds() {     return false; }  @Override public View getGroupView(int groupPosition, boolean b, View view, ViewGroup viewGroup) {     String itemGroup = getGroup(groupPosition);     GroupViewHolder groupViewHolder;     if(view == null){         LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);         view = inflater.inflate(R.layout.expanded_list_group, null);         groupViewHolder = new GroupViewHolder();         groupViewHolder.tvGroup = view.findViewById(R.id.tv_group);         groupViewHolder.cbGroup = view.findViewById(R.id.cb_group);         groupViewHolder.cbGroup.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 int pos = (int)view.getTag();                 checkedGroup[pos] = !checkedGroup[pos];                 for(ChildItemSample item : listChild.get(listGroup.get(pos))){                     item.setChecked(checkedGroup[pos]);                 }                 notifyDataSetChanged();             }         });         view.setTag(groupViewHolder);     }else {         groupViewHolder = (GroupViewHolder)view.getTag();     }     groupViewHolder.tvGroup.setText(String.format("%s (%d)", itemGroup, listChild.get(listGroup.get(groupPosition)).size()));     if(checkedGroup[groupPosition]) groupViewHolder.cbGroup.setChecked(true);     else groupViewHolder.cbGroup.setChecked(false);     groupViewHolder.cbGroup.setTag(groupPosition);     return view; }  @Override public View getChildView(final int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) {     LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);     View rowView = inflater.inflate(R.layout.list_child_pager, null);     ViewPager childLayout = rowView.findViewById(R.id.layout_child);      List<ChildItemSample> childItemSampleList = listChild.get(listGroup.get(groupPosition));     ChildPagerAdapter adapter = new ChildPagerAdapter(fm, childItemSampleList, child_items_per_page);     childLayout.setAdapter(adapter);     return rowView; }  public class ChildPagerAdapter extends FragmentStatePagerAdapter {     private List<ChildItemSample> pagerItemList;     private int items_per_page;      ChildPagerAdapter(FragmentManager fm, List<ChildItemSample> pagerItemList, int items_per_page) {         super(fm);         this.pagerItemList = pagerItemList;         this.items_per_page = items_per_page;     }      @Override     public Fragment getItem(int position) {         return ChildFragment.newInstance(position, pagerItemList, items_per_page);     }      @Override     public int getCount() {         int remainedItemCount = pagerItemList.size()%child_items_per_page;         if(remainedItemCount == 0)             return (pagerItemList.size()/child_items_per_page);         else             return (pagerItemList.size()/child_items_per_page + 1);     } }  public static class ChildFragment extends Fragment {     private static final String SECTION_NUMBER = "section_number";     private static final String ITEMS_PER_PAGE = "items/page";     private static List<ChildItemSample> itemList;      public ChildFragment() {}      public static ChildFragment newInstance(int sectionNumber, List<ChildItemSample> pagerItemList,                                             int itemPerPage) {         ChildFragment fragment = new ChildFragment();         Bundle args = new Bundle();         args.putInt(SECTION_NUMBER, sectionNumber);         args.putInt(ITEMS_PER_PAGE, itemPerPage);         fragment.setArguments(args);         itemList = pagerItemList;         return fragment;     }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         int child_items_per_page = getArguments().getInt(ITEMS_PER_PAGE);         int start_item = getArguments().getInt(SECTION_NUMBER)*child_items_per_page;         int itemCount = itemList.size() - getArguments().getInt(SECTION_NUMBER)*child_items_per_page;         if(itemCount > child_items_per_page) itemCount = child_items_per_page;         itemCount += getArguments().getInt(SECTION_NUMBER)*child_items_per_page;          GridLayout pageView = (GridLayout)inflater.inflate(R.layout.list_pager_item, container, false);         for(int i=start_item; i<itemCount; i++){             ChildItemSample expandedListText = itemList.get(i);             CheckBox cbChild = new CheckBox(getContext());             GridLayout.LayoutParams params = new GridLayout.LayoutParams();             params.width = (int)(80 * getContext().getResources().getDisplayMetrics().density);             cbChild.setLayoutParams(params);             cbChild.setChecked(expandedListText.isChecked());             cbChild.setText(expandedListText.getName());             cbChild.setTag(i);             pageView.addView(cbChild);              cbChild.setOnClickListener(new View.OnClickListener() {                 @Override                 public void onClick(View view) {                     CheckBox cb = (CheckBox) view;                     int pos = (int) view.getTag();                     ChildItemSample selectedItem = itemList.get(pos);                     selectedItem.setChecked(cb.isChecked());                     if(cb.isChecked()){                         checkedBoxesCount++;                         Toast.makeText(getContext(),"Checked value is: " +                                         itemList.get(pos).getName(),                                 Toast.LENGTH_SHORT).show();                     }else {                         checkedBoxesCount--;                         if(checkedBoxesCount == 0){                             Toast.makeText(getContext(),"nothing checked",Toast.LENGTH_SHORT).show();                         }else {                             Toast.makeText(getContext(),"unchecked",Toast.LENGTH_SHORT).show();                         }                     }                 }             });         }         return pageView;     } }  public void clearChecks() {     for(int i=0; i<checkedGroup.length; i++) checkedGroup[i] = false;     for(List<ChildItemSample> value : listChild.values()) {         for (ChildItemSample sample : value) {             sample.setChecked(false);         }     }     checkedBoxesCount = 0;     notifyDataSetChanged(); }  public ArrayList<String> getOrderList(){     ArrayList<String> overallOrder = new ArrayList<>();     for(int i=0; i<getGroupCount(); i++){         //for(int j=0; j<getChildrenCount(i); j++){         for(int j=0; j<listChild.get(getGroup(i)).size(); j++){             if(getChild(i,j).isChecked()){                 String newOrder = getGroup(i) + ">" + getChild(i, j).getName();                 overallOrder.add(newOrder);             }         }     }     return overallOrder; }  @Override public boolean isChildSelectable(int groupPosition, int childPosition) {     return true; }  private class GroupViewHolder {     CheckBox cbGroup;     TextView tvGroup; } } 

Answers 2

can you check this API https://developer.android.com/reference/android/widget/ExpandableListView

A view that shows items in a vertically scrolling two-level list

Read More

Saturday, March 3, 2018

Xamarin Android Facebook GameRequestDialog not calling callbacks

Leave a Comment

I'm using the Xamarin.Facebook.Android package for this. The dialog displays correctly and the requests go through to the correct recipients but the callbacks never get called. I'm not 100% sure where I'm supposed to get the CallbackManager from.

public class FacebookService : IFacebookService {     public void InviteFriends(FacebookInviteCallbacks facebookInviteCallbacks)     {         if (AppInviteDialog.CanShow())         {             var activity = Xamarin.Forms.Forms.Context as Activity;             var content = new GameRequestContent.Builder().                 SetTitle("Check out this game").                 SetMessage("Check out this game I play!").                 Build() as GameRequestContent;              var dialog = new GameRequestDialog(activity);              dialog.RegisterCallback(CallbackManagerFactory.Create(), new MyFacebookCallback(facebookInviteCallbacks));             dialog.Show(content);                          }     }        }  public class MyFacebookCallback : Java.Lang.Object, IFacebookCallback {     private FacebookInviteCallbacks facebookInviteCallbacks;      public ImcFacebookCallback(FacebookInviteCallbacks facebookInviteCallbacks)     {         this.facebookInviteCallbacks = facebookInviteCallbacks;     }      public void OnCancel()     {         System.Diagnostics.Debug.WriteLine("Cancelled sending invite");     }      public void OnError(FacebookException error)     {         facebookInviteCallbacks.FailedCallback(error.Message);     }      public void OnSuccess(Java.Lang.Object result)     {         System.Diagnostics.Debug.WriteLine(result);     } } 

Update

From what I can tell from other examples I've seen, CallbackManagerFactory.Create() is correct.

1 Answers

Answers 1

After a lot of digging and trial and error I finally got this working.

In my FacebookService class I added:

public static ICallbackManager callbackManager; 

In the Invitefriends method, in the if statement I changed this:

dialog.RegisterCallback(CallbackManagerFactory.Create(), new MyFacebookCallback(facebookInviteCallbacks)); 

to

callbackManager = CallbackManagerFactory.Create(); dialog.RegisterCallback(callbackManager, new ImcFacebookCallback(facebookInviteCallbacks)); 

In the MainActivity I added the following override.

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)     {         base.OnActivityResult(requestCode, resultCode, data);                                  Services.FacebookService.callbackManager.OnActivityResult(requestCode, (int)resultCode, data);     } 

That's all it took. I wish the package would have been better documented.

Read More

Tuesday, February 13, 2018

Adding an “Android.Views.ViewGroup” to a Xamarin XAML page

Leave a Comment

I need some help with adding an Android.Views.ViewGroup to a XAML page.

I have a Xamarin project with a solution structure that looks like this:

  • App1
    • /ViewModels
      • /MyPageViewModel.cs
    • /Views
      • /MyPageView.xaml
        • /MyPageView.xaml.cs
  • App1.Android
    • /MainActivity.cs
    • /MainApplication.cs
  • App1.iOS
  • MyAndroidBindingProject
    • /Jars
      • /customViewGroup.aar

Note the customViewGroup.aar that I've added to the solution using a Xamarin Android Binding Library.

The AAR file contains an Android.Views.ViewGroup class that I'd like to show on MyPage.xaml but I have no clue how to do it. I can't seem to find a guide or code sample that fits this exact use case (nor can I find one that involves adding a simple Android.Views.View to a Xamarin XAML page).

I've found examples of adding an Android.Views.ViewGroup to a native Android application (using Java and XML) but nothing that shows how to add it to a Xamarin XAML page.

Please help!


I'm including some source code so you can see what I've tried:

MyPage.xaml

<ContentPage      xmlns="http://xamarin.com/schemas/2014/forms"     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"     x:Class="App1.Views.MyPage"     xmlns:vm="clr-namespace:App1.ViewModels;"     xmlns:androidWidget="clr-namespace:Com.CustomAAR;assembly=Com.CustomAAR;targetPlatform=Android"     xmlns:formsAndroid="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.Platform.Android;targetPlatform=Android"     Title="{Binding Title}">     <ContentPage.Content>         <ContentView x:Name="contentViewParent">             <androidWidget:MyCustomViewGroup x:Arguments="{x:Static formsandroid:Forms.Context}">              </androidWidget:MyCustomViewGroup>         </ContentView>         <!--<ContentView              IsVisible="True"             IsEnabled="True"             BindingContext="{Binding MyCustomViewGroup}">         </ContentView>-->     </ContentPage.Content> </ContentPage> 

MyPage.xaml.cs

public partial class MyPage : ContentPage {     MyCustomViewGroupModel viewModel;      public MyPage()     {         InitializeComponent ();     }      public MyPage(MyCustomViewGroupModel viewModel)     {         InitializeComponent();  #if __ANDROID__         NativeViewWrapper wrapper = (NativeViewWrapper)contentViewParent.Content;         MyCustomViewGroup myCustomViewGroup = (MyCustomViewGroup)wrapper.NativeView;          //myCustomViewGroup = new MyCustomViewGroup(Android.App.Application.Context);          myCustomViewGroup.SomeAction(""); #endif          BindingContext = this.viewModel = viewModel;     } } 

1 Answers

Answers 1

To include native controls in your Xamarin.Forms page you will need to create a custom control and platform renderer. See the official documentation for full walkthrough.

In a gist, you first you declare a new control in your shared project:

public class MyCustomViewControl : View {  } 

Now in the Android project you create a custom renderer, that will use your custom Android view to display natively:

public class MyCustomViewRenderer : ViewRenderer<MyCustomViewControl, MyCustomViewGroup> {     MyCustomViewGroup viewGroup;      public MyCustomViewRenderer(Context context) : base(context)     {     }      protected override void OnElementChanged(ElementChangedEventArgs<MyCustomViewControl> e)     {         base.OnElementChanged(e);          if (Control == null)         {             viewGroup= new MyCustomViewGroup(Context);             SetNativeControl(viewGroup);         }     } } 

You will also use the renderer to setup events, etc. on the native side.

The renderer is recognized and registered by Xamarin.Forms thanks to the attribute, that can be in the same file as the Renderer, above the namespace:

[assembly: ExportRenderer (typeof(MyCustomViewControl), typeof(MyCustomViewRenderer))] 
Read More

Monday, February 5, 2018

How to set shadow effect on ImageView

Leave a Comment

I'm tryin' to set shadow on an Image view on Xamarin.Forms (targeting the Android platform) and I got some examples on the internet.

The PCL code is quite simple, and the platform seemed pretty easy too. The recipe available at the official xamarin developer site is something like this:

[assembly: ResolutionGroupName("MyGroupName")] [assembly: ExportEffect(typeof(LabelShadowEffect), "ShadowEffect")] namespace MyWorkspace {     public class LabelShadowEffect : PlatformEffect     {         protected override void OnAttached()         {             try             {                 var control = (Control as TextView); // TextView have the SetShadowLayer method, but others views don't                  var effect = (ShadowEffect)Element.Effects.FirstOrDefault(e => e is ShadowEffect);                 if (effect != null)                 {                     float radius = effect.Radius;                     float distanceX = effect.DistanceX;                     float distanceY = effect.DistanceY;                     Android.Graphics.Color color = effect.Color.ToAndroid();                     control?.SetShadowLayer(radius, distanceX, distanceY, color);                 }             }             catch (Exception)             {                            }         }          protected override void OnDetached()          {          }     } } 

So I've noticed that this recipe works only for components that render with TextView (that's the only class with the SetShadowLayer method). In other sources I saw something more generic like:

public class ShadowEffect : PlatformEffect {     protected override void OnAttached ()     {         Container.Layer.ShadowOpacity = 1;         Container.Layer.ShadowColor = UIColor.Black.ToCGColor;         Container.Layer.ShadowRadius = 6;     }      protected override void OnDetached ()     {         Container.Layer.ShadowOpacity = 0;     } } 

By the use of UIColor I get that it's targeting iOS platform. No such a thing like this on Android views. I took a look at the XF FrameRenderer source code but I was not able to understand how they made the shadow effect works.

Someone can help me with this?

2 Answers

Answers 1

Please try this below code will work

<Frame OutlineColor="Transparent" Padding="0" CornerRadius="0" VerticalOptions="Center" BackgroundColor="Teal">     <Image Source="Imagename" Aspect="Fill" /> </Frame> 

Answers 2

I recommend using the Elevation property instead of ShadowLayer; Android will add the correct shadow itself based on the elevation you give, and it will adhere to Material Design.

Though you will have to use a custom renderer for this approach, and will need to create a different renderer for iOS/UWP.

Read More

Thursday, November 23, 2017

Grid with RowSpacing(Xamarin Forms) and navigation

Leave a Comment

Now I'm working on updating the UI of my app(XF for Android). I found this UI solution for appbar(from source code Evolve 2016):

enter image description here

It looks beautiful and is implemented simply:

<ContentPage.Content> <Grid RowSpacing="0" >     <Grid.RowDefinitions>         <RowDefinition Height="Auto" />         <RowDefinition Height="*" />     </Grid.RowDefinitions>     <StackLayout BackgroundColor={StaticResource Primary}, Grid.Row=0/>        <SearchBar/>     </StackLayout>     <StackLayout Grid.Row=1>        //other content    </StackLayout>  ..... 

For existing navigation(Master-Detail) it works fine. But I click by item (on this page) - than open new page(no Master Detail). Work like this:

 await Navigation.PushAsync(new SessionDetailPage(), true); 

I click back on toolbar - return to Session page than I get a white line display for a short time

enter image description here

it does not last long, a split second. then the white line disappears. But it's unpleasant to use. Any ideas? How can I improve this?

1 Answers

Answers 1

Might be RowDefinition Height="Auto" calculating and resizing itself, try use absolute value to check if this is the cause.

Read More

Wednesday, November 8, 2017

ScrollView allow content overflow

Leave a Comment

Goal

I am trying to allow a scrollview to overflow (not clip its children). I have this working with a carousel view but cannot get the same result with a scrollview.

The idea of this is to center the scrollview and allow overflow so the content can look centered (being used as tabs).


Code

Use of the scrollview in Xamarin Forms:

 var scrollView = new ScrollView  {     WidthRequest = 200,     HorizontalOptions = LayoutOptions.Center,     Orientation = ScrollOrientation.Horizontal,     Content = scrollViewContent,     IsClippedToBounds = false  }; 

This is my custom renderer for the scrollview:

public class CenteredScrollViewRenderer : ScrollViewRenderer {     protected override void OnElementChanged(VisualElementChangedEventArgs e)     {         base.OnElementChanged(e);          if (e.OldElement != null || this.Element == null)             return;          if (e.OldElement != null)             e.OldElement.PropertyChanged -= OnElementPropertyChanged;          e.NewElement.PropertyChanged += OnElementPropertyChanged;       }      protected void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)     {          if (ChildCount > 0)         {             GetChildAt(0).HorizontalScrollBarEnabled = false;             GetChildAt(0).VerticalScrollBarEnabled = false;             GetChildAt(0).OverScrollMode = OverScrollMode.Never;              // Try and disable clip             ((ViewGroup)GetChildAt(0)).SetClipToPadding(false);             ((ViewGroup)GetChildAt(0)).SetClipChildren(false);         }     } } 

Other attempts

I have also created a function to go through ALL parents to disable clipping just to see if it was a parent causing a problem. This still has not worked.

So how do we allow the scrollview content to overflow outside of its bounds?

Note: I am tagging android as this could be a simple misunderstanding of the native control.


Update:

Tried my best to make an image of the desired effect I am looking for. ScrollView

So the big blue border is the scrollview in the middle of the contentview. The scroll content is only visible when inside the scrollview itself (how it always works). I am trying to not clip the content so can always see all content (overflow), not just inside the scrollview.


Update 2:

The following link may explain the effect I am after better then I have. Please take a look, any question let me know.

Paging-enabled UIScrollView With Previews

Note: I have linked the touch events up so it is only disabling clipping bounds that I need to find a fix for.

1 Answers

Answers 1

You could try the same approach as with elevation / shadow clipping.

Add a parent layout, add padding to the parent layout (to achieve the centered item) and set clipToPadding=false in the parent layout.

Since the question is about Xamarin, I'll just mention that for native Android development you could achieve the same center-locked effect with a RecyclerView and an implementation of the SnapHelper class.

Read More

Friday, July 21, 2017

Xamarin Android: How to Share PDF File From Assets Folder? Via Whatsapp I get message, the file you picked was not a document

Leave a Comment

I use Xamarin Android. I have a PDF File storaged in Assest folder from Xamarin Android.

enter image description here

I want to share this file in whatsapp, but I recive a message: "the file you picked was not a document"

enter image description here

I tried two ways:

This is the first way

var SendButton = FindViewById<Button>(Resource.Id.SendButton); SendButton.Click += (s, e) =>                  {                 ////Create a new file in the exteranl storage and copy the file from assets folder to external storage folder                 Java.IO.File dstFile = new Java.IO.File(Environment.ExternalStorageDirectory.Path + "/my-pdf-File--2017.pdf");                 dstFile.CreateNewFile();                  var inputStream = new FileInputStream(Assets.OpenFd("my-pdf-File--2017.pdf").FileDescriptor);                 var outputStream = new FileOutputStream(dstFile);                 CopyFile(inputStream, outputStream);                  //to let system scan the audio file and detect it                 Intent intent = new Intent(Intent.ActionMediaScannerScanFile);                 intent.SetData(Uri.FromFile(dstFile));                 this.SendBroadcast(intent);                  //share the Uri of the file                 var sharingIntent = new Intent();                 sharingIntent.SetAction(Intent.ActionSend);                 sharingIntent.PutExtra(Intent.ExtraStream, Uri.FromFile(dstFile));                 sharingIntent.SetType("application/pdf");                  this.StartActivity(Intent.CreateChooser(sharingIntent, "@string/QuotationShare"));             }; 

This is the second

//Other way              var SendButton2 = FindViewById<Button>(Resource.Id.SendButton2);             SendButton2.Click += (s, e) =>             {                  Intent intent = new Intent(Intent.ActionSend);                 intent.SetType("application/pdf");                  Uri uri = Uri.Parse(Environment.ExternalStorageDirectory.Path + "/my-pdf-File--2017.pdf");                 intent.PutExtra(Intent.ExtraStream, uri);                  try                 {                     StartActivity(Intent.CreateChooser(intent, "Share PDF file"));                 }                 catch (System.Exception ex)                 {                     Toast.MakeText(this, "Error: Cannot open or share created PDF report. " + ex.Message, ToastLength.Short).Show();                 }             }; 

In other way, when I share via email the pdf file is sent empty, "corrupt file"

What can I do?

2 Answers

Answers 1

The solution is copying de .pdf file from assets folder to a local storage. Then We able to share de file.

First copy the file:

string fileName = "my-pdf-File--2017.pdf";  var localFolder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath; var MyFilePath = System.IO.Path.Combine(localFolder, fileName);  using (var streamReader = new StreamReader(Assets.Open(fileName))) {        using (var memstream = new MemoryStream())        {               streamReader.BaseStream.CopyTo(memstream);               var bytes = memstream.ToArray();               //write to local storage               System.IO.File.WriteAllBytes(MyFilePath, bytes);                MyFilePath = $"file://{localFolder}/{fileName}";       } } 

Then share the file, from local storage:

var fileUri = Android.Net.Uri.Parse(MyFilePath);  var intent = new Intent(); intent.SetFlags(ActivityFlags.ClearTop); intent.SetFlags(ActivityFlags.NewTask); intent.SetAction(Intent.ActionSend); intent.SetType("*/*"); intent.PutExtra(Intent.ExtraStream, fileUri); intent.AddFlags(ActivityFlags.GrantReadUriPermission);  var chooserIntent = Intent.CreateChooser(intent, title); chooserIntent.SetFlags(ActivityFlags.ClearTop); chooserIntent.SetFlags(ActivityFlags.NewTask); Android.App.Application.Context.StartActivity(chooserIntent); 

Answers 2

the file you picked was not a document

I had this issue when I trying to share a .pdf file via WhatsApp from assets folder, but it gives me the same error as your question :

the file you picked was not a document 

Finally I got a solution that copy the .pdf file in assets folder to Download folder, it works fine :

var pathFile = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);  Java.IO.File dstFile = new Java.IO.File(pathFile.AbsolutePath + "/my-pdf-File--2017.pdf"); 

Effect like this.

Read More

Friday, June 9, 2017

Why does Navigation.PushAsync crash after Azure MobileServiceClient LoginAsync()?

Leave a Comment

Edit: Sample project that demonstrates crash can be found here: https://github.com/rringham/brokenazurexamforms - you need to set your own Azure App Service URL in:

  • src/BrokenAzureForms/Droid/Services/User/DroidUserService.cs
  • src/BrokenAzureForms/iOS/Services/User/IosUserService.cs

I'm seeing Xamarin Forms's Navigation.PushAsync() crash on Android when I attempt to use it after authenticating with Azure MobileServiceClient. This crash is isolated to Android - it does not happen on iOS.

Here's the setup - I've got a basic NavigationPage as my main app page:

MainPage = new NavigationPage(new LoginPage()); 

On my LoginPage, I authenticate using a DependencyService-injected class that performs authentication in my Android project:

private async void OnMicrosoftAccountTapped(object sender, EventArgs args) {     IUserService userService = DependencyService.Get<IUserService>();     bool authenticated = await userService.LoginWithAzureAD();     if (authenticated)     {         await Navigation.PushAsync(new HomePage(), false);     }  } 

In my Android implementation of IUserService, I do this (pretty much exactly what the Azure / Xamarin Forms tutorials show):

public async Task<bool> LoginWithAzureAD() {     try     {         _user = await _client.LoginAsync(Xamarin.Forms.Forms.Context, MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory);     }     catch (Exception)     {         return false;     }      return true; } 

Here's where things fall apart. When LoginWithAzureAD() is done, control resumes in OnMicrosoftAccountTapped(); we then go to call Navigation.PushAsync(), and boom - the app crashes, with very little detail to go on:

MobileServiceClient / Navigation crash

All I can think is that Azure MobileServiceClient is doing something pretty funky with Xamarin.Forms.Forms.Context internally, because if I remove the call to await userService.LoginWithAzureAD(), the call to Navigation.PushAsync() works with no issues. Something in MobileServiceClient is either broken, or is breaking something in Xamarin Forms.

Anyone see anything like this?

2 Answers

Answers 1

When I do this, I use the following:

In MainActivity.cs:

// Initialize for Azure Mobile Apps Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();  // Initialize for Xamarin Forms global::Xamarin.Forms.Forms.Init(this, savedInstanceState);  // Initialize for Login Provider var lp = (DroidLoginProvider)DependencyService.Get<ILoginProvider>(); lp.Initialize(this); 

Then, in my DroidLoginProvider class, I do the following:

Context _context;  public void Initialize(Context context) {     this._context = context; }  public async Task LoginAsync(MobileServiceClient client) {     await client.LoginAsync(this._context, MobileServiceAuthenticationProvider.whatever); } 

I call the LoginAsync from a Singleton wrapper in my shared project. It's important that it is a Singleton because there should only be one MobileServiceClient in a project - the authentication is stored in the MobileServiceClient.CurrentUser property and is only set on the current client.

You can see a working project with this logic here: https://github.com/adrianhall/30-days-of-zumo-v2/tree/master/file-upload

Answers 2

I think the login issue is orthogonal, and you're calling PushAsync from a background thread. You should just await the call to your dependency service method from your main thread, and then do PushAsync there.

Here's a sample:

Read More

Thursday, April 27, 2017

Navigation in Xamarin.Forms

Leave a Comment

I have two pages say Page1 and page2. In Page-1 I have listview and a Image button(tap gesture). Here if I click listview item, it navigates to Page2 where it plays a song.

Navigation.PushModalAsync(new page2(parameter1)); 

Song continues to play.Then I go back to page1 by clicking back button.Then As mentioned I have a imagebutton in page1,If I click this image button,I want to go same page which was shown earlier(page2) with same status song continues to play(it should not play from beginning).

I understand ,If I click back button,it destroys modal page.For some reason I cant use pushasync(). Is this the possible???

2 Answers

Answers 1

Would recommend not to tightly couple your audio/media player logic with your navigation logic or Page objects - especially if you want it to continue playing in the background.

Simplest approach would be to have a AudioPlayerService class that subscribes to MessengingCenter for audio player commands - such as play, pause etc. When a play command is published, it can initiate a background thread to play the audio file.

MessagingCenter.Subscribe<Page2, AudioPlayerArgs> (this, "Play", (sender, args) => {       // initiate thread to play song }); 

Now, when you navigate from page1 to page2, you can publish/send a command to the AudioPlayerService class through MessengingCenter to start playing the song. This way, any number of back-and-forth between page1 or page2 won't affect the audio player as it can ignore the play commands if it is already playing the same audio file.

MessagingCenter.Send<Page2, AudioPlayerArgs> (this, "Play", new AudioPlayerArgs("<sound file path>")); 

Note: I personally avoid using MessengingCenter in my code - A better approach would be to rather introduce an interface for IAudioPlayerService with appropriate methods to play, pause etc. and use DependencyService to maintain the AudioPlayerService state as a global object (which is default behavior)

public interface IAudioPlayerService {      bool PlayAudio(string file);      bool PauseAudio();      bool StopAudio(); }  [assembly: Xamarin.Forms.Dependency (typeof (IAudioPlayerService))] public class AudioPlayerService : IAudioPlayerService {       //implement your methods } 

And, use following code to control your audio player service in your Page/ViewModel objects.

DependencyService.Get<IAudioPlayerService>().Play("<sound file path>"); 

Answers 2

You may try to pass the same instance of a global or local variable, whatever is appropriate:

var secondpage = new page2(parameter1); // Global scope. ... Navigation.PushModalAsync(secondpage); 

Hope it helps.

Read More