Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 79144 articles
Browse latest View live

Does anyone know the true data type of the SimpleAudioPlayer

$
0
0

I have been trying to make my code a lot more efficient and one of the ways of doing that is not calling the declarations of some variables everytime of the method is called, and instead defining them at class scope. But since you can't assign var to a public scope you need to define it inside the method for your code to run. Does anyone know the data type of the player

c#:

var Sound = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();

Connectivity changed in xamarin forms for WIFI

$
0
0

Hi,

I am using Xamarin forms essential for ConnectivityChanged.I have 3 scenario
1. Internet is ON-working fine
2. Internet is Off-working fine
3. Wifi in one device is ON, but Mobile Data Hotspot in another device is OFF

The below method is triggered for first 2 scenario, But not for 3rd scenario.
async void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
{

}
how it will work....Please help me with this

Bindings in a ControlTemplate with GradientStops

$
0
0

I have a ControlTemplate where I pass in two BindableProperties (CardPrimaryColor, CardSecondaryColor)

<ctrls:CardView
            CardDescription="{Binding Name}"
            CardPrimaryColor="AliceBlue"
            CardSecondaryColor="White"
            CardSubtitle="{Binding LastUpload, Converter={StaticResource DateConverter}, ConverterParameter='g'}"
            CardTitle="{Binding Nr}"
            IconImageSource="{Binding SyncIcon}">
            <ctrls:CardView.GestureRecognizers>
              <TapGestureRecognizer Command="{Binding Source={RelativeSource AncestorType={x:Type vm:SampleListPageViewModel}}, Path=OnItemTapped}" CommandParameter="{Binding .}" />
            </ctrls:CardView.GestureRecognizers>
          </ctrls:CardView>
<Style TargetType="ctrls:CardView">
      <Setter Property="ControlTemplate" Value="{StaticResource CardViewControlTemplate}" />
    </Style>

