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

Improve how Forms handles Activity Restarts on Android

$
0
0

Summary

Xamarin.Forms currently is tied to the lifecycle of an the MainActivity. This means if that activity is destroyed in anyway (OS kills it, etc) the app "restarts" and offers no way to handle this behavior or restore state. This is summarized in bug #29275.

API Changes

Copying the information from the linked bug report, this is a suggestions:

Google's recommendation for this is to use a retained fragment. The activity looks for the fragment in its fragment manager when it's created, and if it doesn't find one it creates a new one. All important state is kept in the fragment, and the activity does almost nothing. That's what we need here. Instead of FormsApplicationActivity we need FormsApplicationFragment.

Intended Use Case

A common example where the current behavior is undesirable is when the app is backgrounded to the task manager. Then, some time later the user resumes from the task manager and the app restarts. That is, MainActivity.OnCreate is called again and the entire LoadApplication process happens, effectively losing any state that the user might have had in the app.


Xamarin LiveReload - Just does nothing

$
0
0

After 3 days of beating on a brand new "Welcome to Xamarin" solution trying to get LiveReLoad to work... The best I can get is for the solution to not crash at launch.

The solution runs on both emulator and physical device. But changes in the XAML are not reflected in the running solution.
The setup instructions are pretty cut and dried:

  • Install the VSIX
  • Install the Nuget
  • Add the init call in the app class.
  • Rebuild
  • Deploy
  • Debug (F5) (Instructions say its not required. That should be listening regardless to 1 or more clients. But tried anyway)
  • Make changes in XAML and save.
  • Changes are sent to the running app when you save.
    Only they aren't.
    Does anyone see a key step I missed there?

Firewall is off
VS2017 v15.7.2
XamForms: v.Today
LiveReload: v.0.3.27

I've tried Connect from Visual studio both before and after launching on the emulator and physical device.

I am on a corporate domain network. Anyone had success on a domain?

How to consume an external api rest?

$
0
0

I need to consume a Rest API from an ERP Site, where I will list some items from this site, but I do not find anything useful that can help me to consume

I am using json and http client to perform, but the error in the process recognize the site path

public partial class ProdutoPage : ContentPage
    {
        ListView lv = new ListView();
        public ProdutoPage()
        {
            InitializeComponent();
            iniciar();
        }
        private async void  iniciar()
        {
            //tinyapp API = new tinyapp();

            //var lista = API.ListaCategorias("automacao");


            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("token", "");
            client.BaseAddress = new Uri("site");
            var resp = await client.GetAsync("site");

            if (resp.IsSuccessStatusCode)
            {
                var respStr = await resp.Content.ReadAsStringAsync();
                var l = JsonConvert.DeserializeObject<List<Pedido>>(respStr);
                lv.ItemsSource = l;
            }
        }
    }
}

I need a list of ERP site requests

mapping entity framework

$
0
0

