我得到一个空引用异常...请帮我解决

时间:2014-03-26 19:47:48

标签: c# .net json windows-phone-8

我无法添加到observablecollection列表。检索变量并将其存储在类实例中,但我无法将该实例添加到列表

在该行找到无效引用异常: 等待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));
        }
    }


}




}

1 个答案:

答案 0 :(得分:0)

在向数据库添加数据之前,必须初始化ingleresgrp.Items集合。这样就可以在你的meth()方法中执行此操作。

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

您可以在尝试将项添加到ingleresgrp.Items集合的行上添加断点,然后您会发现它出现为null因此异常。所以只是初始化它。