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

How to get MainActivity for an Intent created in another class in Xamarin.Droid project?

$
0
0

I want to set alarm for Xamarin.Droid project. Use DependencyService for platform-specific functions, define an interface with the signature of these functions

namespace ExampleProgram.Droid
{
    public interface IRunAlarm
    {
        Intent setIntent();
        ...
    }
}

and class with implementation.

[assembly: Dependency(typeof(ExampleProgram.Droid.RunAlarm))]
    namespace ExampleProgram.Droid
    {
        public class RunAlarm: MainActivity, IRunAlarm
        {
            public Intent setIntent()
            {
                Intent i = new Intent(this, typeof(AlarmReceiver));
                return i;
            }
            ...
        }
    }

But, when I run the program, an exception occurs:

Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

An exception occurred on this line:

Intent i = new Intent(this, typeof(AlarmReceiver));

How to handle this exception and how to get MainActivity correctly in this case?


How to print

$
0
0
I have decided to migrate an existing WinForm application to XF.

It’s basically a very simple invoicing software for a shop and I was really excited about the performance when I started the project and managed to create iOS, Android, UWP, WPF and macOS all using the same code base (98% of the code is shared)

My project is a shared project (NOT PCL) and all I want to be able to do now is to print the invoices (not necessarily silently like POS)

I have to say that I am baffled that I can’t find a single working example after spending 12 hours on it...

I had been thinking using Shared Code would be giving me more flexibility to access native functions thanks to the #if #endif compiler directives but now I have minimised my expectations and will be the happiest man alive if I can at least print an invoice in the UWP/WPF only ...

I decided to create a PDF first to make things easier and consistent in terms of invoicing layout and even that was a big issue (using iTextSharp failed) so I ended up posting data to a WebService and then leaving PDF generation to the backend

Now, my question is how can I print that PDF using the device’s installed printer? (For now only in UWP/WPF and if I succeed I will be looking for other platforms)

Multiple datatemplates binding

$
0
0

Hi, I am sorry if the question is stupid...

I am trying to use multiple DataTemplates in ListView. The Table binding goes well, whereas the Conversation not... The error message is "No property, bindable property, or event found for Name" (I have the property Name in the ConversationUserControl).

The ItemsSource is a list of objects inherited from the same abstract class.

Maybe the problem is in binding inside the ResourceDictionary, but I don't understand why it works for the first DataTemplate and not for the second one :(
Please help.

.... 
   <ContentPage.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="Table">
                <ViewCell>
                    <local:TableUserControl Table="{Binding Table}"/>
                </ViewCell>
            </DataTemplate>
            <DataTemplate x:Key="Conversation">
                <ViewCell>
                    <local:ConversationUserControl Name="{Binding Name/*  DOESN'T WORK HERE */ }"/>
                </ViewCell>
            </DataTemplate>            
            <local:ContentTemplateSelector x:Key="ContentTemplateSelector"
                                           TableContentTemplate="{StaticResource Table}"
                                           ConversationContentTemplate="{StaticResource Conversation}"/>
        </ResourceDictionary>
    </ContentPage.Resources>

..
    <ContentPage.Content>
        <ListView ItemsSource="{Binding Contents}"
                  ItemTemplate="{StaticResource ContentTemplateSelector}"
                  HasUnevenRows="True" >
        </ListView>
    </ContentPage.Content>

GridUserControl class (the ConversationUserControl is almost the same, only the property is of type Conversation and OnTableChanged method is different too):

public partial class TableUserControl : Grid
{
    public TableUserControl ()
    {
        InitializeComponent ();                                   
    }

        public static readonly BindableProperty TableProperty =
            BindableProperty.Create(nameof(Table), typeof(MyTable), typeof(TableUserControl), null,
                BindingMode.OneWay, null, OnTableChanged);

        public MyTable Table
        {
            get { return (MyTable)GetValue(TableProperty); }
            set  {   SetValue(TableProperty, value);  }
        }

        private static void OnTableChanged(BindableObject bindableObject, object oldobject, object newobject)
        {
              . . . . . .
        }                    
    }

Xamarin form - Firebase notification with image

$
0
0

i want to send notification from firebase console with image, i have successfully implement in my xamarin form i can get device token and can send notification to device from firebase console, but the problem is that i want to send notification with image and i dont know how i can do that, as in firebase console there is no option to select image or write url, so it must be something from xamarin form where we recieve notification. Please check the image below how i want to recieve notification.

notification with image

Persisting data locally (Device cache)

$
0
0

Hi,

Is there a way how you can persist some trivial data locally, such as personId or cartvalue so that when the app is switched off, the value can be retrieved again?

I have been playing around with Application.Current.Properties ["ProfileId"] but the value is lost once the application is closed.

Thanks
Shaun

Real Time FCM Database Sync With Xamarin Form

$
0
0

i am able to get the fcm realtime database data in my xamarin forms, but i want when i change the data of my database on fcm it should also change in my xamarin form application, i had seen people doing it with native form, but that approach didn't worked for me,
please help me if you have any solution for it

Xamarin.livereload: Can't find package