If I bind the BackgroundColor of the Frame, this works correctly and gives me a solid color background. Trying to get a gradient, I attempted to use the new Gradient functionality, but binding the GradientStop Colors does not work.
If I hardcode the GradientStop colors, it works, so I don't really know what to do here. I tried with several RelativeSource markup extension bindings, but nothing worked.

 <ControlTemplate x:Key="CardViewControlTemplate">
       <StackLayout>
         <Frame
     <!-- This works: -->
     <!-- BackgroundColor="{Binding CardPrimaryColor}" -->
           Margin="10,0,10,0"
           BindingContext="{Binding Source={RelativeSource TemplatedParent}}"
           BorderColor="{Binding BorderColor, FallbackValue='DarkGray'}"
           CornerRadius="10"
           HasShadow="True">
           <Frame.Background>
             <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
        <!-- This DOES NOT work :( -->
               <GradientStop Offset="0.1" Color="{Binding CardSecondaryColor, FallbackValue='White'}" />
               <GradientStop Offset="1.0" Color="{Binding CardPrimaryColor}" />
            </LinearGradientBrush>
           </Frame.Background>
           ...
         </Frame>
       </StackLayout>
     </ControlTemplate>

I am at a loss, any insight is greatly appreciated. Thanks!

Speed up performance when load too many control in iOS

$
0
0

Hi,

My example page has 400 controls. In iOS, it take 7s - 8s to load my page, but in Android, it take 1s - 2s.

So how can i speed up when load page in iOS like Android?

Thank you!

Detect the time when user enable mobile data

$
0
0
How can we detect the time that when the user have on/off his internet in his device.

Check if renewable subscription is active (Plugin.InAppBilling)

$
0
0

Hello, I am using the InAppBilling plugin to purchase different subscriptions. My problem is, I don't know how to check if a renewable subscription is active. I tried to get this information like this:

var purchases = await CrossInAppBilling.Current.GetPurchasesAsync(ItemType.Subscription);
if(purchases == null)
{
    return false;
}
{
    foreach(var subscription in purchases)
    {
        Console.WriteLine(subscription);
    }
    return true;
}

This is the console output:
ProductId:com.myapp.subscription1 | AutoRenewing:False | State:Purchased | Id:myProductId

I already tried to use the shared secret as payload and get the information with this code snippet:

Console.WriteLine(subscription.Payload);

but the output was always null.
Maybe someone can help me, thanks in advance.

Dependency Service How do I pass values from standard project to droid project

$
0
0

i have a method that need to use native droid functions. I am using Dependency services to achieve that which is fine, however i also need to send a value that gets filled in my standard project.Now in droid the value is null.

My Service

public interface INavigationService
{
void PushDictionary(List allWordsOfUserForAutomat);
}

My Implementation

public class NavigationImplementation : Activities.INavigationService
{
public void PushDictionary(List allWordsOfUserForAutomat) //HERE I SEE THE VALUE
{
Intent intent = new Intent(MainActivity.Instance,typeof(LockScreenDictionary));
MainActivity.Instance.StartActivity(intent);

        }

}

My standard

protected void LockScreen()
{

 if (!viewDisabled)
   {
     DependencyService.Get<INavigationService>().PushDictionary(_allWordsOfUserForAutomat); //HERE I SEE THE VALUE

    }
     else
    {
NotificationService.ShowToast("Nothing to play");
    }
 }

My droid project

[Activity(Label = "LockScreenDictionary", Theme = "@style/Theme.Splash")]

public class LockScreenDictionary : FormsAppCompatActivity
{

  private List<Word> _allWordsOfUserForAutomat;  //HERE ITS NULL
  protected override void OnCreate(Bundle savedInstanceState)
  {
    base.OnCreate(savedInstanceState);
   LangUpDictionaryPlayer.PlayAutomat(_allWordsOfUserForAutomat);  //HERE ITS NULL
   }

}

XF Prism DialogService Focus/Unfocus Entry in Dialog on Open/Close

$
0
0

Hi,

I've implemented prism DialogService as per instructions here:

https://prismlibrary.com/docs/xamarin-forms/dialogs/dialog-service.html

and ContactSelector demo here:

https://github.com/PrismLibrary/Prism-Samples-Forms/tree/master/07-DialogService/src/PrismSample/Dialogs

I have an entry in the dialog I want to focus on when opening the dialog.

I have managed this with OnAppearing for the Dialog View.

I've noticed the keyboard remains when the Dialog is closed so I want to UnFocus on Close action.

Have tried OnDisappearing in the View class but as it doesn't inherit from Page (presumably) it doesn't fire. Not sure why OnAppearing does though.

I've also tried to get BindingContext (ViewModel) in View class so I can pass the Entry to the ViewModel and UnFocus in the OnDialogClosed but the BindingContext is null.

Any ideas?

Thanks in advance.


How to prevent overflow and fit elements in parent

$
0
0

This is a stacklayout which is inside a grid
<StackLayout Grid.Row="4" Grid.ColumnSpan="3" Orientation="Horizontal" Padding="10,0"> <Button AutomationId="AButton" ImageSource="a_image" HorizontalOptions="FillAndExpand" Visual="Material"> </Button> <Button AutomationId="BButton" ImageSource="b_image" HorizontalOptions="FillAndExpand" Visual="Material"> </Button> <Button AutomationId="CButton" ImageSource="c_image" HorizontalOptions="FillAndExpand" Visual="Material"> </Button> <Button AutomationId="DButton" ImageSource="d_image" HorizontalOptions="FillAndExpand" Visual="Material"> </Button> </StackLayout>

On small screens (<800) this causes the fourth button to overflow the StackLayout and end up outside the screen. Why?
A workaround is to set a WidthRequest to some of the buttons to fit everything on screen, but I would expect "FillAndExpand" to take up as much space as it can and not overflow.

Pulling out your hair because of no lifecycle concept in Xamarin.Forms?

Cell phone app to get to a website

$
0
0

I have a small cell app and I would like sample code to access my website without using WebView.. I need sample code WITHOUT USING WEBVIEW

Plugin.BLE doesn't find any devices - Android 10 and target SDK 29

$
0
0

If I compile my app against Android SDK 28 everything works fine, but if I target Android SDK 29 the plugin doesn't find any devices when running on some Android 10 phones. Has anyone experienced the same? Any workaround or fix for it?

I've tried both the latest stable and pre-release versions of Plugin.BLE.

How to delete an image from a file pictures on xamarin forms?

$
0
0

I've tried this, but it doesnt work

Null reference from DependencyService

$
0
0

Please can someone explain why the line in the shared code throws a null reference exception

Shared project:

 KeyValuePair<List<ImageListItem>, List<Image>> imageListItems = DependencyService.Get<IImageFetcher<ImageListItem, Image>>. 
 ().GetImageListItems(); **--null reference**

IOS:

[assembly: Dependency(typeof(IOSImageFetcher))]
namespace Ferret.iOS
{
public class IOSImageFetcher : IImageFetcher<ImageListItem, UIImage>
      { 
            //code omitted 
      }
{

IImageFetcher:

public interface IImageFetcher<T, K>
{
    KeyValuePair<List<T>, List<K>> GetImageListItems();
}  

According to shell renderer how to do theme icon and text color states?

$
0
0

ı am trying like that it is not working?

[assembly: ExportRenderer(typeof(AppShell), typeof(CShellRenderer))]
namespace Goo4.Droid.Renderers
{
public class CShellRenderer : ShellRenderer
{
public CShellRenderer(Context context) : base(context)
{
}
protected override IShellBottomNavViewAppearanceTracker CreateBottomNavViewAppearanceTracker(ShellItem shellItem)
{
return new CBottomNavViewAppearance();
}

}


public class CBottomNavViewAppearance : IShellBottomNavViewAppearanceTracker
{
    public void Dispose()
    {

    }

    public void ResetAppearance(BottomNavigationView bottomView)
    {

    }    

public void SetAppearance(BottomNavigationView bottomView, IShellAppearanceElement appearance)
{

        OSAppTheme appTheme = Application.Current.RequestedTheme;


        Application.Current.RequestedThemeChanged += (s, a) =>
        {


            if (Application.Current.UserAppTheme == OSAppTheme.Dark) {
                //    // Respond to the theme change

                bottomView.SetBackgroundColor(Android.Graphics.Color.ParseColor("#000000"));

                int[][] states = new int[][]{
                        new int[]{-Android.Resource.Attribute.StateChecked},  // unchecked
                        new int[]{Android.Resource.Attribute.StateChecked},   // checked
                        new int[]{}                                // default
                };

                int[] colors = new int[]{
                        Android.Graphics.Color.ParseColor("#dddddd"),
                        Android.Graphics.Color.ParseColor("#ff0000"),
                        Android.Graphics.Color.ParseColor("#dddddd"),
                    };

                ColorStateList navigationViewColorStateList = new ColorStateList(states, colors);
                bottomView.ItemIconTintList = navigationViewColorStateList;
                bottomView.ItemTextColor = navigationViewColorStateList;

            }
            else
            {
                bottomView.SetBackgroundColor(Android.Graphics.Color.ParseColor("#ffffff"));
            }


        };



    }

Lifetime of ViewModel

$
0
0

Hi,

What is the lifetime of a viewmodel?

For example, can I use a ViewModel variable called isSignedIn and it will be stored even when the app is closed or killed?

or I should still use the SecureStorage / Preference for that?

Thanks,
Jassim

How to delete an image from a file picture? Xamarin forms

Passing values to intent with JSON

$
0
0

am trying to pass value using Newtonsoft.Json from shared project to droid project. So in my shared project i am serializing the object as follows and getting certain result, also displayed below. Then i am taking that result to droid project and trying to deserialize value however i am getting an exception also displayed below

i am trying to pass value using Newtonsoft.Json from shared project to droid project. So in my shared project i am serializing the object as follows and getting certain result, also displayed below. Then i am taking that result to droid project and trying to deserialize value however i am getting an exception also displayed below

My Project

public void PushDictionary(List allWordsOfUserForAutomat)
{
var second = new Intent(MainActivity.Instance, typeof(LockScreenDictionary));

        second.PutExtra("MyData", JsonConvert.SerializeObject(allWordsOfUserForAutomat));
        var result = JsonConvert.SerializeObject(allWordsOfUserForAutomat);

        Console.WriteLine(result);
        MainActivity.Instance.StartActivity(second);
    }

Outcome of my result from json here is "[{\"Id\":3391,\"SentenceId\":40616,\"TextEng\":\"expensive\",\"Explanation\":\"expensive (price)\",\"GrammarDetail\":null,\"DateToShow\":\"0001-01-01T00:00:00\"}]"

My droid

var allWordsOfUserForAutomat = JsonConvert.DeserializeObject(Intent.GetStringExtra("MyData"));
List _allWordsOfUserForAutomat = null;
_allWordsOfUserForAutomat.Add(allWordsOfUserForAutomat);
LangUpDictionaryPlayer.PlayAutomat(_allWordsOfUserForAutomat);

However i am getting this exception, can someone please advise me

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'AT.Model.Word' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

Upload a list of images of type UIImage

$
0
0

My app will retrieve a list of all images from a specific folder and attempt to upload them to a server via an API endpoint

Due to the above requirements, an image picker is not suited

Below is the method in the shared code that is passed a list of UIImages (I am trying to get it to work with just ios for now but the same scenario will eventually be applied to Android also)

The below does not work, as when I view the image on the server(AWS), it is in code format. It also says the content type is application/json on the server which I don't understand as I'm setting it to image/png

  private async Task UploadImages(List<UIImage> images)
    {            
        HttpClient client = new HttpClient();
        var contentType = new MediaTypeWithQualityHeaderValue("image/png");
        client.DefaultRequestHeaders.Accept.Add(contentType);
        client.DefaultRequestHeaders.Add("Id-Token", Application.Current.Properties["id_token"].ToString());

        foreach (var image in images)
        {
            try
            {                                        
                string baseUrl = $"https://********/dev/ferret-test/media/team1/user1/device1/test1.png";             
                client.BaseAddress = new Uri(baseUrl);

                //UploadModel uploadModel = new UploadModel
                //{
                //    image_file = image.AsPNG()
                //};

                byte[] bArray = null;
                Stream pst = image.AsPNG().AsStream();
                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Position = 0;
                    pst.CopyTo(ms);
                    bArray = ms.ToArray();
                }

                //string stringData = JsonConvert.SerializeObject(bArray);
                //var contentData = new StringContent(stringData,
                //System.Text.Encoding.UTF8, "image/png");

                //Byte[] myByteArray = new Byte[imageData.Length];
                //System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));                        

                var postRequest = new HttpRequestMessage(HttpMethod.Put, baseUrl)
                {
                    Content = new ByteArrayContent(bArray)
                };

                var response = await client.SendAsync(postRequest);
                response.EnsureSuccessStatusCode();
                string stringJWT = response.Content.ReadAsStringAsync().Result;   
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }       

how to output data from one page to another from the collection of the selected item?

$
0
0

I have two XAML pages and one of their common ViewModel page.I want to output data from one page to another from the collection of the selected item. It must be Labels Text. I have a problem If I bind Labels Text to a variable. I can see data only on the current page. But if I go to another page and place the same label there, the information is not displayed. I do not understand why so because on the next page the same variable which already contains data

https://stackoverflow.com/questions/63623080/how-to-output-data-from-one-page-to-another-from-the-collection-of-the-selected?noredirect=1#comment112507636_63623080

I posted my question there. Please help. There you can see code and problem description.First problem I solved.Please help me to output data from one page to another from the collection of the selected item

Viewing all 79144 articles
Browse latest View live


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