hi! how to create a many to many mapping in xamarin forms with entity framework sqlite? my two tables are customer
public class Customer
{
[Key]
public int CustomerId { get; set; }
public string MangerFullName { get { return FirstName + " " + LastName; } }
public string EntrpriseName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// public string MyDetail { get; set; }
public string Image { get; set; }
public string Phone { get; set; }
public string Mail { get; set; }
public string Adress { get; set; }
public string CIN { get; set; } and product
public class Product
{
[Key]
public int ProductId { get; set; }
public string Code { get; set; }
public string Designation { get; set; }
public int Quantite { get; set; }
public int Order_Qty { get; set; }
public double Price { get; set; }
public string Type { get; set; }}

Build errors after Visual Studio for Mac update

$
0
0

After upgrading to the latest version of VS Community for Mac, my project no longer compiled. Also, I uninstalled and installed VS 2019, which also doesn't work. I get the following build error:

The primary reference "Plugin.Fingerprint" could not be resolved because it was built against the ".NETPortable,Version=v5.0" framework. This is a higher version than the currently targeted framework ".NETPortable,Version=v4.5,Profile=Profile111".

I noticed many people got this error from this same library in the past but none of the solutions worked for me. The Target Framework for my project was set to .NET Portable (PCL 4.5 Profile111).

When I changed the Target Framework to .NET Standard, I got many more errors like:

Package XLabs.Platform 2.0.5782 is not compatible with netstandard1.5 (.NETStandard,Version=v1.5). Package XLabs.Platform 2.0.5782 supports:
- monoandroid (MonoAndroid,Version=v0.0)
- portable-net45+win8+wp8 (.NETPortable,Version=v0.0,Profile=Profile78)
- portable-net45+win8+wp8+wpa81 (.NETPortable,Version=v0.0,Profile=Profile259)
- wp8 (WindowsPhone,Version=v8.0)
- wpa81 (WindowsPhoneApp,Version=v8.1)
- xamarinios10 (Xamarin.iOS,Version=v1.0)

Needless to say, I'm open to many suggestions. I've tried to go back to a previous version of VS for Mac but can't find them. Also, TIme Machine wasn't enabled so I can't rollback the machine. As you can see from the error, switching from .NET Portable to .NET Standard caused even more errors. I've also tried deleting bin/obj/package folders, clean, rebuild etc. None of that has worked.

Any suggestions would be greatly appreciated.

HotReload LiveReload LiveXaml [Mac] [Windows] [nuget package] [opensource]

Is there a way to trigger Flyout in Shell by own button?

$
0
0

Can I do something like below:

var btn = new Button();
btn.Clicked += async delegate
{
ShowFlyout();
}

Thanks for any Suggestion

Is there a way to override a Back button press on Android?

$
0
0

I'm having issues with a ContentPage in my app. It consists of a WebView that fills the screen. There are links that users can click to be taken to different pages within the webview (these are all external URLs). But if you press the Back button on Android, the app navigates away from the web view page COMPLETELY, taking you back to the previous ContentPage (which unfortunately is almost always the login page, causing people to have to log back-in).

Is there a way to handle the Back button press and provide my own functionality? Ideally I'd like to first attempt to navigate back through the WebView's history (WebView has a GoBack() method), navigating to a different ContentPage ONLY if we're already at the beginning of the history.

This is possible with a "regular" Xamarin app (you can override an Activity's OnBackPressed() method), how can I handle it with Xamarin.Forms?


Center item in RelativeLayout

$
0
0

Hi guys,

I have faced with another issue ...
It is difficult to find how to center image or another item inside RelativeLayout ?!

I have found something like this solution:

<ffimageloadingsvg:SvgCachedImage
                    RelativeLayout.WidthConstraint="{ConstraintExpression 
                        Type=RelativeToParent,
                        Property=Width,
                        Factor=0.5,
                        Constant=0}"
                    RelativeLayout.HeightConstraint="{ConstraintExpression 
                        Type=RelativeToParent,
                        Property=Height,
                        Factor=0.5,
                        Constant=0}"
                    RelativeLayout.XConstraint="{ConstraintExpression 
                        Type=RelativeToParent,
                        Property=Width,
                        Factor=0.25,
                        Constant=0}"
                    RelativeLayout.YConstraint="{ConstraintExpression 
                        Type=RelativeToParent,
                        Property=Height,
                        Factor=0.25,
                        Constant=0}"
                    WidthRequest="50"
                    HeightRequest="50"
                    Source="resource://image.svg"/>

Is there better solution ?

How does one Programmatically determine the Screen Inch size of a device?

$
0
0

How does one Programmatically determine the Screen Inch size of a device i.e. 5", 5.7", etc.?

Done callback from WebView

$
0
0

Hi all,
in my XF application I have the possibility to open a web page.

For do this, I use the Xamarin.Essential: await Browser.OpenAsync(url, opts);.

I need to have a callback when the user tap on Done button (on iOS) or the back button (on Andorid).

How can I do this?

There is another way other than use Xamarin.Essential?

Thank you! :smile:

Xamarin Forms Android Fixed Notification

$
0
0

Hi all,

I want fixed notification xamarin forms on android. I mean like music app or love counter app notifications unremovable and updateable.

Also the notification package should be able to do them. Even if Android restarts, it should not be affected. The application should notify even if it is closed.

Is this possible?

Thanks in advance

Firebase push notifications with xamarin forms

$
0
0

I've added a project and an application on firebase which is linked to my testing application I created with Xamarin Forms. I downloaded the json file and placed it in my application and set the build action to "GoogleServicesJson". Also, I installed the "Plugin.FirebasePushNotification" package to my project. This is my code in my Xamarin Forms project:

