将XML解析的值存储在textview而不是listview中

时间:2014-10-14 12:52:34

标签: java android xml

我正在尝试解析存储在列表视图中的XML。这是我的代码:

XMLParser.java

public class XMLParser {

    // constructor
    public XMLParser() {

    }

    /**
     * Getting XML from URL making HTTP request
     * @param url string
     * */
    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

    /**
     * Getting XML DOM element
     * @param XML string
     * */
    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is); 

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
    }

    /** Getting node value
      * @param elem element
      */
     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {     
            NodeList n = item.getElementsByTagName(str);        
            return this.getElementValue(n.item(0));
        }
}

AndroidXMLParsingActivity.java

public class AndroidXMLParsingActivity extends ListActivity {
    // All static variables
    static final String URL = "http://www.findyourfate.com/rss/dailyhoroscope-feed.asp?sign=Capricorn";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_TITLE = "title";
    static final String KEY_DESC = "description";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element
        NodeList nl = doc.getElementsByTagName(KEY_ITEM);
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
            // adding HashList to ArrayList
            menuItems.add(map);
        }
        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, menuItems,
                R.layout.list_item,
                new String[] { KEY_TITLE, KEY_DESC}, new int[] {
                        R.id.name, R.id.desciption});
        setListAdapter(adapter);
    }
}

现在我想将此解析后的值存储在字符串中,而不是此列表中。但是当我尝试 parser.getValue(e,KEY_DESC)); 我不知道这里的元素是什么。 如果我想将KEY_DESC设置为textview t1的文本,我该怎么办?

修改

我试过这样做,但它显示了NullPointer异常。这是我试过的:

XMLParserActivity.class:

public class XMLParserActivity extends Fragment {

    Button b1;
    TextView t1;
    EditText e1;
    String sunsign;
    static final String URL = "http://www.findyourfate.com/rss/dailyhoroscope-feed.asp?sign=Capricorn";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_TITLE = "title";
    static final String KEY_DESC = "description";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.horoscope,
                container, false);

        e1 = (EditText) rootView.findViewById(R.id.editText1);
        b1 = (Button) rootView.findViewById(R.id.button1);
        t1 = (TextView) rootView.findViewById(R.id.textView1);

        b1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                sunsign = e1.getText().toString();

                ShowResult(sunsign);

                // Toast.makeText(getActivity(), ""+fullname,
                // Toast.LENGTH_SHORT).show();
            }
        });

        return rootView;
    }

    private void ShowResult(String fullname) {
    // TODO Auto-generated method stub

    new Thread(new Runnable(){
        public void run()
        {
            XMLParser parser = new XMLParser();
            String xml = parser.getXmlFromUrl(URL); // getting XML
            Document doc = parser.getDomElement(xml); // getting DOM element

            NodeList nl = doc.getElementsByTagName(KEY_ITEM);
            Element e = (Element) nl.item(0);
            String desc = parser.getValue(e, KEY_DESC);
            t1.setText(desc);
        }
    }).start();

    DoStyling();
}

    public void DoStyling() {
        // TODO Auto-generated method stub

        t1.setVisibility(View.VISIBLE);

        //Toast.makeText(getActivity(), ""+lovenumarray, Toast.LENGTH_SHORT).show();
    }
    }

logcat的:

10-14 18:44:35.712: E/AndroidRuntime(17084): FATAL EXCEPTION: main
10-14 18:44:35.712: E/AndroidRuntime(17084): java.lang.NullPointerException
10-14 18:44:35.712: E/AndroidRuntime(17084):    at tech.know.merge.calove.HoroscopeFragment.DoStyling(HoroscopeFragment.java:82)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at tech.know.merge.calove.HoroscopeFragment.ShowResult(HoroscopeFragment.java:76)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at tech.know.merge.calove.HoroscopeFragment.access$0(HoroscopeFragment.java:59)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at tech.know.merge.calove.HoroscopeFragment$1.onClick(HoroscopeFragment.java:49)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at android.view.View.performClick(View.java:4211)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at android.view.View$PerformClick.run(View.java:17446)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at android.os.Handler.handleCallback(Handler.java:725)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at android.os.Looper.loop(Looper.java:153)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at android.app.ActivityThread.main(ActivityThread.java:5297)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at java.lang.reflect.Method.invokeNative(Native Method)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at java.lang.reflect.Method.invoke(Method.java:511)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
10-14 18:44:35.712: E/AndroidRuntime(17084):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:4)

Hello Here您可以使用DOM Parser解决您的问题

class getData extends AsyncTask<Void, Void, String> {
        private ProgressDialog mProgress;
        private String responseString;
        private String result;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            mProgress = new ProgressDialog(DOMXMLParsingActivity.this);
            mProgress.setMessage("Loading");
            mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgress.setCancelable(false);
            mProgress.show();
        }

        @Override
        protected String doInBackground(Void... unsued) {
            try {
                HttpPost httpPost = new HttpPost(
                        "http://www.findyourfate.com/rss/dailyhoroscope-feed.asp?sign=Capricorn");

                httpPost.addHeader("Accept", "application/xml");
                httpPost.addHeader("Content-Type", "application/xml");
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse httpResponse = (HttpResponse) httpclient
                        .execute(httpPost);

                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    responseString = EntityUtils.toString(httpResponse
                            .getEntity());
                    System.out.println("pankaj " + responseString);
                    result = "true";
                }

            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("error" + e);
                result = "false";
            }
            return result;
        }

        @Override
        protected void onPostExecute(String sResponse) {
            mProgress.dismiss();
            if (result.equals("true")) {
                XMLDOMParser parser = new XMLDOMParser();
                ArrayList<Data> datas = new ArrayList<Data>();
                InputStream stream = new ByteArrayInputStream(
                        responseString.getBytes());
                Document doc = parser.getDocument(stream);
                NodeList nodeList = doc.getElementsByTagName("item");
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Element e = (Element) nodeList.item(i);
                    Data data = new Data();
                    data.setName(parser.getValue(e, "title"));
                    data.setUsername(parser.getValue(e, "description"));
                    datas.add(data);
                    System.out.println("pankaj " + parser.getValue(e, "title")
                            + " " + parser.getValue(e, "description") + " "
                            + parser.getValue(e, "link"));
                }
                listView.setAdapter(new CustomListAdapter(
                        DOMXMLParsingActivity.this, datas));
            } else {

            }
        }
    }


package com.example.demowork;

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

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;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLDOMParser {
    public Document getDocument(InputStream inputStream) {
        Document document = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inputSource = new InputSource(inputStream);
            document = db.parse(inputSource);
        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }
        return document;
    }

    public String getValue(Element item, String name) {
        NodeList nodes = item.getElementsByTagName(name);
        return this.getTextNodeValue(nodes.item(0));
    }

    private final String getTextNodeValue(Node node) {
        Node child;
        if (node != null) {
            if (node.hasChildNodes()) {
                child = node.getFirstChild();
                while (child != null) {
                    if (child.getNodeType() == Node.TEXT_NODE) {
                        return child.getNodeValue();
                    }
                    child = child.getNextSibling();
                }
            }
        }
        return "";
    }
}