0

<song>リストの最初のものだけを取得しようとしているだけです。<song>私が使用しているコードは正常に動作しますが、リスト内の同様のタグ ( ) の最後のエントリしか取得しません。ここに私のXMLがあります:

    <songs id="stationid">
<song>
<title>
<![CDATA[ Last Breath ]]>
</title>
<artist>
<![CDATA[ Xela ]]>
</artist>
<album>
<![CDATA[ For Frosty Mornings And Summer Nights ]]>
</album>
<albumart>
<![CDATA[ ]]>
</albumart>
<date>1344536317</date>
</song>
<song>
<title>
<![CDATA[ Turn On Switch Off (Starring Valerie Trebeljahr) ]]>
</title>
<artist>
<![CDATA[ Static ]]>
</artist>
<album>
<![CDATA[ Flavour Has No Name ]]>
</album>
<albumart>
<![CDATA[ ]]>
</albumart>
<date>1344536000</date>
</song>
<song>
<title>
<![CDATA[ Aim Low ]]>
</title>
<artist>
<![CDATA[ Sheik & Beige ]]>
</artist>
<album>
<![CDATA[ Sty Wars - A Collection of Por ]]>
</album>
<albumart>
<![CDATA[ ]]>
</albumart>
<date>1344531485</date>
</song>
    </songs>

そして私のコード:(曲の変更に合わせてフィードが更新され、常にリストの一番上にある現在再生中の曲が欲しいので、最初のリスト項目のみを取得したい)

    package com.example.networking;

import android.app.Activity;
import android.os.Bundle;

import java.io.IOException;
import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.util.Log;

import android.widget.ImageView;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import java.io.InputStreamReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element; 
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class NetworkingActivity extends Activity {   

    private InputStream OpenHttpConnection(String urlString) 
    throws IOException
    {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString); 
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))                     
            throw new IOException("Not an HTTP connection");        
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();                 
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                 
            }                     
        }
        catch (Exception ex)
        {
            Log.d("Networking", ex.getLocalizedMessage());
            throw new IOException("Error connecting");
        }
        return in;     
    }




private String WordDefinition(String word) {
    InputStream in = null;
    String strDefinition = "";
    try {
        in = OpenHttpConnection(
"http://api.somafm.com/songs/groovesalad.xml");
        Document doc = null;
        DocumentBuilderFactory dbf = 
            DocumentBuilderFactory.newInstance();
        DocumentBuilder db;            
        try {
            db = dbf.newDocumentBuilder();
            doc = db.parse(in);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }            
        doc.getDocumentElement().normalize(); 

        //---retrieve all the <song> elements---
        NodeList definitionElements = 
            doc.getElementsByTagName("song"); 

        //---iterate through each <song> elements---
        for (int i = 0; i < definitionElements.getLength(); i++) { 
            Node itemNode = definitionElements.item(i); 
            if (itemNode.getNodeType() == Node.ELEMENT_NODE) 
            {            
                //---convert the song node into an Element---
                Element definitionElement = (Element) itemNode;

                //---get all the <artist> elements under 
                // the <song> element---
                NodeList wordDefinitionElements = 
                    (definitionElement).getElementsByTagName(
                    "artist");

                strDefinition = "";
                //---iterate through each <artist> elements---
                for (int j = 0; j < wordDefinitionElements.getLength(); j++) {                    
                    //---convert an <artist> node into an Element---
                    Element wordDefinitionElement = 
                        (Element) wordDefinitionElements.item(j);

                    //---get all the child nodes under the 
                    // <artist> element---
                    NodeList textNodes = 
                        ((Node) wordDefinitionElement).getChildNodes();

                    strDefinition += 
                        ((Node) textNodes.item(0)).getNodeValue() + ". \n";    
                }

            } 
        }
    } catch (IOException e1) {
        Log.d("NetworkingActivity", e1.getLocalizedMessage());
    }   
    //---return the definitions of the word---
    return strDefinition;
}

private class AccessWebServiceTask extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {
        return WordDefinition(urls[0]);
    }

    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
    }
}

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

  //---access a Web Service using GET---
        new AccessWebServiceTask().execute("apple");

}
}

誰かが私を助けることができればありがとう!

4

1 に答える 1

0

内側のループの最後のステートメントに最初に到達したときに、WordDefinition の外側の for ループを中断する必要があります。たとえば、フラグを設定して for でテストすることで、これを行うことができます。

boolean flag = false;    
for (int i = 0; i < definitionElements.getLength && !flag; i++) {
...
    strDefinition += 
                    ((Node) textNodes.item(0)).getNodeValue() + ". \n";
    flag = true;
    break;

次のように、XPathを使用することをお勧めします。

private String WordDefinition(String word) {
    InputStream in = null;
    String strDefinition = "";
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();

    try {
        in = OpenHttpConnection(
                "http://api.somafm.com/songs/groovesalad.xml");
        XPathExpression xPathExpression = xPath.compile("/songs/song[1]/artist");
        Node node = (Node) xPathExpression.evaluate(new InputSource(in), XPathConstants.NODE);
        strDefinition = node.getTextContent();
    }
    catch (IOException e1) {
        Log.d("NetworkingActivity", e1.getLocalizedMessage());
    }
    catch (XPathExpressionException e1) {
        Log.d("NetworkingActivity", e1.getLocalizedMessage());
    }
    // ---return the definitions of the word---
    return strDefinition;
}
于 2012-08-10T00:51:28.520 に答える