Solutions to common issues in android development working with Xamarin

Whenever we start to develop a cross-platform application, first we choose the technology to go ahead with development, So if it is Xamarin then you are in right place. In this blog, we will figure out the problems you might face in developing an Android application with the Xamarin Common code base i.e PCL project.

There are few basic issues a developer can come across while working with Xamarin and access native functionality in common code base. Here is the list of some very common issues which a developer will surely face with Xamarin:

  • How to create and use custom dependency services to access native functionality?
  • How one can add a native based styling for a common code base?
  • Page content shifted upward along with the header when a soft keyboard is visible.
  • Using a messenger service to send a broadcast message and data in entire common code.
  • Handling large Bitmaps using List views of Xamarin while fast scrolling.

So let’s start with the first two point and rest will discuss in my upcoming series of blog on Xamarin .  So, start with ‘Dependency Services’ –

Dependency service is nothing but a class which is used to access the data from the native application interface like getting the image from Gallery, Getting Location from GPS etc.

To start creating a dependency service steps below points should be followed:

public interface IPicturePicker

{

   Task<string> GetImageStreamAsync();

}

Interface Class

Now go to the Droid project create a class named PicturePickerImplementation under folder DependencyService as shown in Fig 1.2

PicturePickerImplementation Class

Body for this class should be as below:

[assembly: Dependency(typeof(PicturePickerImplementation))]

namespace <Enter your name space>

{

   public class PicturePickerImplementation : IPicturePicker

   {

       public Task<string> GetImageStreamAsync()

       {

           // Define the Intent for getting images

           Intent intent = new Intent();

           intent.SetType(“image/*”);

           intent.SetAction(Intent.ActionGetContent);

           // Get the MainActivity instance

           MainActivity activity = MainActivity.Instance;

           if(activity == null)

           {

               activity = Forms.Context as MainActivity;

           }

       Intent chooseImageIntent =                ImagePicker.getPickImageIntent(Android.App.Application.Context);

            // Start the picture-picker activity (resumes in MainActivity.cs)

     activity.StartActivityForResult(chooseImageIntent, MainActivity.PickImgId );

           // Save the TaskCompletionSource object as a MainActivity property

     activity.PickImgTask = new TaskCompletionSource<string>();

           // Return Task object

           return activity.PickImageTaskCompletionSource.Task;

        }

    }

}

2. In Your Main class of droid project like in above code main class name is MainActivity, add the below code:

public static readonly int PickImgId = 1000;

public TaskCompletionSource<string> PickImgTask { set; get; }

protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)

{

         base.OnActivityResult(requestCode, resultCode, intent);

if (requestCode == PickImgId )

  {

   if (resultCode == Result.Ok)

     {

        Bitmap bitmap = ImagePicker.getImageFromResult(this, resultCode, intent);

        byte[] bitmapData;

        bitmap = ThumbnailUtils.ExtractThumbnail(bitmap, 250, 250);

        System.IO.Stream stream;

        using (var s = new MemoryStream())

        {

           bitmap.Compress(Bitmap.CompressFormat.Png, 0, s);

           stream = s;// ContentResolver.OpenInputStream(uri);

           bitmapData = s.ToArray();

        }

        string Base64ImageDa = StreamToBase64String(bitmapData);

              if (!string.IsNullOrEmpty(Base64ImageDa))

                     PickImgTask.SetResult(Base64ImageDa);

              else

                        PickImgTask.SetResult(null);

         }

     }

}

3. Usage inside the common code:

var Base64ImageDaedit = await DependencyService.Get<IPicturePicker>().GetImageStreamAsync();

With this piece of code, you will get the returned data for an image from native android part as described in above example.

Now, start with the second point i.e. Native android styling in common XAML UI, there are many areas where a developer thinks that native interface would work better instead of a Xamarin based UI like Xamarin provided alert boxes do not look that cool or adding a border for a stack layout like as we did with drawable XML file in android or Navigation/Title bar color etc.

To add the android styling in Xamarin common code below are the steps you should follow:

  1. Create a styles.xml under Resources folder in Droid project as shown in Fig 1.3:
Styles.xml
  1. Add the below code in styles.xml:

<?xml version=”1.0″ encoding=”utf-8″ ?>

<resources>

<style name=”MyTheme” parent=”MyTheme.Base”>

</style>

 <style name=”MyTheme.Base” parent=”Theme.AppCompat”>

<item name=”colorPrimary”>@color/primary</item>

    <item name=”colorPrimaryDark”>@color/primaryDark</item>

    <item name=”colorAccent”>@color/accent</item>

    <item name=”android:windowBackground”>@color/window_background</item>

    <item name=”android:windowTitleBackgroundStyle”>@style/WindowTitleBackground</item>

<item name=”alertDialogTheme”>@style/dialog</item>

</style>

<!–Dialog–>

<style name=”dialog” parent=”Base.Theme.AppCompat.Light.Dialog.Alert”>

    <item name=”colorAccent”>#ffffff</item>

    <item name=”android:textColorPrimary”>#ffffff</item>

    <item name=”android:background”>#1A3E5E</item>

    <item name=”buttonStyle”>@style/MyButton</item>

</style>

 <style name=”MyButton” parent=”Widget.AppCompat.Button”>

    <item name=”android:textAllCaps”>false</item>

 </style>

Here we have declared the colors for our application and dialog (alert boxes) style for what color it should look like etc.

2. Open the Android manifest file as shown in Fig 1.4 and update the <application></application> tag as below

<application android:icon=”@drawable/Icon” android:label=”Label to provide” android:theme=”@style/MyTheme”>

. . .

</application>

AndroidManifest

Now when we clean and Rerun the application, this style will automatically get applied to the existing theme.

So, In this blog I covered two major issues and be ready for my next blog of Xamarin series to discuss rest of the issues.

Related Posts

Leave a comment