线程已启动<thread pool =“”>:当我从api获取数据时

时间:2015-07-31 09:33:34

标签: c# multithreading listview xamarin xamarin.forms

我想从api获取数据并将其放入组列表视图,但应用程序不显示错误而不显示数据。对不起我的英语不好

这是我下载数​​据的功能:

    List<String> usernames = accessClass.setUsernames();
    List<String> passwords = accessClass.setPasswords();
    System.out.print("Please enter your username: ");
    user1 = wordScan.next();

    int i=0;
    while(i<3)
    {
        if(usernames.contains(user1)){

        System.out.print("Now enter your password: ");

        pass1=wordScan.next();

        if(passwords.contains(pass1)){

            System.out.println("Logged in.");
            System.out.println("Your username is "+user1);

            random.setSeed(System.currentTimeMillis());
            numGen = random.nextInt(899999)+100000;

            System.out.println("Your access code is: "+numGen);
            break;
            }
        }else{

            if(i==2) {
             System.out.println("Invalid Username... Terminating.");
             System.exit(0);
             }

             else {
             System.out.println("Invalid Username... Try Again.");
             i++;
             }  
        }
    }
    wordScan.close();
}

和要在布局中显示的代码

public async Task<List<GroupInvoiceInList>> test_connection()
    {
        var listItems = new List<GroupInvoiceInList> ();
        using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add ("token","40df006e4c4314aefd892e335a743338c8d3331e");

                var response = await client.GetAsync(SuperVAR.URL_CUSTOMER_GET_LISTINVOICE+"?limit=15");
                if (response.IsSuccessStatusCode)
                {
                    JObject res = JObject.Parse (response.Content.ReadAsStringAsync ().Result);
                    string message = res ["message"].ToString ();
                    if (message.Equals ("Success")) {
                        JArray arrayData = (JArray)res["data"]["invoiceList"];
                        GroupInvoiceInList g1 = new GroupInvoiceInList (1437880499);
                        for (int i = 0; i < arrayData.Count; i++) {
                            var item = (JObject)arrayData [i];

                            InvoiceInList hihi = new InvoiceInList (Int32.Parse(item["invoiceStatus"].ToString()));
                            hihi.invoiceId = Int32.Parse(item["invoiceId"].ToString());
                            hihi.invoiceProductName = item["productName"].ToString();
                            hihi.contactPhone = item["receiverPhone"].ToString();
                            hihi.invoiceReceiverName = item["receiverName"].ToString();
                            hihi.invoiceReceiverAddress = item["receiverFullAddress"].ToString();
                            hihi.invoiceCodFee = Double.Parse(item["codFee"].ToString());
                            hihi.invoiceSumFee = Double.Parse(item["sumFee"].ToString());
                            g1.Add (hihi);

                            Debug.WriteLine(hihi.invoiceId+"");
                        }
                        listItems.Add (g1);

                    } else {
                        //DisplayAlert ("", message, "OK");
                    }
                }
            }
        return listItems;
    }

的DataModel: 的 GroupInvoiceInList

var listItems = test_connection ().Result;
listView = new ListView 
    {
        SeparatorVisibility = SeparatorVisibility.None,
        HasUnevenRows = true,
        ItemTemplate = new DataTemplate(typeof(InvoiceInListCell)),
        IsGroupingEnabled = true,
        GroupHeaderTemplate = new DataTemplate(typeof(GroupInvoiceInListCell)),
        ItemsSource = listItems
    };
this.Content = new StackLayout
    {
        Children = {listView  },
        BackgroundColor = Color.White,
    };

InvoiceInList

public class GroupInvoiceInList : ObservableCollection<InvoiceInList>
    {
        public int dayOfMonth { get; set;}
        public string dayOfWeek { get; set; }
        public string monthAndYear { get; set;}

        public GroupInvoiceInList (long time)
            {
                DateTime timeA = SuperFUNC.FromUnixTime(time);
                this.dayOfMonth = timeA.Day;
                this.dayOfWeek = SuperFUNC.ConvertToDayOfWeek ((int)timeA.DayOfWeek);
                this.monthAndYear = SuperFUNC.ConvertToMonthOfYear ((int)timeA.Month) + " " + timeA.Year;
            }
    }

申请表输出:

public class InvoiceInList
    {
        public int invoiceId{ set; get;}
        public string invoiceStatus{ set; get;}
        public string contactPhone{ set; get;}
        public string invoiceProductName { set; get;}
        public string invoiceReceiverName { set; get;}
        public string invoiceReceiverAddress { set; get;}
        public double invoiceCodFee{ set; get;}
        public double invoiceSumFee{ set; get;}
        public long invoiceCreateDate{ set; get;}
        public Color backGroundTop { set; get;} 

        public InvoiceInList (int invoiceStatus)
            {
                this.invoiceStatus = SuperFUNC.ConvertStatusToString (invoiceStatus);
                this.backGroundTop = SuperFUNC.ConvertStatusToColor (invoiceStatus);
            }
    }

我是c#和xamarin的新手,感谢阅读

1 个答案:

答案 0 :(得分:0)

我认为在与UI交互相同的线程上运行json连接可能会出现问题,因此无需等待列表视图在返回数据之前更新。

我在代码中使用了单一职责,并使用事件处理程序来检测数据集何时更改为重新绑定listview上的数据。我的例子是XMl,但概念是一样的。

对Listview数据绑定的引用:

http://developer.xamarin.com/guides/cross-platform/xamarin-forms/introduction-to-xamarin-forms/#Customizing_the_Appearance_of_a_Cell

在Page OnAppearing事件

上调用
var response = await DataHelper.GetData();

我的Data Helper类中的HTTP请求

 public static async Task<string> GetData()
        {
    var result = true;
    var url = "API Call URL";

    var content = new Dictionary<string, string>();
    content["needed parameter for API call"] = ID;
    var response = await WebRequestHelper.MakeAsyncRequest(url, content);
                if (response.IsSuccessStatusCode)
                {
    result = response.Content.ReadAsStringAsync().Result;
    result = result.Replace("<xml>", "<ModelResultName>").Replace("</xml>", "</ModelResultName>");
                }
                else
                {
                    result = false;
                    Debug.WriteLine("Failed to get data");
                }
return result;

然后我有一个事件处理程序来检测更改并重新绑定我的Listview数据源

    public event EventHandler<ModelName> ResultUpdated;

    private void ResultUpdated(object sender, GamesResult e)
    {
            Model "In your case InvoiceInList" itemSource = null;
            ListView.ItemsSource = itemSource;        
    }

另请注意,listview ItemTemplate应绑定到模型上的数据模板绑定,例如:

ListView.ItemTemplate = new DataTemplate(typeof(InvoiceInListCell))

Label invoiceProductName = new Label();
invoiceProductName .SetBinding(Label.TextProperty, "productName");