【问题标题】:android sax parser shows only first line in TextViewandroid sax 解析器仅在 TextView 中显示第一行
【发布时间】:2012-07-05 22:12:11
【问题描述】:

我正在使用 android 和 java 进行我的第一个项目 而且经验很少。 我有一个收音机播放器(激活服务的开始和停止按钮) 和 xml 文件中的一些数据,例如在 textview 中加载的艺术家标题和专辑 我使用了一个计时器,这样 gui 会随着歌曲的播放而更新

这一切都有效 只有在文本视图中加载歌词时,它才显示 xml 标签的第一行 <LYRIC>

这是我的主要活动:

extends  Activity implements OnClickListener{

     private static final String TAG = "ServicesDemo";
     public String myimageURL;
     private EditText Lyrics;
    private ImageView AlbumPic;
    private Button play,  stop;
    private TextView Artist, Song, Album, News, Lyric;
    private UpdateTimeTask m_updateTime;
    private Handler m_handler;
    Parser data;
    /** The delay in milliseconds between updates. */
    private final int DELAY = 20000;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Artist =(TextView)findViewById(R.id.tvArtist);
        Song  =(TextView)findViewById(R.id.tvSongTitle);
        Album =(TextView)findViewById(R.id.tvAlbum);
        play = (Button) findViewById(R.id.play);
        stop = (Button) findViewById(R.id.stop);
        Lyrics = (EditText) findViewById(R.id.tvLyrics);
        News = (TextView)findViewById(R.id.tvAnouncement);
        AlbumPic = (ImageView) findViewById(R.id.AlbumPic);



        play.setOnClickListener(this);
        stop.setOnClickListener(this);



        m_updateTime = new UpdateTimeTask();

        m_handler = new Handler();
        m_handler.post(m_updateTime);
    }

    private class UpdateTimeTask implements Runnable {
        public void run() {


            try {

                SAXParserFactory saxPF = SAXParserFactory.newInstance();
                SAXParser saxP = saxPF.newSAXParser();
                XMLReader xmlR = saxP.getXMLReader();


                URL url = new URL("http://www.mysite.com/AndroidTest.php"); 
                XMLHandler myXMLHandler = new XMLHandler();
                xmlR.setContentHandler(myXMLHandler);
                xmlR.parse(new InputSource(url.openStream()));

            } catch (Exception e) {
                System.out.println(e);
            }
            data = XMLHandler.data;



            for (int i = 0; i < data.getTitle().size(); i++) {

           Lyrics.setText(data.getLyric().get(i));
                 myimageURL = data.getPic().get(i);

            Song.setText("Title = "+data.getTitle().get(i));


            Artist.setText("Artist = "+data.getArtist().get(i));


            Album.setText("Album = "+data.getAlbum().get(i)); 






 }

 downloadFile(myimageURL );

}

Bitmap bmImg;
void downloadFile(String fileUrl) {
 URL myFileUrl = null;
 try {
    myFileUrl = new URL(fileUrl);
 } catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
 }
 try {
    HttpURLConnection conn = (HttpURLConnection) myFileUrl
          .openConnection();
    conn.setDoInput(true);
    conn.connect();
    InputStream is = conn.getInputStream();

    bmImg = BitmapFactory.decodeStream(is);
    AlbumPic.setImageBitmap(bmImg);
 } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
 }
 m_handler.postDelayed(m_updateTime, DELAY);
 AlbumPic.clearAnimation();
}

}

我的 xml 代码

<?xml version="1.0"?>
<CATALOG>
<CD>
<LYRIC>Stop that train: I'm leavin' - today!
Stop that train: I'm leavin' - anyway!
Stop that train: I'm leavin'. and I said:
It won't be too long whether I'm right or wrong;
I said, it won't be too long whether I'm right or wrong.

All my good life I've been a lonely man,
Teachin' my people who don't understand;
And even though I tried my best,
I still can't find no happiness.

So I got to say:
Stop that train: I'm leavin' - oh, baby now!
Stop that train: I'm leavin' - don't care what you say!
Stop that train: I'm leavin'. and I said:
It won't be too long whether I'm right or wrong;
Said, it won't be too long whether I'm right or wrong.

Some goin' east; and-a some goin' west,
Some stand aside to try their best.
Some livin' big, but the most is livin' small:
They just can't even find no food at all.

I mean, stop it:
Stop that train: I'm leavin' - leavin', mm-hmm.
Stop that train: I'm leavin' - I don't mind!
Stop that train: I'm leavin'. and I said:
It won't be too long whether I'm right or wrong;
I said it won't be too long whether I'm right or wrong.

Stop that train: I'm leavin' - leavin'!
Stop that train: I'm leavin' - can't take it!
Stop that train: I'm leavin' - got to be better!
It won't be too long whether I'm right or wrong;
I said it won't be too long whether I'm right or wrong.</LYRIC>
<ARTIST>Bob Marley</ARTIST>
<TITLE>Stop That Train</TITLE>
<ALBUM>Talkin blues</ALBUM>
<PIC>http://www.mysite.com/Android/Radio/AlbumCovers/Bob-Marley-Talkin-blues.jpg</PIC>
</CD>
</CATALOG>

我也尝试使用edittext加载歌词,但它也只显示&lt;LYRIC&gt;标签的第一行

有人可以提供一些建议如何在 textview 中显示整个文本

谢谢

我的 xmlhandler

public class XMLHandler extends DefaultHandler {

    String elementValue = null;
    Boolean elementOn = false;
    public static Parser data = null;

    public static Parser getXMLData() {
        return data;
    }

    public static void setXMLData(Parser data) {
        XMLHandler.data = data;
    }

    /** 
     * This will be called when the tags of the XML starts.
     **/
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        elementOn = true;

        if (localName.equals("CATALOG"))
        {
            data = new Parser();
        } else if (localName.equals("CD")) {
            /** 
             * We can get the values of attributes for eg. if the CD tag had an attribute( <CD attr= "band">Akon</CD> ) 
             * we can get the value "band". Below is an example of how to achieve this.
             * 
             * String attributeValue = attributes.getValue("attr");
             * data.setAttribute(attributeValue);
             * 
             * */
        }
    }

    /** 
     * This will be called when the tags of the XML end.
     **/
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        elementOn = false;

        /** 
         * Sets the values after retrieving the values from the XML tags
         * */ 
        if (localName.equalsIgnoreCase("title"))
            data.setTitle(elementValue);
        else if (localName.equalsIgnoreCase("artist"))
            data.setArtist(elementValue);
        else if (localName.equalsIgnoreCase("album"))
            data.setAlbum(elementValue);
        else if (localName.equalsIgnoreCase("lyric"))
            data.setLyric(elementValue);
        else if (localName.equalsIgnoreCase("pic"))
            data.setPic(elementValue);


    }

    /** 
     * This is called to get the tags value
     **/
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {

        if (elementOn) {
            elementValue = new String(ch, start, length);
            elementOn = false;
        }

    }

    public void post(Runnable mUpdate) {
        // TODO Auto-generated method stub

    }

    public void removeCallbacks(Runnable sendUpdatesToUI) {
        // TODO Auto-generated method stub

    }

    public void postDelayed(Runnable runnable, int i) {
        // TODO Auto-generated method stub

    }

}

【问题讨论】:

    标签: android xml parsing textview sax


    【解决方案1】:

    我建议你检查你的 XMLHandler 对象。我怀疑你那里有问题。

    如果您能向我们展示您的 XMLHandler 类会更好地帮助您。

    编辑:

    我对您的处理程序进行了一些更改。我认为您在读取元素值时可能会遇到问题。改用 CharArrayWriter (我已经解决了一个相同的问题)。 而且我认为您也不需要'elementOn'。如果它是不必要的变量,请不要使用它。 确保在 XML 布局上定义了一个多 TextView。 希望它有效:-)

    public class XMLHandler extends DefaultHandler {
    
        private static final String TAG = "XMLHandler";
        private String elementValue = null;
        public static Parser data = null;
    
        /** The contents. */
        private CharArrayWriter contents = new CharArrayWriter();
    
        public static Parser getXMLData() {
            return data;
        }
    
        public static void setXMLData(Parser data) {
            XMLHandler.data = data;
        }
    
        /** 
         * This will be called when the tags of the XML starts.
         **/
        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
    
            /**It´s a good practice to reset the CharArrayWriter when you start any element.*/
            contents.reset();
    
            if (localName.equals("CATALOG"))
            {
                data = new Parser();
            } else if (localName.equals("CD")) {
                /** 
                 * We can get the values of attributes for eg. if the CD tag had an attribute( <CD attr= "band">Akon</CD> ) 
                 * we can get the value "band". Below is an example of how to achieve this.
                 * 
                 * String attributeValue = attributes.getValue("attr");
                 * data.setAttribute(attributeValue);
                 * 
                 * */
            }
        }
    
        /** 
         * This will be called when the tags of the XML end.
         **/
        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            /** 
             * Sets the values after retrieving the values from the XML tags
             * */ 
             String elementValue = contents.toString().trim();
    
            if (localName.equalsIgnoreCase("title"))
                data.setTitle(elementValue);
            else if (localName.equalsIgnoreCase("artist"))
                data.setArtist(elementValue);
            else if (localName.equalsIgnoreCase("album"))
                data.setAlbum(elementValue);
            else if (localName.equalsIgnoreCase("lyric"))
                data.setLyric(elementValue);
            else if (localName.equalsIgnoreCase("pic"))
                data.setPic(elementValue);
        }
    
        /** 
         * This is called to get the tags value
         **/
        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
                contents.write(ch, start, length);
        }
    
        @Override
        public void endDocument() throws SAXException {
            Log.i(TAG, "Catalog parse finalized with success.");
        }
    }
    

    【讨论】:

    • 不客气。让我知道您的进度... 向我展示您的代码以帮助您解决问题。
    • 我在上面编辑了我的帖子,并包含了 xmlhandler 的代码,我只了解一半的情况,也许它与我的 xml 文件本身有关。当 jpg 文件的名称以“as_”开头时,我首先遇到加载图片的问题,我动态更改了所有 jpg 文件名,该问题已解决,但现在歌词出现问题
    • @user1505173,查看我的编辑
    • 是的!有效!非常感谢你真的帮助了我,不仅显示了整个歌词,而且我的应用程序也运行得更流畅了 :-) 谢谢 Yugidroid 的宝贵时间。
    • @user1505173,不客气。我很高兴能帮助你。请问你能接受答案吗? :)
    猜你喜欢
    • 2012-07-16
    • 1970-01-01
    • 2014-03-29
    • 2011-08-02
    • 1970-01-01
    • 2012-07-22
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多