如何使用 xml 解析器解析 java.lang.string 无法转换为 java.lang.integer andr

时间:2023-01-13
本文介绍了如何使用 xml 解析器解析 java.lang.string 无法转换为 java.lang.integer android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试解析 XML 并将其显示到列表视图中,但在运行应用程序后没有任何反应 - 显示列表但不包含 XML 数据.我不知道我是否遗漏了什么.

I am trying to parse XML and display it into list view, but after running the app nothing happens -- the list is displayed but not with the XML data . I don't know if I am missing something.

MainActivity 类

public class MainActivity extends ListActivity {
// All static variables
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    ListView myList=(ListView)findViewById(android.R.id.list);

    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

    XMLParser parser = new XMLParser();
    String xml = null; // getting XML
    try {
        xml = parser.getXmlFormUrl(URL);
    } catch (IOException e) {
        e.printStackTrace();
    }
    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_ID, parser.getValue(e, KEY_ID));
        map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
        map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
        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.activity_main,
            new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
            R.id.name, R.id.desciption, R.id.cost });

    setListAdapter(adapter);
    // selecting single ListView item

}

}

XmlParser 类

 public class XMLParser {
    String result;
    public String getXmlFormUrl(String link) throws IOException{
    URL url=new URL(link.toString());
    HttpURLConnection UrlConnection= (HttpURLConnection)     url.openConnection();
    int status=UrlConnection.getResponseCode();
    if(status==200){
        InputStream inputStream=UrlConnection.getInputStream();
        BufferedReader bufferedReader=new BufferedReader(new     InputStreamReader(inputStream,"UTF8"));
        StringBuilder stringBuilder= new StringBuilder();
        String line;
        while ((line=bufferedReader.readLine())!=null){
            stringBuilder.append((line+"
"));
        }
        result=stringBuilder.toString();
        inputStream.close();
    }
    return  result;
}
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 DOM
    return doc;
}
public String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return this.getElementValue(n.item(0));
}

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 "";
}

}

ActivityMain.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="android.prgguru.com.xmlparsingg.MainActivity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@android:id/list"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="73dp" />
</RelativeLayout>

logcat

2/? E/ActivityThread: Service com.google.android.gms.car.CarService has leaked ServiceConnection com.google.android.gms.car.hr@3bb3cd94 that was originally bound here
                                                   android.app.ServiceConnectionLeaked: Service com.google.android.gms.car.CarService has leaked ServiceConnection com.google.android.gms.car.hr@3bb3cd94 that was originally bound here
                                                       at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1083)
                                                       at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:977)
                                                       at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1779)
                                                       at android.app.ContextImpl.bindService(ContextImpl.java:1762)
                                                       at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
                                                       at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
                                                       at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
                                                       at com.google.android.gms.common.stats.g.a(:com.google.android.gms:128)
                                                       at com.google.android.gms.common.stats.g.a(:com.google.android.gms:145)
                                                       at com.google.android.gms.car.hc.<init>(:com.google.android.gms:319)
                                                       at com.google.android.gms.car.CarChimeraService.onCreate(:com.google.android.gms:74)
                                                       at com.google.android.chimera.container.ServiceProxy.setImpl(:com.google.android.gms:119)
                                                       at com.google.android.chimera.container.ServiceProxy.onCreate(:com.google.android.gms:109)
                                                       at android.app.ActivityThread.handleCreateService(ActivityThread.java:2825)
                                                       at android.app.ActivityThread.access$1800(ActivityThread.java:156)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1434)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:211)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5373)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)

推荐答案

您不能直接将您的 String 对象更改或引用为 Integer 类型,因为没有 这两个类的父子关系.

You cannot directly change or reference your String object to Integer type because there is no parent-child relationship between these two classes.

如果您尝试以这种方式将 String cast 转换为 Integer,则会引发 ClassCastException.

If you try to cast a String to a Integer in such a way, it will raise a ClassCastException.

String someValue = "123";
Integer intValue = (Integer) someValue; // ClassCastException Raise.

所以如果你想改变或引用一个String变量为Integer,你必须使用解析技术.

So if you want to change or reference a String Variable to Integer, you must use parsing techniques.

int intValue = Integer.parseInt(someValue); //this code will work for this.

这篇关于如何使用 xml 解析器解析 java.lang.string 无法转换为 java.lang.integer android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Sax - ExpatParser$ParseException 下一篇:XMl 解析中的空指针异常

相关文章

最新文章