久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

如何使用 xml 解析器解析 java.lang.string 無法轉換為

how to resolve java.lang.string cannot be cast to java.lang.integer android with xml parser(如何使用 xml 解析器解析 java.lang.string 無法轉換為 java.lang.integer android)
本文介紹了如何使用 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Upload progress listener not fired (Google drive API)(上傳進度偵聽器未觸發(Google 驅動器 API))
Save file in specific folder with Google Drive SDK(使用 Google Drive SDK 將文件保存在特定文件夾中)
Google Drive Android API - Invalid DriveId and Null ResourceId(Google Drive Android API - 無效的 DriveId 和 Null ResourceId)
Google drive api services account view uploaded files to google drive using java(谷歌驅動api服務賬戶查看上傳文件到谷歌驅動使用java)
Google Drive service account returns 403 usageLimits(Google Drive 服務帳號返回 403 usageLimits)
com.google.api.client.json.jackson.JacksonFactory; missing in Google Drive example(com.google.api.client.json.jackson.JacksonFactory;Google Drive 示例中缺少)
主站蜘蛛池模板: 亚洲一区 | 日本不卡一区 | 国产一区二区三区在线 | 中文日韩在线 | 国产美女久久久 | 日韩一区二区av | 国产乱码久久久久久 | 日韩精品av一区二区三区 | 久热9| 国产精品7777777 | 99热这里只有精品8 激情毛片 | 日韩免费视频一区二区 | 欧美综合一区二区三区 | 欧美猛交| 久久专区 | 国产一区在线看 | av免费网站在线观看 | 中文二区 | 成人激情视频 | 日韩精品免费一区二区在线观看 | 久久91av| 国产精品久久国产精品久久 | 1204国产成人精品视频 | 成人欧美一区二区三区黑人孕妇 | 中文字幕一区二区三区乱码图片 | 国产精品久久久久久久岛一牛影视 | 国产福利观看 | 草久网 | 日韩成人性视频 | 国产精品精品久久久 | 91久久久久久久久久久 | 美女日批免费视频 | 可以在线观看av的网站 | 狠狠综合久久av一区二区小说 | 成人性视频免费网站 | 岛国av免费观看 | 99精品免费久久久久久日本 | 人人爽人人草 | 精品美女 | 99色综合| 91亚洲视频在线 |