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

Data Best Practices Opinions

$
0
0

Developing an Xamarin Android app that is data centric. A set of activities that make API calls and display the response. Currently I am making the API calls from the activity. Things work but what is the best practices for the calls. When the devices rotates and the activity gets rebuilt the API is recalled. I am thinking that this is not smart. Should this go to HandlerThread, service ?? trying not to reinvent the wheel. Thx for the input.


Previewer background colour or style setting?

$
0
0

Hi, when I use the Xamarin Forms Previewer in Visual Studio 2017 (15.6.7) my app is shown in 'dark' mode or style i.e. has a black background, text is white (or light gray) yet when I run the app on my phone again using VS the background is white, text dark.

Is there some setting I need to change to make the previewer the same as my phone?

Note this is the Android preview.

Thanks John

Xamarin forms android - disables SSL CA validation

$
0
0

Hello we are facing a security problem with apk, there's a application validating our apk (Appthority) and reports this:

Disables SSL CA Validation

[
{
"status": "DISABLED",
"hostname": "xxx.xxxxxx-xx.com",
"connection": "10.27.68.128:40326->192.129.240.16:443",
"validation_hostnames": [
]

wa are using https connection for WS and SSL/TLS implementation, and trusted certificate

this only happens with apk but not with ipa

greetings

Detect a person's anthropometric measurements with the camera

$
0
0

Hello, I have to develop an app that has to detect a person's anthropometric measurements with the camera.
Can uou help me? Thanks.

External USB webcam plugin for Xamarin.Android

$
0
0

Hi!

Did anybody ever tried to attach external USB webcamera by OTG cable to Android device and take photo or video using this camera?
There are several applications in Play Store which can demonstrate the above, for example this.

After some searching I've found a native library libuvc, which provides all the necessary functionality to reach the above.
My question is wheter it is possible to make by somebody a similar wrapper and nuget package for this library like for example sqlite or UrhoSharp?

They are using the same way to provide the needed functionality in Xamarin: Wrapping a native library into a C# library which can be then easily used in any Xamarin project.

(iOS) Button Click doesn't get hit when adding Grid layout (xaml)

$
0
0

I created simple blank Xamarin forms project. When I add the Grid layout object to my xaml, button clicks don't get hit. If I remove the grid, button clicks code is getting hit. Any ideas what is wrong?

Note: Fixed markdown in this discussion to correctly display the XAML.

XAML:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:BlankForm" x:Class="BlankForm.BlankFormPage">
    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="53"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <StackLayout Orientation="Vertical" Grid.Row="0" Grid.Column="0">
            <Button x:Name="Connection" Text="line" Clicked="Handle_Clicked"/>
            <Button x:Name="Btn2" Text="Btn2" Pressed="OnPress" Clicked="Handle_Clicked2" ></Button>
        </StackLayout>
    </Grid>
</ContentPage>

App xamarin + website

$
0
0

Hello good day,
I have the following problem if someone could guide me. I'm creating a mobile application for android and ios, and I would like to know how I can create a web page and synchronize the database using MySQL.

ListView not updating UI when changing bindable property from ViewModel

$
0
0

Hi there, everyone!

I have a simple listview on my Xamarin application which contains iterates over the menu items from an ObservableCollection:

<views:MenuItemsListView x:Name="_menuItemList"
    ItemsSource="{Binding MenuItems}"
    SelectedItem="{Binding SelectedMenuItem}"
    SeparatorVisibility="None">

    <ListView.Behaviors>
        <behaviors:EventToCommandBehavior EventName="ItemTapped"
            Command="{Binding NavigateCommand}" />
    </ListView.Behaviors>
</views:MenuItemsListView>
  • MenuItemsListView is a simple list view with a stackLayout and two labels.

On my ViewModel constructor, I'm inserting the available menus and updating the SelectedMenuItem in order to make the first item initially activated:

public MasterPageViewModel(INavigationService navigationService)
    : base(navigationService)
{
    MenuItems.Add(new MenuItemModel { Icon = "\ue88a", PageName = "HomePage", Title = "Início" });

    MenuItems.Add(new MenuItemModel { Icon = "\ue7fd", PageName = "CustomersListPage", Title = "Clientes" });

    MenuItems.Add(new MenuItemModel { Icon = "\ue871", PageName = "ProductsListPage", Title = "Produtos" });

    MenuItems.Add(new MenuItemModel { Icon = "\ue8cc", PageName = "OrdersListPage", Title = "Pedidos" });

    SelectedMenuItem = MenuItems[0];
    MenuItems[0].IsSelected = true;

    NavigateCommand = new DelegateCommand(HandleNavigate);
}

I can assure the SelectedMenuItem is being correctly updated. Basically, I'm using Prism's SetProperty to update the referenced _selectedMenuItem. For some odd reason, the background color of selected item is never updated (except when navigating, when it works accordingly).

I tried some solutions suggested here and there, but, as of now, none of them worked. I really appreciate if someone can help me with this!


Broadcast receiver not firing on receive

$
0
0

Here is my broadcast receiver code:

[BroadcastReceiver]
[IntentFilter(new[] { BluetoothDevice.ActionFound })]
public class BlueToothDeviceBroadcastReciever : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
IBlueToothService service = Xamarin.Forms.DependencyService.Get();
string action = intent.Action;
if (action == BluetoothDevice.ActionFound)
{
BluetoothDevice newDevice = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
service.DeviceAdded(new Models.BluetoothDevice(newDevice.Name, newDevice.Address));
}
}
}

