Android:从DefaultHandler类传递数据到Activity?[英] Android: passing data from DefaultHandler class to Activity?

本文是小编为大家收集整理的关于Android:从DefaultHandler类传递数据到Activity?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在使用一个Android应用程序,我将使用萨克斯很多.我想知道将"数据"或从我的处理程序发送回到我的活动的最佳方式是什么?

imo在我的处理程序中调用意图或创建吐司等,它有点乱,我希望从我的活动中完成这些东西,具体取决于我的处理程序内发生的事情.

你们想什么?我该如何以干净的方式执行此操作?

这是一个代码示例:

        public void startElement(String n, String l, String q, Attributes a) throws SAXException{
            if(l == "login") in_loginTag = true;

            if(l == "error") {

                    if(Integer.parseInt(a.getValue("value")) == 1)
                        Toast.makeText(getApplicationContext(), "Couldn't connect to Database", Toast.LENGTH_SHORT).show();
                    if(Integer.parseInt(a.getValue("value")) == 2)
                        Toast.makeText(getApplicationContext(), "Error in Database: Table missing", Toast.LENGTH_SHORT).show();
                    if(Integer.parseInt(a.getValue("value")) == 3)
                        Toast.makeText(getApplicationContext(), "Invalid username and/or password", Toast.LENGTH_SHORT).show();

                error_occured = true;

            }

我希望从我的处理程序课上显示这些吐司.

推荐答案

我在我当前的应用程序中完成了相当多的XML解析,这是这个例子帮助了很多.

设计明智我相信您应该使用自定义sax处理程序而不是敬酒或意图的广播等,这将在开头XML元素处实例化解析对象.此对象是您XML项的表示.所以也许物体将是汽车,并且有一个门,颜色,轮子的设定器/吸气剂.当您解析SAX解析器中的数据时,您将设置这些值.当SAX Parser完成解析时,您将调用您的解析器将其传递给您的活动,该活动与来自XML的所有汽车都充满.在我的情况下,我实际上填充了我的对象的列表/数组.该示例仅处理一组数据.无论如何,链接解释了这一切.

编辑:只是在查看我的代码,实际上我在我的处理程序中做了什么,构建了一系列ParsedData设置对象,该对象通过getParsedData()完成了解析后返回到活动.以下是一些重要的代码:

xml处理程序:

private boolean in_IdSite;
private boolean in_SiteName;

private ArrayList<ParsedChannelDataSet> list = new ArrayList<ParsedChannelDataSet>();

public ArrayList<ParsedChannelDataSet> getParsedData() {
    return this.list;
}

@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    // first tag parsed so add a new ParsedEventDataSet object
    if(localName.equals("stmSiteUser")) {
        list.add(new ParsedChannelDataSet());
    } else if (localName.equals("idSite")) {
        this.in_IdSite = true;
    } else if (localName.equals("siteName")) {
        this.in_SiteName = true;    
    }
}

@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    if (localName.equals("idSite")) {
        this.in_IdSite = false;
    } else if (localName.equals("siteName")) {
        this.in_SiteName = false;
    }
}

@Override
public void characters(char ch[], int start, int length) {
    // determine if any tag is current, get data from tag and populate into ParsedEventDataSet
    if (this.in_IdSite) {
        this.list.get(this.list.size()-1).setExtractedIdSite(new String(ch, start, length));
    } else if (this.in_SiteName) {
        this.list.get(this.list.size()-1).setExtractedSiteName(new String(ch, start, length));
    }
}

这是我的sample parseddatasampleset(这可以被称为无论您想要的东西)显然,您想要替换SiteName和Idsite的其他内容.这些只是我的XML元素

public class ParsedChannelDataSet {
    private String extractedIdSite = null;
    private String extractedSiteName = null;


    public String getExtractedIdSite() {
        return extractedIdSite;
    }

    public void setExtractedIdSite(String _extractedIdSite) {
        this.extractedIdSite = _extractedIdSite;
    }   

    public String getExtractedSiteName() {
        return extractedSiteName;
    }

    public void setExtractedSiteName(String _extractedSiteName) {
        Log.d("", _extractedSiteName);
        this.extractedSiteName = _extractedSiteName;
    }       


    public String toString() {
        /* TODO */
        return "todo";
    }
}

所以你可以看到我构建一系列ParsedChanneldataset对象,这些对象被传递回活动.这是一个比使用吐司或广播更好的解决方案,因为它是一个更脱钩的解决方案

编辑2:本网站的第2页上的第一篇文章我链接了关于解析多个XML元素的提升.请参阅这里(解析多个XML元素).

我希望这有助于你

其他推荐答案

你可以:

  1. 将活动传递到XML中 处理程序,将其存放为实例 变量,并回复它 需要.

  2. 在活动中创建静态成员并将活动分配给 它在创建时.然后从您的XML处理程序中,您可以引用ActivityClass.getMyactivity()[例如]并调用一些方法来弹出吐司.

iOS/Mac OS X有一个名为"通知"的概念,其中任何代码都可以在某些事件中注册兴趣.如果有一个Android等价物,那就做到这一点,我是另一种方式,我e. XML处理程序可以广播某种故障事件/通知,并且活动可以侦听它并流行吐司.

