gpt4 book ai didi

android - 如何使用 sax 显示 XML 解析

转载 作者:行者123 更新时间:2023-11-30 04:11:24 24 4
gpt4 key购买 nike

我想使用此 URL 的 SAX 创建 xml 解析

http://news.google.com/?output=rss

但是我得到了错误,请检查并让我知道我在哪里做错了,或者如果我的问题有其他解决方案。

我在 GoogleNewsSaxActivity.class 中的这一行出错

for (int i = 0; i < baseParserData.getTitle().size(); i++) {

我的代码如下。

GoogleNewsSaxActivity.class

public class GoogleNewsSaxActivity extends Activity {

BaseFeedParser baseParserData;

ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
private myAdapter rssadaptor = null;
ListView lview;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();


URL url = new URL("http://news.google.com/?output=rss");

RssHandler myXMLHandler = new RssHandler();
xmlR.setContentHandler(myXMLHandler);

xmlR.parse(new InputSource(url.openStream()));


} catch (Exception e) {
System.out.println(e);
}

baseParserData = RssHandler.baseParserData;

/**
* Run a for loop to set All the TextViews with text until
* the size of the array is reached.
*
**/
for (int i = 0; i < baseParserData.getTitle().size(); i++) {

System.out.println("value of i==============>" + i);
HashMap<String, String> map = new HashMap<String, String>();

map.put("title", baseParserData.getTitle().get(i));
//map.put("Artist", baseParserData.getArtist().get(i));
//map.put("Contry", baseParserData.getCountry().get(i));

items.add(map);

rssadaptor = new myAdapter(GoogleNewsSaxActivity.this, items);
}

lview = (ListView) findViewById(R.id.listView);

// Getting adapter by passing xml data ArrayList
rssadaptor = new myAdapter(this, items);
lview.setAdapter(rssadaptor);

}
}

RssHandler.class

public class RssHandler extends DefaultHandler{

/*private List<BaseFeedParser> messages;
//private Message currentMessage;
private StringBuilder builder;*/


String elementValue = null;
Boolean elementOn = false;
public static BaseFeedParser baseParserData = null;

public static BaseFeedParser getBaseParserData() {

return baseParserData;
}
public static void setBaseParserData(BaseFeedParser baseParserData) {

RssHandler.baseParserData = baseParserData;
}

/*public List<BaseFeedParser> getMessages(){
return this.messages;
}*/

@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
elementOn = true;

System.out.println("Hello this is startElement : =========>");

if (localName.equals(BaseFeedParser.CHANNEL))
{
baseParserData = new BaseFeedParser();
} else if (localName.equals(BaseFeedParser.ITEM)) {


}
}

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {

if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}

}


@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {

elementOn = false;

/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase(BaseFeedParser.TITLE))
baseParserData.setTitle(elementValue);
else if (localName.equalsIgnoreCase(BaseFeedParser.LINK))
baseParserData.setLink(elementValue);
else if (localName.equalsIgnoreCase(BaseFeedParser.PUB_DATE))
baseParserData.setPubDate(elementValue);
else if (localName.equalsIgnoreCase(BaseFeedParser.DESCRIPTION))
baseParserData.setDescription(elementValue);

}


}

还有另外两个类 BaseFeedParser.class 和 myAdapter.class,BaseFeedParser 类包含 Getters/Setters 方法,myadapter 是自定义 ListView 的适配器类。

谢谢。

LOGCAT 中显示错误