AndroidMainfest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.TestingNotification">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="27" />
  <uses-permission android:name="android.permission.INTERNET" />
    <application android:label="TestingNotification.Android">
      <receiver
       android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver"
       android:exported="false" />
      <receiver
          android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
          android:exported="true"
          android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
          <action android:name="com.google.android.c2dm.intent.RECEIVE" />
          <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
          <category android:name="${applicationId}" />
        </intent-filter>
      </receiver>
    </application>
</manifest>

MainActivity:

protected override void OnCreate(Bundle savedInstanceState)

    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

    base.OnCreate(savedInstanceState);
    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
    LoadApplication(new App());

    FirebasePushNotificationManager.ProcessIntent(this, Intent);
    FirebasePushNotificationManager.Initialize(this, true);

    // FirebasePushNotificationManager.Initialize(this,false);
    if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
    {
        //Change for your default notification channel id here
        FirebasePushNotificationManager.DefaultNotificationChannelId = "quayo-project";

        //Change for your default notification channel name here
        FirebasePushNotificationManager.DefaultNotificationChannelName = "Quayo-Project";
    }
    //If debug you should reset the token each time.
    //Handle notification when app is closed here
    CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
    {
        Toast.MakeText(this, "ok", ToastLength.Long);
    };

}

And the json file:

{
  "project_info": {
    "project_number": "358226749019",
    "firebase_url": "https://quayo-project.firebaseio.com",
    "project_id": "quayo-project",
    "storage_bucket": "quayo-project.appspot.com"
  },
  "client": [
    {
      "client_info": {
        "mobilesdk_app_id": "1:358226749019:android:54b60a3809576332",
        "android_client_info": {
          "package_name": "com.companyname.TestingNotification"
        }
      },
      "oauth_client": [
        {
          "client_id": "358226749019-bgbp51sguavj4m10ahooqv537h5fgppd.apps.googleusercontent.com",
          "client_type": 3
        }
      ],
      "api_key": [
        {
          "current_key": "AIzaSyBsR2Ixk_psObHy-Zjde8GzYbSv_Z_6Bxg"
        }
      ],
      "services": {
        "appinvite_service": {
          "other_platform_oauth_client": [
            {
              "client_id": "358226749019-bgbp51sguavj4m10ahooqv537h5fgppd.apps.googleusercontent.com",
              "client_type": 3
            }
          ]
        }
      }
    }
  ],
  "configuration_version": "1"
}

But I still can't receive any notifications when I try A/B test or cloud messaging with firebase and when I run the app no user is added to the firebase app. So what am I missing here? can someone help? Thanks in advance

How to access path of image

$
0
0
Hi xamarin forum,
How can I get the path of my picture inside my mobile device using xamarin.form

Prompt user to change battery optimization settings - Android

$
0
0

Hi,
I am looking for some solution for disabling battery optimization setting for my application.
When user install app first time and Battery optimization is enable, App should prompt custom popup (Popup text based on user language), and after clicking on button, It should navigate to setting page, there user can disable battery optimization.
Same setting app should save, And should not ask again and again.


How to improve performance of consuming a rest web services in xamarin form?

$
0
0

Hi need some help. I'm using refit api for consuming rest service but the problem is that performance is too slow, Ho can i improve performance in xamarin form.

App login credentials for Google Play monkey test

$
0
0

I'm using Xamarin Forms 4 (newest as of today).

Upon uploading an artifact to Google Play, it automatically runs a "monkey" test on the artifact. If one provides "Login information", the monkey can also login and make some more test. The automated test can also extended with a Robo-script or even a setup of Firebase, but that is not relevant for me right now. What would be wonderfull, would be to provide the login information. My problem is, that I cannot find a way to provide the ressourcenames of the following elements:

  1. Username field
  2. Password field
  3. Login button

Because I have some minor usability warnings, I could actually see the id (I think?) of the Username field, and the Password field (Google Play displays this information together with the warning explanation)

Username: android:id​/content​/RelativeLayout[0]​/PlatformRenderer[0]​/NavigationPageRenderer[0]​/PageContainer[0]​/PageRenderer[0]​/WhiteLineEntryRenderer[6]​/FormsEditText[0]

