Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Carousel not updating

Hey everyone,

I will apologise ahead of time, I am just starting with xamarin and this is my first post, let me know if I should make myself more clear/concise or give more/less info.

I started working on a Xamarin.Forms app a couple of days ago, I looked at multiple codebases to see how things work in Xamarin. I want to ask the user to choose pictures from their gallery and upload them to the app and to my server, I found a code example that does this perfectly:
(github. com/danielkon96/MultiImagePicker) sorry for the misformed URL I can't post links yet.

If I clone the repo I can see it works perfectly, but when I try to integrate it into my app my I run into two issues, the major one is that after I select the images it does not update the carousel, another minor problem is that it does not ask me for permission and just tells me I need to enable them.

I am not sure what code to post, most of my code is the same except for one main difference which would be in my Android MainActivity which I will post below. I have a login page that if the user successfully logs in then they get redirected to the page where they then upload their pictures which is identical to the ImageSelectionPage in the Github link.

While I try to debug with breakpoints, it runs code from my ImageSelectionPage even though that page should only be 'activated' after the user does a successful login and gets sent there.

The following is my main Activity class

namespace SwipeCardView.Sample.Droid
{
    [Activity(Label = "SwipeCardView.Sample", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Portrait)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            //NuGet Initializations
            CrossCurrentActivity.Current.Init(this, bundle);

            CarouselViewRenderer.Init();
            CarouselView.FormsPlugin.Android.CarouselViewRenderer.Init();
            FFImageLoading.Forms.Platform.CachedImageRenderer.Init(enableFastRenderer: false);

            base.OnCreate(bundle);
            Xamarin.Essentials.Platform.Init(this, bundle);
            global::Xamarin.Forms.Forms.Init(this, bundle);

            var width = Resources.DisplayMetrics.WidthPixels;
            var height = Resources.DisplayMetrics.HeightPixels;
            var density = Resources.DisplayMetrics.Density;

            App.ScreenWidth = (width - 0.5f) / density;
            App.ScreenHeight = (height - 0.5f) / density;


            FirebaseApp.InitializeApp(this);
            LoadApplication(new App());
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        #region Image Picker Implementation
        public static int OPENGALLERYCODE = 100;
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            //NuGet Initializations
            CarouselViewRenderer.Init();
            FFImageLoading.Forms.Platform.CachedImageRenderer.Init(enableFastRenderer: false);

            //If we are calling multiple image selection, enter into here and return photos and their filepaths.
            if (requestCode == OPENGALLERYCODE && resultCode == Result.Ok)
            {
                List<string> images = new List<string>();

                if (data != null)
                {
                    //Separate all photos and get the path from them all individually.
                    ClipData clipData = data.ClipData;
                    if (clipData != null)
                    {
                        for (int i = 0; i < clipData.ItemCount; i++)
                        {
                            ClipData.Item item = clipData.GetItemAt(i);
                            Android.Net.Uri uri = item.Uri;
                            var path = GetRealPathFromURI(uri);


                            if (path != null)
                            {
                                images.Add(path);
                            }
                        }
                    }
                    else
                    {
                        Android.Net.Uri uri = data.Data;
                        var path = GetRealPathFromURI(uri);

                        if (path != null)
                        {
                            images.Add(path);
                        }
                    }

                    //Send our images to the carousel view.
                    MessagingCenter.Send<App, List<string>>((App)Xamarin.Forms.Application.Current, "ImagesSelectedAndroid", images);
                }
            }
        }

        /// <summary>
        ///     Get the real path for the current image passed.
        /// </summary>
        [Obsolete]
        public String GetRealPathFromURI(Android.Net.Uri contentURI)
        {
            try
            {
                ICursor imageCursor = null;
                string fullPathToImage = "";

                imageCursor = ContentResolver.Query(contentURI, null, null, null, null);
                imageCursor.MoveToFirst();
                int idx = imageCursor.GetColumnIndex(MediaStore.Images.ImageColumns.Data);

                if (idx != -1)
                {
                    fullPathToImage = imageCursor.GetString(idx);
                }
                else
                {
                    ICursor cursor = null;
                    var docID = DocumentsContract.GetDocumentId(contentURI);
                    var id = docID.Split(':')[1];
                    var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
                    var projections = new string[] { MediaStore.Images.ImageColumns.Data };

                    cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
                    if (cursor.Count == 0)
                    {
                        cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
                    }
                    var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
                    cursor.MoveToFirst();
                    fullPathToImage = cursor.GetString(colData);
                }
                return fullPathToImage;
            }
            catch (Exception ex)
            {
                Toast.MakeText(Xamarin.Forms.Forms.Context, "Unable to get path", ToastLength.Long).Show();
            }
            return null;
        }
        #endregion
    }
}

The following is my app landing page where the user logs in before being redirected:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Login : ContentPage
{
IAuth auth;

    public Login()
    {
        InitializeComponent();
        auth = DependencyService.Get<IAuth>();
    }

    async void LoginClicked(object sender, EventArgs e)
    {
        string Token = await auth.LoginWithEmailPassword(EmailInput.Text, PasswordInput.Text);

        if (Token != "")
        {
            await Navigation.PushAsync(new ImageSelectionPage ());
        }
        else
        {
            ShowError();
        }
    }

    async private void ShowError()
    {
        await DisplayAlert("Authentication Failed", "E-mail or password are incorrect. Try again!", "OK");
    }

    async void SignUpClicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new SignUpPage());
    }


}

Best Answers

Answers

  • guantanamo_baeguantanamo_bae Member

    thanks @jezh !! :)

Sign In or Register to comment.