Here is my on-resume code for the activity:

protected override void OnResume()
{
if(bluetoothDeviceReceiver == null)
{
bluetoothDeviceReceiver = new BlueToothDeviceBroadcastReciever();
}
RegisterReceiver(bluetoothDeviceReceiver, new IntentFilter(BluetoothDevice.ActionFound));
base.OnResume();
}

and I am calling start scan once the user clicks a button:

public void StartScan()
{
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
if(adapter.IsEnabled)
{
adapter.StartDiscovery();
}
}

I cant get the OnReceive to fire inside the broadcast receiver
did I miss anything?

Thanks!

Xamarin iOS Notifications (Dependency Service)

$
0
0

Hi,

I have a really weird problem, I hope you can help me.
I am implementing notifications in a Xamarin.Forms project, working in both android and iOS platform. To do so, I have to use Dependency Service, so I can make a native implementation of the notification for both platforms. In android it works ok, but in iOS, for some reason, when it enters the iOS method to make the notification, it just returns in the middle of the method without throwing any message or error, as if it was a "return" keyword. I proved what happened if I call that same method with the same parameters from another point of the app, and it works very well in that case, but it doesn't when I call it from the point where it is supposed to do it.

I show you the interface for the Dependency Service:

public interface INotificationsManager
{
    void GenerateNotification(string title, string content);
}

And where I call it in the Shared Project:

    public class ServConnection
    {
    INotificationsManager iNotManager;

        private ServConnection()
        {
        iNotManager = DependencyService.Get<INotificationsManager>();
        NotifyMessage();
    }

        private void NotifyMessage()
        {
        iNotManager.GenerateNotification("Test", "This is a message");
    }
}

This is the implementation in the iOS project:

    public void GenerateNotification(string title, string content)
    {
        UILocalNotification notification = new UILocalNotification
        {
            FireDate = NSDate.FromTimeIntervalSinceNow(0),
            AlertTitle = title,
            AlertAction = "View Alert",
            AlertBody = content,
            ApplicationIconBadgeNumber = 1,
            SoundName = UILocalNotification.DefaultSoundName
        };

        UIApplication.SharedApplication.ScheduleLocalNotification(notification);
    }

When it enters this method, it just doesn't get to the end. What can be wrong?

Change Button Text

$
0
0

I'm using Xamarin Forms to develop a Cross-Platform app.
I want to change the Text of the button "Start Job" to something like "Finish".
When clicking StartJob and then change to Finish Job.

LocalBroadcastManager - where is it?

$
0
0