其他推荐答案

我会使用自定义 Handler 我在我的活动中创建并将其传递给XML解析器.然后在这个解析器中我可以调用一些 sendMessage 在自定义处理程序上.

处理程序这里

本文地址:https://www.itbaoku.cn/post/102712.html

问题描述

I'm working on an android application where I'll be using the SAX quite a lot. I was wondering what would be the best way to send 'data' or results from my handler back to my activity?

IMO it's kind of messy to call intents or create toasts etc within my handler, and I'd prefere to do those kind of things from my activity, depending on what happens within my handler.

What do you guys think? How should I do this in a clean way?

Here's a code example:

        public void startElement(String n, String l, String q, Attributes a) throws SAXException{
            if(l == "login") in_loginTag = true;

            if(l == "error") {

                    if(Integer.parseInt(a.getValue("value")) == 1)
                        Toast.makeText(getApplicationContext(), "Couldn't connect to Database", Toast.LENGTH_SHORT).show();
                    if(Integer.parseInt(a.getValue("value")) == 2)
                        Toast.makeText(getApplicationContext(), "Error in Database: Table missing", Toast.LENGTH_SHORT).show();
                    if(Integer.parseInt(a.getValue("value")) == 3)
                        Toast.makeText(getApplicationContext(), "Invalid username and/or password", Toast.LENGTH_SHORT).show();

                error_occured = true;

            }

I'd prefere not showing these Toasts from my handler class.

推荐答案

I've done quite a bit of XML parsing in my current app and this is this example helped a lot .

Design wise i believe instead of toasts or intent broadcasting etc you should be using a custom SAX Handler which will instantiate a Parse object at the beginning XML element. This object is a representation of your XML items. So maybe the object will be Car and have a setter/getter for Door, Colour, Wheels. As your parsing the data in the SAX parser you will set those values. when the SAX parser finishes parsing you call your parser to have it pass back the object to your activity which is full with all cars from your XML. In my case i actually populate a list/array of my objects which are passed back. The example only deals with one set of data. Anyway that link explains it all.

Edit: Was just looking at my code, actually what I do in my handler is build an array of my ParsedData set objects which are passed back to the activity after parsing is complete via getParsedData(). Here is some of the important code:

XML handler:

private boolean in_IdSite;
private boolean in_SiteName;

private ArrayList<ParsedChannelDataSet> list = new ArrayList<ParsedChannelDataSet>();

public ArrayList<ParsedChannelDataSet> getParsedData() {
    return this.list;
}

@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    // first tag parsed so add a new ParsedEventDataSet object
    if(localName.equals("stmSiteUser")) {
        list.add(new ParsedChannelDataSet());
    } else if (localName.equals("idSite")) {
        this.in_IdSite = true;
    } else if (localName.equals("siteName")) {
        this.in_SiteName = true;    
    }
}

@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    if (localName.equals("idSite")) {
        this.in_IdSite = false;
    } else if (localName.equals("siteName")) {
        this.in_SiteName = false;
    }
}

@Override
public void characters(char ch[], int start, int length) {
    // determine if any tag is current, get data from tag and populate into ParsedEventDataSet
    if (this.in_IdSite) {
        this.list.get(this.list.size()-1).setExtractedIdSite(new String(ch, start, length));
    } else if (this.in_SiteName) {
        this.list.get(this.list.size()-1).setExtractedSiteName(new String(ch, start, length));
    }
}

Here is my sample ParsedDataSampleSet (this can be called whatever you want) obviously you want to replace siteName and idSite with something else too. These are just my XML elements

public class ParsedChannelDataSet {
    private String extractedIdSite = null;
    private String extractedSiteName = null;


    public String getExtractedIdSite() {
        return extractedIdSite;
    }

    public void setExtractedIdSite(String _extractedIdSite) {
        this.extractedIdSite = _extractedIdSite;
    }   

    public String getExtractedSiteName() {
        return extractedSiteName;
    }

    public void setExtractedSiteName(String _extractedSiteName) {
        Log.d("", _extractedSiteName);
        this.extractedSiteName = _extractedSiteName;
    }       


    public String toString() {
        /* TODO */
        return "todo";
    }
}

So you can see I build an array of ParsedChannelDataSet objects which are passed back to the activity. this is a far better solution than using toast or broadcasts because its a more decoupled solution

Edit 2: The first post on this 2nd page of the site I linked mentions about parsing multiple XML elements like mine. See here (parse multiple xml elements).

I hope this helps you out

其他推荐答案

You could:

  1. Pass the activity into the XML handler, store it as an instance variable, and call back to it as needed.

  2. Create a static member in your activity and assign the activity to it when it's created. Then from your XML handler, you could reference ActivityClass.getMyActivity() [for example] and call some method to pop toast.

iOS/Mac OS X has a concept called "notifications" where any code can register an interest in some event. If there's an Android equivalent, that'd be another way to do this, i. e. the XML handler could broadcast some sort of failure event/notification and the Activity could listen for it and pop toast.

其他推荐答案

I would use a custom Handler which I created in my activity and passing it to the XML parser. Then within this parser I could call some sendMessage on the custom Handler.

An example usage of Handler here.