简体   繁体   中英

How to check if a link request is valid before it sends it? (Xamarin.Forms)

I am working on a simple test project where if you type into an entry any stock ticker symbol it produces a WebClient and link that returns a string of that stock price.

I know the exact URL that I need to acquire the data from, and if the user inputs an existing ticker symbol it works perfectly fine. However, I have a run-time error if the user makes up a ticker symbol, as the program tries to pull data from a non-existent web page.

On run of the application, it goes directly into break mode and returning the error System.NullReferenceException: 'Object reference not set to an instance of an object.' .

How can I check if the URL is valid before making the request or at least be able to catch the error before putting the application into break mode?

This is the c# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Stock_WatchList
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class sybmolSelector : ContentPage
    {
        public string price { get; set; }
        public sybmolSelector()
        {
            InitializeComponent();

            BindingContext = this;
        }

        private void Entry_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            var nameValue = entry.Text.ToString();
            var link = "https://sandbox.iexapis.com/stable/stock/" + nameValue + "/price?token=Tsk_57bebc1d051340dbaad8656ab0027e90";

            var client1 = new WebClient();
            string b = client1.DownloadString(link);

            price = "$" + b;

            Symbol.Text = nameValue.ToString();
            Price.Text = price;
        }
    }
}

and the Xamarin code:

<?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="Stock_WatchList.sybmolSelector"
             BackgroundColor="Black"
             NavigationPage.IconColor="HotPink">
    <ContentPage.Content>
        <StackLayout>
            <Label TextColor="HotPink" BackgroundColor="Black" Text="------------------- Enter A Symbol Below -------------------" FontSize="19" LineBreakMode="TailTruncation"></Label>
            <Entry PlaceholderColor="HotPink" PropertyChanged="Entry_PropertyChanged" FontSize="19" x:Name="entry" TextColor="HotPink" BackgroundColor="#111111"></Entry>
            <Label x:Name="Symbol" Margin="5" Text="" HorizontalOptions="Start" TextColor="HotPink" FontSize="40"/>
            <Label x:Name="Price" Margin="5,0,5,5" Text="" HorizontalOptions="Start" TextColor="HotPink" FontSize="50"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Don't make a call if Entry.Text is null or empty. When your form gets loaded PropertyChanged will get called. At that moment Text is still null. It certainly doesn't have a default in your markdown.

private void Entry_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    // guard for null
    if (entry == null) return;
    // no need to call the api if we don't have a value
    if (String.IsNullOrEmpty(entry.Text)) return;

    var link = "https://sandbox.iexapis.com/stable/stock/" + entry.Text + "/price?token=sometoken";

    using(var client1 = new WebClient()) // WebClient does implement (useless) IDisposable
    {
         price = "$" + client1.DownloadString(link);
    }

    // maybe these are null as well, who knows
    if (Symbol != null)  Symbol.Text = entry.Text;
    if (Price != null)   Price.Text = price;
}

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