05-31 09:42:25.693: I/System.out(279): java.net.SocketException: Permission denied
05-31 09:42:25.713: D/AndroidRuntime(279): Shutting down VM
05-31 09:42:25.713: W/dalvikvm(279): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-31 09:42:25.752: E/AndroidRuntime(279): FATAL EXCEPTION: main
05-31 09:42:25.752: E/AndroidRuntime(279): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rahul.android.sax/com.rahul.android.sax.GoogleNewsSaxActivity}: java.lang.NullPointerException
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.os.Handler.dispatchMessage(Handler.java:99)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.os.Looper.loop(Looper.java:123)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-31 09:42:25.752: E/AndroidRuntime(279): at java.lang.reflect.Method.invokeNative(Native Method)
05-31 09:42:25.752: E/AndroidRuntime(279): at java.lang.reflect.Method.invoke(Method.java:521)
05-31 09:42:25.752: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-31 09:42:25.752: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-31 09:42:25.752: E/AndroidRuntime(279): at dalvik.system.NativeStart.main(Native Method)
05-31 09:42:25.752: E/AndroidRuntime(279): Caused by: java.lang.NullPointerException
05-31 09:42:25.752: E/AndroidRuntime(279): at com.rahul.android.sax.GoogleNewsSaxActivity.onCreate(GoogleNewsSaxActivity.java:61)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-31 09:42:25.752: E/AndroidRuntime(279): ... 11 more

最佳答案

使用下面的代码。

站点列表.java

public class SitesList {

/** Variables */
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> website = new ArrayList<String>();
private ArrayList<String> pubdate = new ArrayList<String>();
private ArrayList<String> desc = new ArrayList<String>();

/**
* In Setter method default it will return arraylist change that to add
*/

public ArrayList<String> getName() {
return name;
}

public void setName(String name) {
this.name.add(name);
}

public ArrayList<String> getWebsite() {
return website;
}

public void setWebsite(String website) {
this.website.add(website);
}

public ArrayList<String> getPubdate() {
return pubdate;
}

public void setPubdate(String pubdate) {
this.pubdate.add(pubdate);
}

public ArrayList<String> getDesc() {
return desc;
}

public void setDesc(String desc) {
this.desc.add(desc);
}

}

MyXMLHandler.java

public class MyXMLHandler extends DefaultHandler {

Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;

public static SitesList getSitesList() {
return sitesList;
}

public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}

/**
* Called when tag starts ( ex:- <name>AndroidPeople</name> -- <name> )
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {

currentElement = true;

if (localName.equals("channel")) {
/** Start */
sitesList = new SitesList();
}

}

/**
* Called when tag closing ( ex:- <name>AndroidPeople</name> -- </name> )
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {

currentElement = false;

/** set value */
if (localName.equalsIgnoreCase("title")) {
sitesList.setName(currentValue);
} else if (localName.equalsIgnoreCase("link")) {
sitesList.setWebsite(currentValue);
} else if (localName.equalsIgnoreCase("pubDate")) {
sitesList.setPubdate(currentValue);
} else if (localName.equalsIgnoreCase("description")) {
sitesList.setDesc(currentValue);
}
}

/**
* Called to get tag characters ( ex:- <name>AndroidPeople</name> -- to get
* AndroidPeople Character )
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {

if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}

}

}

主 Activity .java

public class MainActivity extends Activity {
SitesList sitesList = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);

/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView pubdate[];
TextView desc[];

try {

/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();

/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://news.google.com/?output=rss");

/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));

} catch (Exception e) {
System.out.println("XML Pasing Exception = " + e);
}

/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;

/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
website = new TextView[sitesList.getWebsite().size()];
pubdate = new TextView[sitesList.getPubdate().size()];
desc = new TextView[sitesList.getDesc().size()];

System.out.println("Hello Name size is:- " +sitesList.getName().size());
System.out.println("Hello website size is:- " +sitesList.getWebsite().size());
System.out.println("Hello pubdate size is:- " +sitesList.getPubdate().size());
System.out.println("Hello desc size is:- " +sitesList.getDesc().size());


/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name is = " + sitesList.getName().get(i));
website[i] = new TextView(this);
website[i].setText("Link is = " + sitesList.getWebsite().get(i));

layout.addView(name[i]);
layout.addView(website[i]);
}

/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getPubdate().size(); i++) {
pubdate[i] = new TextView(this);
pubdate[i].setText("Pub date is = "
+ sitesList.getPubdate().get(i));

desc[i] = new TextView(this);
desc[i].setText("Desc is = "
+ sitesList.getDesc().get(i));

layout.addView(pubdate[i]);
layout.addView(desc[i]);
}

/** Set the layout view to display */
setContentView(layout);

}
}

关于android - 如何使用 sax 显示 XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10815733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com