Password: android:id​/content​/RelativeLayout[0]​/PlatformRenderer[0]​/NavigationPageRenderer[0]​/PageContainer[0]​/PageRenderer[0]​/WhiteLineEntryRenderer[8]​/FormsEditText[0]

However, these are far to long to be entered in the login information (the HTML-field seems to have a maxlenght shorter then this).

I've tried setting the "AutomationId" on the element (Entry and Button) in Xamarin.Forms, but does not seem to help?

Have anyone found a way to do this?

Cannot Connect to sql

$
0
0

Hi Xamarin forum,

Can somebody help because I got SNI_ERROR_35 when connecting to sql actually the debbuger stops at this line
SqlCommand selectTbl = new SqlCommand("SELECT * FROM tablename WHERE Username='"+user.Username+"'AND Password='"+user.Password+"'", databaseConnect.connectDB());

and the console keeps saying Thread finish #1 #2 and so on

Coordinates from string to double or float

$
0
0

Hi everyone!

I'm working with an API-Rest that generates me a JSON with a polygon (every coordinates of that polygon, shape).

Well, I deserialize it in classes, but the coordinates deserialize in string (I mean, x and y coordinates as string) so I can't use it, because I need to put each point with lat and with long.

How can I deserialize it in a double or float to use my coordinates?

That is the JSON: shape\":[\"52.5139618,13.3210087\",\"52.5139618,13.3222961\",\"52.5141335,13.3228111\",\"52.5144768,13.3231544\",\"52.5146484,13.3236694\",\"52.5146484,13.3243561\",\"52.5144768,13.3248711\",\"52.5141335,13.3252144\",

And that is my class:

public class Component
{
public int id { get; set; }
public string[] shape { get; set; }
}

Thank you in advance

Layout not updating in Android as expected

$
0
0

I dynamically configure a UI and for some reason in Andriod the views don't update as expected. When the device is rotated on Andriod the PageScrollView resizes but the child view zoomable doesn't (See screenshot). It works perfectly well on IOS. I have tried calling InvalidateMeasure on PageScrollView and that doesnt help.

foreach (var formPage in currentForm.pages)
                    {

                    var layout = new FormRelativeLayoutPage();
                    layout.HorizontalOptions = LayoutOptions.FillAndExpand;
                    layout.VerticalOptions = LayoutOptions.FillAndExpand;

                    layout.BackgroundColor = Color.Blue;

                    OptimisedImage image =null;

                        if (formPage.image != null)
                        {

                        var img = new MemoryStream(formPage.image);

                        var ImageStream = new MemoryStream();
                        img.CopyTo(ImageStream);
                        img.Dispose();

                        var byteArray = ImageStream.ToArray();

                        var imageSource = ImageSource.FromStream(() => new MemoryStream(byteArray));


                            image = new OptimisedImage
                            {
                                Aspect = Aspect.Fill,
                                Source = imageSource

                            };

                        layout.Children.Add(image,
        Constraint.Constant(0),
        Constraint.Constant(0),
        Constraint.RelativeToParent((parent) => { return parent.Width; }),
        Constraint.RelativeToParent((parent) => { return parent.Height; }));

                    }



                    addControls(layout,image, formPage);

                    var zoomable = new ContentView()//new PinchToZoomContainer()
                    {
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        VerticalOptions = LayoutOptions.FillAndExpand,
                        BackgroundColor = Color.Green,
                        //Content = layout
                    };

                    PageScrollView sv = new PageScrollView(currentForm)
                    {
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        VerticalOptions = LayoutOptions.FillAndExpand,
                        BackgroundColor = Color.Yellow,
                        Content = zoomable,
                        PageNo = formPage.pageNo
                };





                    pages.Add(sv);


                }

                CarouselViewControl cv = new CarouselViewControl
                {
                    ItemsSource = pages//, ItemTemplate = GetDataTemplate()
                    ,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    Orientation= CarouselViewOrientation.Horizontal

                };

                cv.ShowArrows = true;
                cv.ShowIndicators = true;
                cv.Scrolled += Cv_Scrolled;

                Content = cv

;

Viewing all 91519 articles
Browse latest View live


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