Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android XML解析器是';不太管用_Java_Android_Xml_Parsing_Url - Fatal编程技术网

Java Android XML解析器是';不太管用

Java Android XML解析器是';不太管用,java,android,xml,parsing,url,Java,Android,Xml,Parsing,Url,我需要将XML数据解析为字符串[],以便在下拉式自动完成文本视图中显示它。我试过JDOM,但它对我不起作用。我在另一个解析器上停止: 我只用我需要的东西重拨了密码 现在我有以下文件: 包com.example.selpItemalProject.ivo.dimitrov import java.util.ArrayList; import java.util.HashMap; import org.w3c.dom.Document; import org.w3c.dom.Element; im

我需要将XML数据解析为字符串[],以便在下拉式自动完成文本视图中显示它。我试过JDOM,但它对我不起作用。我在另一个解析器上停止: 我只用我需要的东西重拨了密码 现在我有以下文件: 包com.example.selpItemalProject.ivo.dimitrov

import java.util.ArrayList;
import java.util.HashMap;

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

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
在此处输入代码
导入android.widget.ArrayAdapter; 导入android.widget.AutoCompleteTextView

public class browse_courses extends Activity {
    // All static variables
        static final String URL = "http://www.inf.ed.ac.uk/teaching/courses/selp/xml/courses.xml";
// XML node keys
static final String KEY_ITEM = "course"; // parent node
static final String KEY_DRPS = "drps";
static final String KEY_NAME = "name";
static final String KEY_URL = "url";
static final String KEY_ACR = "acronym";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    overridePendingTransition(R.anim.fadein, R.anim.fadeout);
    setContentView(R.layout.activity_browse_courses);

    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 <course>
    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_DRPS, parser.getValue(e, KEY_DRPS));
        map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
        map.put(KEY_URL, parser.getValue(e, KEY_URL));
        map.put(KEY_ACR, parser.getValue(e, KEY_ACR));

        // adding HashList to ArrayList
        menuItems.add(map);
    }
    int len = menuItems.size();
    String[] abc = new String[len]; // array to hold all the names which then will be in the drop-down text view
    for(int i=0;i<len;i++){
        abc[i]=(menuItems.get(i)).get(KEY_NAME);
    }
    String[] a={"abc","bcd"}; //ignore, made for testing

    AutoCompleteTextView textView = (AutoCompleteTextView)     findViewById(R.id.autoCompleteTextViewCourses);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.select_dialog_item, abc);

        textView.setThreshold(1);

        textView.setAdapter(adapter);
        }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.browse_courses, menu);
    return true;
}
}


我不确定是否是android虚拟设备无法下载XML文件或其他内容。

在android中解析XML的最佳推荐方法是使用xmlPullParser而不是DOM

问题是,每当我在AVD中打开此活动时,应用程序就会崩溃,我不知道为什么。发布您的Logcat错误。
package com.example.selptimetableproject.ivo.dimitrov;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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 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));
    }