和这里的许多其他人一样,我是C#和Xamarin的新手,但不是一般的编程人员。
我正在做一个模型概念的证明,在那里我可以查询股票/密码价格数据,并用这些数据更新Xamarin中的元素。
我有一个名为LoadData()的API方法,它可以在应用程序启动时正常工作。它使用文本属性中的数据更新一些Xamarin标签项。
我有一个Xamarin Button对象,它有一个Click事件,该事件触发相同的LoadData()方法,尝试加载新的JSON数据,然后用新数据更新标签。
任何后续的LoadData()调用在第一次被调用后都将不起作用。我认为发生的情况是它调用的原始数据被缓存,并且调用不会返回全新的、新的数据。
我花了两天时间研究C#中的缓存,试图找到正确的代码语法,以便在每次调用LoadData()之前清除JSON数据,或者防止它缓存。我发现了相当多的对话和代码示例,但当我尝试它们时,它们要么不起作用,要么在Visual Studio中显示为红色下划线并生成错误。
我将进行大量这样的API调用,所以我正在寻找正确的语法来解决这个问题。任何对清晰的代码示例的帮助都是非常感谢的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xamarin.Forms;
namespace DataBindingTest2
{
[System.ComponentModel.DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
static string IEXTrading_API_PATH = "https://cloud.iexapis.com/v1/crypto/btcusdt/quote/1?token=TOKEN_GOES_HERE";
static List<string> FinalPriceQuote = new List<string>(); // The LIST object to hold the final JSON data
public string vLatestPrice = "";
public string vCompanyName = "";
public string vLatestVolume = "";
public MainPage()
{
InitializeComponent();
LoadData();
}
void Handle_Clicked(object sender, System.EventArgs e)
{
LoadData();
}
public async void LoadData()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); // <-- doesn't seem to have any effect
using (HttpResponseMessage response = await client.GetAsync(IEXTrading_API_PATH))
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
RootObject priceData = JsonConvert.DeserializeObject<RootObject>(data);
FinalPriceQuote.Add(priceData.symbol.ToString());
FinalPriceQuote.Add(priceData.latestPrice.ToString());
FinalPriceQuote.Add(priceData.latestVolume.ToString());
vCompanyName = FinalPriceQuote[0];
vLatestPrice = FinalPriceQuote[1];
vLatestVolume = FinalPriceQuote[2];
CompanyName.Text = vCompanyName; // <-- updates Label text in XAML
PriceLabel.Text = vLatestPrice; // <-- updates Label text in XAML
LatestVolume.Text = vLatestVolume; // <-- updates Label text in XAML
}
}
}
}
}
发布于 2019-07-12 00:39:31
看起来你总是附加到FinalPriceQuote
并读取前3个值,但从来没有清除它。尝试在FinalPriceQuote.Add(...)
之前添加FinalPriceQuote.Clear()
https://stackoverflow.com/questions/56998874
复制相似问题