$
0
0

Hello,
I am trying to compile a project (developed by others) that relies on the xamarin livereload package. Unfortunately I can't get this package to install.

I have downloaded the VSIX file as described in the documentation and that installed successfully, but I get this message from nuget when I open the project solution:
Error NU1101 Unable to find package Xamarin.LiveReload. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages, NuGet

I googled this and tried a variety of fixes, notably:

I tried multiple variations of this line in the console: install-package xamarin.livereload -prerelease -project myprojectname
And I opened the package manager, set 'source' to 'All' and ticked the 'include prerelease' button. Livereload shows up in the Installed tab of the package manager but states 'not available in this source'.

What am I missing here? I presume I need to add a new source to nuget or something equally similar but I'm not sure what that source is. Any tips?

Spam is getting out of hand

$
0
0

Title basically says everything. The spam from whoever these guys are is getting seriously out of hand. It is nearly impossible to use the forum with the amount of "shitposting" going on. Can't the admins do anything against that. It's really grinding my gears....


Link Assemblies Task failed unexpectedly Error

$
0
0

I have added the Plugin.MediaManager.Forms in my xamarin forms project for video view. The project was working fine before adding this plugin in my project, but after i have added the plugin, the project doesn't compile for android giving " Link Assemblies Task failed unexpectedly " error. Can somebody help me ?

It works fine for IOS.

Moreover, the plugin installs with warnigs too :

Package 'Plugin.MediaManager.Forms 0.4.5' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.

Command binding in button not working

$
0
0

Using Xamarin Forms with Visual Studio 2017.

Button click on iOS is not calling the Command action.

It works on Android but iOS not.

I am using Linker Behavior: Link All

This is my code:

XAML

 <StackLayout Orientation="Vertical" >
                                <Button x:Name="btnSignIn" Text="Log in" BackgroundColor="#0072BD" TextColor="White" FontSize="20" FontAttributes="Bold"  HorizontalOptions="CenterAndExpand" Command="{Binding LoginCommand}"/>
                            </StackLayout>

XAML.cs

public LoginPage()
    {
            InitializeComponent();         
            BindingContext = viewModel = new LoginPageViewModel();
            viewModel.Navigation = this.Navigation;
            PasswordEntry.Text = string.Empty;

            EmailEntry.Focus();
            EmailEntry.Completed += (s, e) => PasswordEntry.Focus();           
            switchRemember.Toggled += switchremember_toggled;
    }

ViewModel

            public LoginPageViewModel()
                {
                        RememberChecked = false;
                       LoginCommand = new Command(Login);          
                        IsBusy = false;
                }

    public async void Login()
        {

                if (Settings.IsConnected)
                {
                    IsBusy = true;

                  ..... //Complementary code

                    IsBusy = false;
                }
                else
                    ShowAlert("Failed connection", "Check your internet connection.");

        }

I tried the answer from @christopherpolska
https://forums.xamarin.com/discussion/88071/mvvmcross-not-binding-barbutton-click-event-on-device

but didn´t work for me.

Apk size is too large.How to reduce it?

$
0
0

In my xamarin form application I am using Telerik.but when I release my apk for playstore,the apk size taking 86 mb..so how to reduce it?

I checked all linking setting,while using sdk and user assembly,and sdk assembly only then apk not open.

how to solve this?

Grouped Listview overlapping with bottom navigation bar for iOS?

$
0
0

I have a bottom navigation bar (Tabbed Page) with four 4 tabs, the 4th tab has navigation page which will navigate to other pages.
The 4th tab is having grouped listview which will navigate to other pages and again if I click on the 4th tab from child pages of 4th Tab will navigate to the Top page (which is grouped list page) making the problem. If I click other Tabs and come back to 4th Tab is not creating the problem.
If I coming back to the 4th tab (grouped listview page) from child page of list page the last 2 items are not able to click. Here my assumption is the bottom tab bar is overlapping with listview while coming back from the child page.
But if I come back from the main tabs it is working fine. And this is occurring for iOS only Android is working fine.
Can anybody help me out to fix this issue?

How to change Pin position on location changed event

$
0
0

I am developing an app to track users live location.I have the updated positions from geolocator plugin.when i get new positions i change the pin position.But it is not changing in the map.Here is the code,
this method is called in every 1 sec
private async void TrackMe()
{
var current = await CrossGeolocator.Current.GetPositionAsync();
current.Accuracy = 30;
float bearing =float .Parse ( current.Heading.ToString ());
var pins = new Pin { Label = "ME", Icon = BitmapDescriptorFactory.FromBundle("path4646.png"), Flat = true };
var latitude = current.Latitude;
var longitude = current.Longitude;
Device.BeginInvokeOnMainThread(() =>
{
pins.Position = new Position(latitude, longitude);
pins.Rotation = bearing;
if (MapTrack.Pins.Count == 0)
{
MapTrack.Pins.Add(pins);
}
MapTrack.MoveCamera(CameraUpdateFactory.NewPosition(new Position(latitude, longitude)));
});
}

Any help will appreciated, thanks in advance
Regards

