简体   繁体   中英

XAMARIN Android C# How to open browser through application

I am trying to open a webpage through my app. I have tried code from multiple different sources, but ever time I try to run the application it throws a Null Reference Exception at the block of code, whether it is to open a webpage or open the dialer (the code is close to identical for each).

facebook.Click += delegate
{
    var uri = Android.Net.Uri.Parse("http://www.facebook.com");
    var i = new Intent(Intent.ActionView, uri);
    StartActivity(i);
};

Error

0x52 in Project4.SecondScreen.OnCreate at C:\\Users\\jalco\\Documents\\Visual Studio 2015\\Project4\\Project4\\SecondScreen.cs:44,13 C# 0x13 in Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ at /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/platfo‌​rms/android-23/src/generated/Android.App.Activity.cs:2857,4

Based on your ADB it looks like your 'facebook' variable is null, and you can not assign a click event to a null reference, hence the Null Reference Exception.

Make sure to reference the control via the id you assigned to it.

Example:

XML layout

<Button
        android:id="@+id/facbook_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Facebook Link" />

Code Behind (Activity)

Button facebook= FindViewById<Button>(Resource.Id.facbook_btn);
facebook.Click += delegate
{
    var uri = Android.Net.Uri.Parse("http://www.facebook.com");
    var i = new Intent(Intent.ActionView, uri);
    StartActivity(i);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM