我目前正在构建一个应用程序,该应用程序从以下网站读取xml文件:http://wx.toronto.ca/festevents.nsf/tpaview?readviewentries,然后将其显示在带有图像和单个列表视图的列表视图中。我面临的问题是,使用以下代码解析后:
NodeList nodeList = document.getElementsByTagName("viewentry");
它只返回xml文件中的第一个子元素。以下是xml文件的部分副本以获得一个想法:
<viewentries timestamp="20141204T225826,77Z" toplevelentries="486">
<viewentry position="1" unid="76D2D8314E365A2A85257DA4004B11B7" noteid="56C06" siblings="486">
<entrydata columnnumber="0" name="EventName">
<text>Learn To Skate Lessons</text>
</entrydata>
<entrydata columnnumber="1" name="Area">
<textlist>
<text>Central East</text>
<text>Southeast</text>
</textlist>
</entrydata>
<entrydata columnnumber="2" name="CategoryList">
<textlist>
<text>Family/Children</text>
<text>Sports</text>
</textlist>
</entrydata>
<entrydata columnnumber="3" name="PresentedByOrgName">
<text/>
</entrydata>
<entrydata columnnumber="4" name="Image">
<text>
http://wx.toronto.ca/festevents.nsf/all/76D2D8314E365A2A85257DA4004B11B7/$File/learntoskate.jpg
</text>
</entrydata>
</viewentry>
以下是我的Android代码...我测试了我的singleListview和我的imageloader,而不是它们都有效。
MainActivity
public class TorontourismActivity extends Activity{
ListView listView;
ListViewAdapter adapter;
ProgressDialog progressDialog;
ArrayList<HashMap<String,String>> arrayList;
static String Event = "text";
static String Area = "text";
static String Category = "textlist";
static String Presented = "entrydata";
static String Image = "entrydata columnnumber=4 name=Image";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main); //View from the layout file in res folder
new DownloadXMLFile().execute();
}
private class DownloadXMLFile extends AsyncTask<Void,Void,Void>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(TorontourismActivity.this);
progressDialog.setTitle("Torontourism the know it all for Toronto Events");
progressDialog.setMessage("I'm loading....Give me a minute.");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... params)
{
arrayList = new ArrayList<HashMap<String, String>>();
TorontourismParser parser = new TorontourismParser();
String xml = parser.getXMLfromURL("http://wx.toronto.ca/festevents.nsf/tpaview?readviewentries");
Document document = parser.getElements(xml);
try
{
NodeList nodeList = document.getElementsByTagName("viewentry");
for(int i =0; i < nodeList.getLength(); i++)
{
Element element = (Element) nodeList.item(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(Event, parser.getValue(element, Event));
map.put(Area, parser.getValue(element, Area));
// map.put(Category, parser.getValue(element, Category));
map.put(Image, parser.getValue(element, Image));
/*map.put(ShowDate, parser.getValue(element, ShowDate));
map.put(BeginTime, parser.getValue(element, BeginTime));
map.put(EndShowDate, parser.getValue(element, EndShowDate));*/
System.out.println(Event);
arrayList.add(map);
}
} catch (Exception e)
{
Log.i("Error in Torontourism Activity", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void arguments)
{
listView = (ListView) findViewById(R.id.listView);
adapter = new ListViewAdapter(TorontourismActivity.this, arrayList);
listView.setAdapter(adapter);
progressDialog.dismiss();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_torontourism, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
DOM Parser
public class TorontourismParser {
static final String FesEventURL = "http://wx.toronto.ca/festevents.nsf/tpaview?readviewentries";
//constructor
public TorontourismParser()
{
}
//open a HTTP Connection
public String getXMLfromURL(String urlString)
{
String xmlfile = null;
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlString);
HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xmlfile = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xmlfile;
}
public Document getElements(String xml)
{
Document document = null;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource.setCharacterStream(new StringReader(xml));
document = documentBuilder.parse(inputSource);
} catch (Exception e) {
Log.e("Error in Parser file", e.getMessage());
e.printStackTrace();
}
return document;
}
public final String getElements(Node node)
{
Node element;
StringBuilder value = new StringBuilder();
if(node != null)
{
if(node.hasChildNodes())
{
for(element = node.getFirstChild(); element != null;
element = element.getNextSibling())
{
if (element.getNodeType() == Node.TEXT_NODE)
{
value.append(element.getNodeValue());
}
}
}
}
return value.toString();
}
public String getValue(Element element, String string) {
NodeList nodeList = element.getElementsByTagName(string);
return this.getElements(nodeList.item(0));
}
}
ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater layoutInflater;
ArrayList<HashMap<String,String>> xmldata;
ImageLoader imageLoader;
HashMap<String,String> hashMap = new HashMap<String, String>();
public ListViewAdapter(Context context,ArrayList<HashMap<String,String>> arrayList)
{
this.context = context;
xmldata = arrayList;
imageLoader = new ImageLoader(context);
}
@Override
public int getCount() {
return xmldata.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
TextView Event;
TextView Area;
TextView Category;
TextView Presented;
ImageView Image;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.listview_item, parent, false);
hashMap = xmldata.get(position);
Event = (TextView) view.findViewById(R.id.Event);
Area = (TextView) view.findViewById(R.id.Area);
//Category = (TextView) view.findViewById(R.id.Category);
//Presented = (TextView) view.findViewById(R.id.Presented);
Image = (ImageView) view.findViewById(R.id.Image);
Event.setText(hashMap.get(TorontourismActivity.Event));
Area.setText(hashMap.get(TorontourismActivity.Area));
//Category.setText(hashMap.get(TorontourismActivity.Category));
// Presented.setText(hashMap.get(TorontourismActivity.Presented));
imageLoader.DisplayImage(hashMap.get(TorontourismActivity.Image),Image);
Log.i("Event:", hashMap.get(TorontourismActivity.Event));
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view1) {
hashMap = xmldata.get(position);
Intent intent = new Intent(context,SingleItemView.class);
intent.putExtra("Event", hashMap.get(TorontourismActivity.Event));
intent.putExtra("Area", hashMap.get(TorontourismActivity.Area));
// intent.putExtra("Category", hashMap.get(TorontourismActivity.Category));
//intent.putExtra("Presented", hashMap.get(TorontourismActivity.Presented));
intent.putExtra("Image", hashMap.get(TorontourismActivity.Event));
context.startActivity(intent);
}
});
return view;
}
}
Single Item viewer
public class SingleItemView extends Activity {
String Event;
String Area;
String Presented;
String Category;
String Image;
ImageLoader imageLoader = new ImageLoader(this);
@Override
public void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.singleitemview);
Intent intent = getIntent();
Event = intent.getStringExtra("Event");
Area = intent.getStringExtra("Area");
//Presented = intent.getStringExtra("Presented");
// Category = intent.getStringExtra("Category");
Image = intent.getStringExtra("Image");
TextView textView = (TextView) findViewById(R.id.Event);
//TextView textView1 = (TextView) findViewById(R.id.Area);
//TextView textView2 = (TextView) findViewById(R.id.Presented);
//TextView textView3 = (TextView) findViewById(R.id.Category);
ImageView imageView = (ImageView) findViewById(R.id.Image);
textView.setText(Event);
//textView1.setText(Area);
//textView2.setText(Presented);
//textView3.setText(Category);
imageLoader.DisplayImage(Image, imageView);
}
}
图像加载器
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViewStringMap
= Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int NoImage_Id = R.drawable.temp_img;
public void DisplayImage(String url, ImageView imageView) {
imageViewStringMap.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
queuePhoto(url, imageView);
//imageView.setImageDrawable(getResources().getDrawable());
// imageView.setImageResource(R.drawable.temp_img);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad photoToLoad = new PhotoToLoad(url,imageView);
executorService.submit(new PhotoLoader(photoToLoad));
}
private Bitmap getBitmap(String url) {
File file = fileCache.getFile(url);
Bitmap bitmap = decodeFile(file);
if (bitmap != null)
return bitmap;
try {
Bitmap bitmap1 = null;
URL imageurl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) imageurl.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setInstanceFollowRedirects(true);
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = new FileOutputStream(file);
Utils.CopyStream(inputStream, outputStream);
outputStream.close();
connection.disconnect();
bitmap = decodeFile(file);
return bitmap;
} catch (Throwable ex) {
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
private Bitmap decodeFile(File file) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
FileInputStream fileInputStream = new FileInputStream(file);
BitmapFactory.decodeStream(fileInputStream, null, options);
fileInputStream.close();
final int Size = 1000;
int width_temp = options.outWidth, height_temp = options.outHeight;
int scale = 1;
while (true) {
if (width_temp / 2 < Size || height_temp / 2 < Size)
break;
width_temp /= 2;
height_temp /= 2;
scale *= 2;
}
BitmapFactory.Options options1 = new BitmapFactory.Options();
options1.inSampleSize = scale;
FileInputStream inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options1);
inputStream.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String uri, ImageView ImView)
{
url = uri;
imageView = ImView;
}
}
class PhotoLoader implements Runnable
{
PhotoToLoad photoToLoad;
PhotoLoader(PhotoToLoad photoToLoad){
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
try{
if(ImageViewReused(photoToLoad))
return;
Bitmap bitmap = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bitmap);
if(ImageViewReused(photoToLoad))
return;
BitmapDisplayer bitmapDisplayer = new BitmapDisplayer(bitmap,photoToLoad);
handler.post(bitmapDisplayer);
} catch (Throwable throwable){
throwable.printStackTrace();
}
}
}
boolean ImageViewReused(PhotoToLoad photoToLoad)
{
String string = imageViewStringMap.get(photoToLoad.imageView);
if(string == null || !string.equals(photoToLoad.url))
return true;
return false;
}
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap bitmap1, PhotoToLoad photoToLoad1)
{
bitmap = bitmap1;
photoToLoad = photoToLoad1;
}
public void run() {
if(ImageViewReused(photoToLoad))
return;
if(bitmap != null){
photoToLoad.imageView.setImageBitmap(bitmap);
}else{
//photoToLoad.imageView.setImageResource(NoImage_Id);
}
}
}
public void clearCache()
{
memoryCache.clear();
fileCache.clear();
}
}
感谢任何帮助。从我认为问题出在解析器文件中。除此之外,请帮助我。
谢谢!