Activity Indicator is not Showing unless async method finish

$
0
0

I have a login page that takes token and approve from webAPI. I need to show activity Indicator on that period. I am using MVVM pattern.

My XAML ;

  <StackLayout>
  <Grid>
 <Grid>
 <Button x:Name="Btn_Login" TextColor="White" Text="LOGIN" Command="{Binding LoginCommand}" BackgroundColor="Green" Grid.Row="0" Grid.Column="2" CornerRadius="25" BorderRadius="25"/>
            </Grid>

        </Grid>

    </StackLayout>
    <StackLayout>
        <ActivityIndicator IsVisible="{Binding IsBusy}"  IsRunning="{Binding IsBusy}" Color ="Black"/>
    </StackLayout>

My MVVM;

 private bool _isBusy;
    public bool IsBusy
    {
        get { return _isBusy; }
        set
        {
            _isBusy = value;
            OnPropertyChanged(nameof(IsBusy));
        }
    }

  public ICommand LoginCommand => new AsyncCommand(Login);

  private async Task Login()
    {

        await MakeTrueIsBusyStatus();
        await AddValidations();

        bool isValid = Validate();
        if (isValid)
        {
            User user = new User(LoginUserName.Value, LoginPassword.Value);


            var token = "";
            ServiceManager serviceManager = new ServiceManager(user);

            string response = await serviceManager.Login();

            var apiResponse = JsonConvert.DeserializeObject<WebApiResponse<MyResponse>>(response);
            var jObjectResponse = JObject.Parse(response);
            var statusCode = jObjectResponse.GetValue("statusCode").ToString();

            if (apiResponse.StatusCode == (Int32)HttpStatusCode.OK)
            {
                var jObjectResult1 = JObject.Parse(jObjectResponse.GetValue("result").ToString());

                token = jObjectResult1.GetValue("token").ToString();
                try
                {
                    await Navigation.PushModalAsync(new MyMasterDetailPage());

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
            {
                await MakeFalseIsBusyStatus();
                var errorResponse = JObject.Parse(jObjectResponse.GetValue("errorResponse").ToString());
                await Application.Current.MainPage.DisplayAlert(jObjectResponse.GetValue("message").ToString(),
                    errorResponse.GetValue("exceptionType").ToString(), "cancel");

            }
        }

     private async Task MakeTrueIsBusyStatus()
    {
        IsBusy = true;
    }

    private async Task MakeFalseIsBusyStatus()
    {
        IsBusy = false;
    }

My problem is that when i click login button my UI froze and not showing activity indicator unless login method finish. I used all method async but still UI freeze so activity indicator not showing. Please help why is this happening?

How to provide instruction when open the app in xamarin.forms?

$
0
0

I want to provide instruction of the user that how user can use the app.but i did not found any method for instruction.if any one have any method to define instruction when user open the app first time please suggest me for this.i found showcase in android.is there any method in Xamarin forms.


View class to PDF/image

$
0
0
I have a database filled with student’s data and i have generated a report with all that data, the data is generated in a grid(can be listview too) and is there anyway to convert that grid or any view class like stacklayout into a PDF file or image file that will be saved into the user’s device? The report i generated will be quite large and is scrollable horizontally and vertically.
Im currently using Xamarin.forms but implementation is only on Android.
Thanks in advance :)

Edit: the screenshot method is not suitable as the report height and width will be larger than the device screen

Accessing SQL Server from mobile app remotely

$
0
0

Hi, I have created different web services to access my sql server database from a mobile device. The thing is they both the mobile device and my laptop had to be in the same network(wifi). Now, I would like to know what do I need to do in order to using my mobile app from the outside access to a remote database.
Please be specific with your answer, I would like to know if a rest api is the best choice or not, and if it is then what's the procedure to implement remote access and what's the security configuration for sql server. thanks.
I using Xamarin Forms(cross platform) and SQL Server 2017.

Breakpoints not loaded in UWP without .Net Native Toolchain enabled

$
0
0

When creating a new Net Standard Xamarin Cross-Platform App then putting a breakpoint in shared code and starting the UWP app the debugger does not break on the breakpoint and VS says the breakpoint is not loaded. If you go to [UWP app] > bin > Debug > x86 > AppX there are no pdb files, which is why I assume the breakpoints don't get loaded.

Does anyone have a solution to this? Enabling .Net Native Toolchain fixes the issue, but makes compiling much slower. An issue was posted to the VS developer community, but it doesn't seem to be getting much attention...

developercommunity.visualstudio.com/content/problem/124393/uwp-breakpoints-ignored-when-net-native-toolchain.html

How can i change view label color from view model.

$
0
0
I want to show error to user after form validation. I am doing validation in my command can execute method.
If validation fails how can i tell user about the error in input?

How to put image in Sqlite database ?

$
0
0

Hi guys i created database in my Xamarin project , and I want to put images also in database,small icons ...How can I do that ?

My database look like this

Public class Person
{
public string Photo {get;set;}
}
How to set now a photo here in database ?

Viewing all 77050 articles
Browse latest View live


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