Has anyone used LocalBroadcastManager with their App?
I have not been able to type in class package out in anyway that Visual Studio will recognize there is such a class.

I am only able to use BroadcastManager which is not exactly what I want.

If you have it in your IDE can you please tell me where it is located

Thanks

How to get an original image size?

$
0
0

Hi! I have the very basic case, but can't find elegant solution: need to know original image size for layout. But after loading an image to Image view I get -1 value for its width and height.

Here's a code sample, what I'm trying:

var icon = new Image {
    Source = ImageSource.FromFile("icon-edit.png")
};

// This will output -1 values for width and width request
Console.WriteLine("Width={0}, WidthRequest={1}", icon.Width, icon.WidthRequest);

// Adding to relative layout, won't work as expected! Icon's width is calculated as -1.
Children.Add(editIcon,
    Constraint.RelativeToParent((parent) => (parent.Width - icon.Width) / 2),
    Constraint.Constant(10)
);

In the example above icon should be centered horizontally and I could achieve that in some other way. But actually I'll need more sophisticated layout, that's why I need to know image width.

Why is this frame cut off?

$
0
0

I am confused why the Frame in this XAML is being cut off.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MobileMidstream.Pages.LoginPage">
    <ContentPage.Content>
        <StackLayout Orientation="Vertical">
            <Frame OutlineColor="Cornsilk"  
                   Padding="10"
                   VerticalOptions="Start"
                   HorizontalOptions="CenterAndExpand">
                    <Label Text="Username:" />
            </Frame>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

What changes to the XAML would I make to have the Frame anchor to the left side of the screen and fill across to the right side?

Generated Bindings Remove Generics

$
0
0

I am trying to bind an abstract class that uses generics:

public abstract class ResponseCallback<T>
{
  public ResponseCallback() {}

  public abstract void onResponse(Response<T> paramResponse);

  public abstract void onError(int paramInt, String paramString);
}

However, the generated C# file does not have this

 // Metadata.xml XPath class reference: path="/api/package[@name='com.test.test.module.api']/class[@name='ResponseCallback']"
[global::Android.Runtime.Register ("com/test/test/module/api/ResponseCallback", DoNotGenerateAcw=true)]
[global::Java.Interop.JavaTypeParameters (new string [] {"T"})]
public abstract partial class ResponseCallback : global::Java.Lang.Object {

    internal    new     static  readonly    JniPeerMembers  _members    = new XAPeerMembers ("com/test/test/module/api/ResponseCallback", typeof (ResponseCallback));
    internal static new IntPtr class_ref {
        get {
            return _members.JniPeerType.PeerReference.Handle;
        }
    }

    public override global::Java.Interop.JniPeerMembers JniPeerMembers {
        get { return _members; }
    }

    protected override IntPtr ThresholdClass {
        get { return _members.JniPeerType.PeerReference.Handle; }
    }

    protected override global::System.Type ThresholdType {
        get { return _members.ManagedPeerType; }
    }

    protected ResponseCallback (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}

    // Metadata.xml XPath constructor reference: path="/api/package[@name='com.test.test.module.api']/class[@name='ResponseCallback']/constructor[@name='ResponseCallback' and count(parameter)=0]"
    [Register (".ctor", "()V", "")]
    public unsafe ResponseCallback ()
        : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
    {
        const string __id = "()V";

        if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero)
            return;

        try {
            var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), null);
            SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef);
            _members.InstanceMethods.FinishCreateInstance (__id, this, null);
        } finally {
        }
    }

    static Delegate cb_onError_ILjava_lang_String_;

    static Delegate GetOnError_ILjava_lang_String_Handler ()
    {
        if (cb_onError_ILjava_lang_String_ == null)
            cb_onError_ILjava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, IntPtr>) n_OnError_ILjava_lang_String_);
        return cb_onError_ILjava_lang_String_;
    }

    static void n_OnError_ILjava_lang_String_ (IntPtr jnienv, IntPtr native__this, int p0, IntPtr native_p1)
    {
        global::Com.Test.Test.Module.Api.ResponseCallback __this = global::Java.Lang.Object.GetObject<global::Com.Test.Test.Module.Api.ResponseCallback> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
        string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer);
        __this.OnError (p0, p1);
    }


    // Metadata.xml XPath method reference: path="/api/package[@name='com.test.test.module.api']/class[@name='ResponseCallback']/method[@name='onError' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='java.lang.String']]"
    [Register ("onError", "(ILjava/lang/String;)V", "GetOnError_ILjava_lang_String_Handler")]
    public abstract void OnError (int p0, string p1);

}

