问题描述
所以我对我的 API 进行 POST 调用以获取多个对象,然后将这些对象添加到列表中并显示在 RecyclerView 中。问题是,在获得 var 结果 后,它会跳过该方法中剩余的全部代码并执行下一个方法 SetupRecyclerView。 catch 不会捕获任何异常。这段代码有什么问题?
async void GetPostList()
{
try
{
string url = "linkToMyWebService";
var uri = new Uri(url);
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,RequestUri = uri
};
httpclienthandler clientHandler = new httpclienthandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender,cert,chain,sslPolicyErrors) => { return true; };
HttpClient client = new HttpClient(clientHandler);
var result = await client.SendAsync(request);
var contentBody = await result.Content.ReadAsstringAsync();
List<postRetrieved> posts = JsonConvert.DeserializeObject<List<postRetrieved>>(contentBody);
foreach (var post in posts)
{
postModel newPost = new postModel();
newPost.username = post.fullName;
newPost.description = post.postTitle;
newPost.city = post.postCity;
postList.Add(newPost);
}
}
catch
{
}
}
void SetupRecyclerView()
{
postRecyclerView.SetLayoutManager(new Android.Support.V7.Widget.linearlayoutmanager(postRecyclerView.Context));
postAdapter = new PostAdapter(MainScreenPosts);
postRecyclerView.SetAdapter(postAdapter);
}
解决方法
可能是关于 Catch。正在返回一些错误,并且一个空的 catch 会导致该方法被跳过。 您可以在“异常设置”中启用“公共语言运行时异常”或在捕获中记录错误。这将帮助您获得有关代码中出现问题的更多详细信息。
,好吧,问题在于 GetPostList 是异步的。在等待获取对象列表的请求时,它开始执行需要这些对象运行的方法 SetupRecyclerView。我已经把它放在我的 trycatch 的 finally{} 块中,现在它工作正常。