Frage

I am trying to create a simple note-taking application for my own use. The idea is to learn C#/Mono XML editing.

I can't find a NullReference that the compiler is complaining about. No idea why. I can't see it. After few days of searching I give up... help. :)

Here is the code that is making a bug. The application runs fine until I press a button to Add new note. It just crashes. The add_activated function runs when a button is pressed and it should use AddNote function.

The code is incomplete and it certainly has some logic bugs. But I can handle those. I'm just wondering why it won't run.

MainActivity.cs:

// (...)
protected void add_activated (object sender, System.EventArgs e)
    {
        Gtk.TextBuffer buffer;          
        buffer = textview1.Buffer;

        Note note = new Note(entry3.Text, buffer.Text);     

        AddNote (note);
    }


    public static void AddNote (Note note)
    {
        string xmlFile = "/home/tomasz/.keeper/keeper.xml";

        XmlDocument xmlDoc = new XmlDocument ();
        xmlDoc.Load (xmlFile);
        XmlNode xmlRoot = xmlDoc.CreateElement("keeper");

        if (!xmlDoc.DocumentElement.Name.Equals("keeper") )
        {       
            xmlDoc.AppendChild (xmlRoot);
        }

        XmlNode xmlNote = xmlDoc.CreateElement ("note");
        XmlNode xmlTitle = xmlDoc.CreateElement ("title");
        XmlNode xmlText = xmlDoc.CreateElement ("text");

        xmlRoot.InsertAfter (xmlRoot.LastChild, xmlNote);
        xmlTitle.InnerText = note.Title;
        xmlNote.InsertAfter (xmlNote.LastChild, xmlTitle);
        xmlText.InnerText = note.Text;
        xmlNote.InsertAfter (xmlNote.LastChild, xmlText);

        xmlDoc.Save (xmlFile);
    }


    protected void remove_activated (object sender, System.EventArgs e)
    {
        throw new System.NotImplementedException ();
    }
    }
}

Note.cs:

using System;

namespace Keeper
{
public class Note
{   
    private string title;
    private string text;

    public string Title {
        get 
        {
            return this.title;
        }
        set 
        {
            this.title = value;
        }
    }
    public string Text
    {
        get 
        {
            return this.text;
        }
        set 
        {
            this.text = value;
        }
    }

    public Note (string title, string text)
    {
        this.Title = title;
        this.Text = text;
    }
}
}
War es hilfreich?

Lösung

The immediate problem is that you got the arguments to InserAfter mixed up. First one should be the node to insert and the second one should be the reference node. The root element has no children yet, so LastChild is going to be null and hence the exeption. Using null as a reference point is valid, but not as a node to add.

There are other issues but you said you are able to fix those, so there you go.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top