2014-03-26 52 views
-1

我無法添加到observablecollection列表。變量被檢索並且也存儲在類實例中,但是我無法將該實例添加到列表中。我收到一個空引用異常...請幫我解決

在該行發現空引用異常: await meth(); 在LoadedData方法

using Newtonsoft.Json; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net.Http; 
using System.Text; 
using System.Threading.Tasks; 
using News_Specific.Resources; 
using System.ComponentModel; 

using System.Collections.ObjectModel; 
//using System.ComponentModel; 
//using News_Specific.Resources; 
namespace News_Specific.ViewModels 
{ 
public class Search 
{ 
    IndRes singleres = new IndRes(); 
    IndResGrp singleresgrp = new IndResGrp(); 
    //ObservableCollection<List<IndRes>> lst = new ObservableCollection<List<IndRes>>(); 
    //public Result res; 
    public IndRes getresultitems{ get; set; } 

    public bool IsDataLoaded { get; set; } 

    public async void LoadData() 
    { 
     await meth(); 
    } 


    public async Task<List<IndRes>> meth() 
    { 


     HttpClient client = new HttpClient(); 
     string key = "s8w8MsPnqPUpcBHCn6ok0evbZGI_"; 
     string topic = "windows"; 
     string baseUrl = "http://www.faroo.com/api?" + 
         "q={0}" + 
         "&start=1" + 
         "&key={1}" + 
         "&length=2" + 
         "&l=en" + 
         "&src=news" + 
         "&f=json"; 
     string url = string.Format(baseUrl, 
            topic, 
            key); 

     string result = await client.GetStringAsync(url); 



     RootObject obj = JsonConvert.DeserializeObject<RootObject>(result); 
     if (obj.results != null) 
     { 
      foreach (Result res in obj.results) 
      { 
       singleres.title = res.title; 
       singleres.kwic = res.kwic; 
       singleresgrp.Items.Add(singleres); 

      } 

     } 
     this.IsDataLoaded = true; 
     return singleresgrp.Items; 

    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    private void NotifyPropertyChanged(String propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (null != handler) 
     { 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 


} 




} 
+0

嘿,他只是一個初學者只是試圖幫助他,當他得到解決他的答案,然後我想用戶刪除自己的問題。 – loop

回答

0

你必須將數據添加到it.for在您的甲基()方法做到這一點之前初始化你ingleresgrp.Items集合。

singleresgrp.Items= new List<IndRes>();

您可以在您試圖將項目添加到您的收藏ingleresgrp.Items,那麼你會發現它出來是空因此exception.so只是初始化它的行添加破發點。

相關問題