2015-08-28 59 views
0

這是我的代碼。我使用函數來檢索列表,但它沒有發送它。將函數返回給函數

public List<string> country_set() 
{ 
    mCountryUrl = new Uri ("http://xxxxxxx.wwww/restservice/country"); 
    mList = new List<string>(); 
    mCountry = new List<Country>(); 
    WebClient client = new WebClient(); 
    client.DownloadDataAsync (mCountryUrl); 
    client.DownloadDataCompleted += (sender, e) => { 
     RunOnUiThread (() => { 
      string json = Encoding.UTF8.GetString (e.Result); 
      mCountry = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>> (json); 
      Console.WriteLine (mCountry.Count.ToString()); 
      int x = mCountry.Count; 
      for(int i=0; i< x ; i++) 
      { 
       mList.Add(mCountry[i].name); 
      } 
     }); 
    }; 
    return mList; 
} 

它引發異常。 請幫助我

+3

你會得到哪些例外? – Chostakovitch

+3

什麼行引發異常? – bkribbs

+0

除非它是android的設計模式,否則您懷疑您返回的是帶有0個元素的列表,並派發一個線程將項添加到該列表中(這也不是線程安全的)。 – Rob

回答

1

問題是,在調用Web服務器完成之前,您的方法完成後立即返回mList。現在,在您的調用代碼檢查列表以查找它爲空之後,最終將調用服務器並完成您的列表,這已經太晚了!

這將解決這個問題:

 var mCountryUrl = new Uri("http://xxxxxxx.wwww/restservice/country"); 
     var mList = new List<string>(); 
     var mCountry = new List<Country>(); 
     WebClient client = new WebClient(); 
     var data = client.DownloadData(mCountryUrl); 

     string json = Encoding.UTF8.GetString(data); 
     mCountry = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>>(json); 
     Console.WriteLine(mCountry.Count.ToString()); 
     int x = mCountry.Count; 
     for (int i = 0; i < x; i++) 
     { 
      mList.Add(mCountry[i].name); 

     } 

     return mList; 
+0

謝謝你的幫助......它運作良好......我會永遠記住這一點...... – sam

+0

不客氣! – Alireza

+1

這不是異步的,因爲海報的版本是(試圖成爲)。 –

1

這個怎麼樣:

public async Task<List<string>> country_set() 
{ 
    mCountryUrl = new Uri ("http://xxxxxxx.wwww/restservice/country"); 
    mList = new List<string>(); 
    mCountry = new List<Country>(); 
    WebClient client = new WebClient(); 
    byte[] data = await client.DownloadDataTaskAsync(mCountryUrl); 
    string json = Encoding.UTF8.GetString(data); 
    mCountry = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>> (json); 
    Console.WriteLine (mCountry.Count.ToString()); 
    int x = mCountry.Count; 
    for(int i=0; i<x; i++)   
     mList.Add(mCountry[i].name);   

    return mList; 
} 

它使用.NET中的新異步模式。

編輯:代碼是從Android應用程序鍵入。任何出現語法錯誤(或任何其他類型)的人,請在評論中發出信號。

+0

感謝您的回覆......它也在工作.... – sam