从url获取XML文件到Android应用程序

时间:2014-08-21 07:26:38

标签: java android xml

我有一个问题,从网站获取.xml数据并解析到Android应用程序,我尝试了很多建议但从未工作过。当我在资源文件夹中打开文件时它工作正常,但是当我尝试从url获取时,它没有显示任何内容

这是我的活动类

package com.android.baliweather;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;  
import android.widget.TextView;

public class Prakiraan extends Activity {
/** Called when the activity is first created. */
private ListView listView;
private TextView judul;
private String URL_MAIN = "http://localhost/android/propinsi_17_1.xml";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.prakiraan_cuaca);
    judul = (TextView) findViewById(R.id.menu1);
    listView = (ListView) findViewById(R.id.listview);
    bindDataToListing();
}

private void bindDataToListing() {
    try {
        URL url = new URL("http://localhost/android/propinsi_17_1.xml");
        URLConnection connection = url.openConnection();
        //URLConnection connection = url.openConnection();  
        //HttpURLConnection httpConnection = (HttpURLConnection)connection;
        //InputStream in = httpConnection.getInputStream();
        SAXParserFactory saxparser = SAXParserFactory.newInstance();
        SAXParser parser = saxparser.newSAXParser();
        XMLReader xmlReader = parser.getXMLReader();
        XMLParser pc = new XMLParser();
        xmlReader.setContentHandler(pc);
        //InputStream is = getAssets().open("propinsi_17_1.xml");
        //InputStream is = new URL(URL_MAIN).openStream();
        xmlReader.parse(new InputSource(connection.getInputStream()));
        BindingData bindingData = new BindingData(this, pc.kota, pc.cuaca, pc.suhuMin, pc.suhuMax, pc.kelembapanMin, pc.kelembapanMax, pc.kecepatanAngin, pc.arahAngin);
        listView.setAdapter(bindingData);
    } 
    catch (Exception e) {
        e.getMessage();
    }
}

}

我认为问题只在这个课上,但我不知道哪一个。请帮忙

1 个答案:

答案 0 :(得分:0)

可能是android.os.NetworkOnMainThreadException - 您正在尝试在UI线程中执行时间繁重的任务,而系统阻止您这样做(您可以在logcat中看到这一点)。您可以实现AsyncTask以便在后台线程中执行此操作。

也可能是您忘记在清单文件中添加权限 - <uses-permission android:name="android.permission.INTERNET" />