[global::Android.Runtime.Register ("com/test/test/module/api/ResponseCallback", DoNotGenerateAcw=true)]
internal partial class ResponseCallbackInvoker : ResponseCallback {

    public ResponseCallbackInvoker (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) {}

    internal    new     static  readonly    JniPeerMembers  _members    = new JniPeerMembers ("com/test/test/module/api/ResponseCallback", typeof (ResponseCallbackInvoker));

    public override global::Java.Interop.JniPeerMembers JniPeerMembers {
        get { return _members; }
    }

    protected override global::System.Type ThresholdType {
        get { return _members.ManagedPeerType; }
    }

    // Metadata.xml XPath method reference: path="/api/package[@name='com.test.test.module.api']/class[@name='ResponseCallback']/method[@name='onError' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='java.lang.String']]"
    [Register ("onError", "(ILjava/lang/String;)V", "GetOnError_ILjava_lang_String_Handler")]
    public override unsafe void OnError (int p0, string p1)
    {
        const string __id = "onError.(ILjava/lang/String;)V";
        IntPtr native_p1 = JNIEnv.NewString (p1);
        try {
            JniArgumentValue* __args = stackalloc JniArgumentValue [2];
            __args [0] = new JniArgumentValue (p0);
            __args [1] = new JniArgumentValue (native_p1);
            _members.InstanceMethods.InvokeAbstractVoidMethod (__id, this, __args);
        } finally {
            JNIEnv.DeleteLocalRef (native_p1);
        }
    }

}

As you can see, I am missing the public abstract void onResponse(Response<T> paramResponse); node in my generated code. What can I do to get this and the generics included in the C# code? I have been googling all night and cant find anything.

Some articles suggest adding to the Additions file in the binding project, but I can't figure out how to get it to work and there is no documentation on the Addtions section of the binding process.

NOTE: I changed the paths in the Metadata comments as it is proprietary.


Button Text Getting Cutoff on Android

$
0
0

The text of my buttons are getting cutoff in Android when I have made the HeightRequest of the button smaller than the default. The same thing renders normally with the button text centered on iOS. Below is the code and there is an image showing the problem attached. Any help would be appreciated!

    var btnSignUp = new Button 
    {
            Text = "Vendor Sign Up",
            Font = Font.OfSize ("BenchNine-Regular", 20),
            BackgroundColor = Constants.Colors.MainBlue,
            TextColor = Color.Black,
            WidthRequest = 135,
            HeightRequest = 26,
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            Image = (FileImageSource)FileImageSource.FromFile ("arrow.png"),
    };

    var btnLogin = new Button 
    {
            Text = "Vendor Login",
            Font = Font.OfSize ("BenchNine-Regular", 20),
            BackgroundColor = Constants.Colors.MainBlue,
            TextColor = Color.Black,
            WidthRequest = 125,
            HeightRequest = 26,
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            Image = (FileImageSource)FileImageSource.FromFile ("arrow.png"),
    };

Xamarin forms local database

$
0
0

I am trying to implement a database following this: https://docs.microsoft.com/nl-nl/xamarin/xamarin-forms/app-fundamentals/databases

But I am getting an aggregate.exception on the main() function when debugging on my iphone.

I added this to my app.cs:

`
static ItemDatabase database;

    public static ItemDatabase Database
    {
        get
        {
            if (database == null)
            {
                database = new ItemDatabase(
                  Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WaarStaatSQLite.db3"));
            }
            return database;
        }
    }`

Then this is the database class:
` public class ItemDatabase
{
readonly SQLiteAsyncConnection database;

    public ItemDatabase(string dbPath)
    {
        database = new SQLiteAsyncConnection(dbPath);
        database.CreateTableAsync<Item>().Wait(); // aggregate.exception probably from this line
        Debug.WriteLine("Created Database");
    }

    //get all items from db async
    public async Task<ObservableCollection<Item>> GetItemsAsync()
    {
        Debug.WriteLine("get items");
        var data = await database.Table<Item>().ToListAsync();
        Debug.WriteLine(data.ToString());
        if(data != null)
        {
            return new ObservableCollection<Item>(data);
        }
        else
        {
            return null;
        }

    }

    //get all items from db not async
    public async Task<ObservableCollection<Item>> GetItemsNotDoneAsync()
    {
        var data = await database.QueryAsync<Item>("SELECT * FROM [Item] WHERE [Done] = 0");
        return new ObservableCollection<Item>(data);
    }

    //get item from db with id
    public async Task<Item> GetItemAsync(int id)
    {
        return await database.Table<Item>().Where(i => i.ID == id).FirstOrDefaultAsync();
    }

    //save or update a single item
    public async Task<int> SaveItemAsync(Item item)
    {
        if (item.ID != 0)
        {
            return await database.UpdateAsync(item);
        }
        else
        {
            return await database.InsertAsync(item);
        }
    }

    //delete item in db
    public async Task<int> DeleteItemAsync(Item item)
    {
        return await database.DeleteAsync(item);
    }
}`

I then call this function in the MainPageViewModel:

public override async void OnNavigatedTo(INavigationParameters parameters) { var data = await App.Database.GetItemsAsync(); if (data != null) { Debug.WriteLine(data.ToString()); Items = data; } }

OnNavigatedTo is a prism function.
I first thought maybe the OnNavigatedTo function can't be async but I found a question only saying the OnNavigatedTo function could be async void.

So I did some debugging using breakpoints and print statements and I found that the code stops in the database constructor on the createTable line. Because the Debug.writeline is never executed. Using a breakpoint on that line didn't help because i couldn't step in on the function.
I don't know if I needs to implement something in the ios-project because the sample didn't include anything.

Any help implementing databases is appreciated.

Can not find Android App template after I re-installed VS2017

$
0
0

Before I Re-Installed VS2017 When I followed the instructions Click > New > Project to create a new project. In New Project dialog, click the Android App template I found Android. But since I re-installed VS2017 I do not have a Android App template. What must I do?

[You need to increase the $(TargetFrameworkVersion) for your project] warning

$
0
0

After upgrading Visual Studio 2017 to version 15.8, my android project is getting the following warning:

The $(TargetFrameworkVersion) for App3.Android.dll (v9.0) is greater than the $(TargetFrameworkVersion) for your project (v8.1). You need to increase the $(TargetFrameworkVersion) for your project

To reproduce this error:
1. Create a new "Mobile App (Xamarin.Forms)" project with Code Sharing Strategy using ".NET Standard"
2. Build the project

In my project's Properties->Application, Compile using Android version: Android 8.1 (Oreo)
And in my Android Manaifest, Target Android version: Android 8.1 (API Level 27-Oreo)
And in my project csproj, AndroidUseLatestPlatformSdk is set to false

Anyone encountered this warning?

What's the best/simplest library for creating and displaying a QR code based on a string?

$
0
0

I've got a Xamarin app that have iOS and Android versions (.NET Standard business layer).

I've been asked to add a QR code to one of the screens. It'll encode a short string. I can't talk out to an API for this, so needs to be done on the device.

I'm looking for a simple, supported library that'll generate a QR code for me and allow me to display it on the device. Ideally will be iOS and Android, but I could use different ones for both.

I don't need scanning features.

I came across the ZXing.Net.Mobile, but looked like it could be heavier than I need, so wondered if anyone had experience/knowledge of a lighter weight solution.

Viewing all 204402 articles
Browse latest View live


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