0
package com.example.nasadailyimage;


import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;

public class NasaDailyImage extends Activity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nasa_daily_image);
        IotdHandler handler = new IotdHandler();
        System.out.println("handler object created");
        Log.d("NasaDailyImage","handler object created");
        new ConfigParser().execute();//here i have called execute on my AsyncTaskclass
//      handler.processFeed(); 

        }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.nasa_daily_image, menu);
        return true;
    }

}

和我的 ConfigParser 类

import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.os.AsyncTask;
import android.util.Log;

public class ConfigParser extends AsyncTask<Void, Void,Void > {

    private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";

    @Override
    protected Void doInBackground(Void... params) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            IotdHandler handler=new IotdHandler();
            reader.setContentHandler(handler);
            InputStream inputStream = new URL(url).openStream(); 
            reader.parse(new InputSource(inputStream));
        } 
        catch (Exception e)
        {
            Log.d("IotdHandler", "Exception");
            e.printStackTrace();
        }
        return null;
    }

}

和我的 IotdHandler 类

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class IotdHandler extends DefaultHandler {

    private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
    private boolean inUrl = false;
    private boolean inTitle = false;
    private boolean inDescription = false;
    private boolean inItem = false;
    private boolean inDate = false;
    private Bitmap image = null;
    private String title = null;
    private StringBuffer description = new StringBuffer();
    private String date = null;
    private String imageUrl;



    private Bitmap getBitmap(String url) {
        try { 
            HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
            connection.setDoInput(true);

            connection.connect();
            InputStream input = connection.getInputStream();

            Bitmap bitmap = BitmapFactory.decodeStream(input);
            input.close();
            return bitmap;
        } 
        catch (IOException ioe) 
        { ioe.printStackTrace(); }
        return null;
    }

    public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
        if (localName.equals("enclosure")) 
        { inUrl = true; 
        imageUrl=attributes.getValue("url");
        System.out.println(imageUrl);
        } 
        else { inUrl = false; }
        if (localName.startsWith("item")) 
        { inItem = true; } 
        else if (inItem) { 
            if (localName.equals("title")) 
            { inTitle = true;
            System.out.println("invtitle");} 
            else { inTitle = false; }
            if (localName.equals("description")) 
            { inDescription = true; 
            System.out.println("indiscription");} 
            else { inDescription = false; }
            if (localName.equals("pubDate"))
            { inDate = true;
            System.out.println("dtae");} 
            else { inDate = false; }
        }
    }
    public void characters(char ch[], int start, int length) {
        String chars = new String(ch).substring(start, start + length);
        if (inUrl && url == null) { image = getBitmap(imageUrl); }
        if (inTitle && title == null) { title = chars; }
        if (inDescription) { description.append(chars); }
        if (inDate && date == null) { date = chars; }
    }

    public Bitmap getImage() { return image; }
    public String getTitle() { return title; }
    public StringBuffer getDescription() { return description; }
    public String getDate() { return date; }

}

所以基本上我想从 NASA 获取每日图像更新,但在我的程序中,一切都返回 null 我不知道我在尝试什么,我的 xml 文件没有解析以避免 NetworkOnMainTHread 我也使用了 Async 类,任何帮助.

4

3 回答 3

1

这是解析 xml rss 提要的代码...

import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class XMLParsingDOMExample extends Activity {

    ArrayList<String> title;
    ArrayList<String> description;
    ArrayList<String> pubDate;

    ItemAdapter adapter1;   


    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


         if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

        ListView list = (ListView) findViewById(R.id.list);
        title = new ArrayList<String>();
        description = new ArrayList<String>();  
        pubDate = new ArrayList<String>();  

        parse();

        adapter1 = new ItemAdapter(this);
        list.setAdapter(adapter1);
    }

protected void parse() {
        // TODO Auto-generated method stub


        try {

            URL url = new URL(
                    "http://www.nasa.gov/rss/dyn/image_of_the_day.rss");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("item");
            for (int i = 0; i < nodeList.getLength(); i++) {

                Node node = nodeList.item(i);       

                Element fstElmnt = (Element) node;
                NodeList nameList = fstElmnt.getElementsByTagName("title");
                Element nameElement = (Element) nameList.item(0);
                nameList = nameElement.getChildNodes();         
                title.add(((Node) nameList.item(0)).getNodeValue());

                NodeList websiteList = fstElmnt.getElementsByTagName("description");
                Element websiteElement = (Element) websiteList.item(0);
                websiteList = websiteElement.getChildNodes();
                description.add(((Node) websiteList.item(0)).getNodeValue());

                NodeList websiteList1 = fstElmnt.getElementsByTagName("pubDate");
                Element websiteElement1 = (Element) websiteList1.item(0);
                websiteList1 = websiteElement1.getChildNodes();
                pubDate.add(((Node) websiteList1.item(0)).getNodeValue());

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

    }


    class ItemAdapter extends BaseAdapter {

        final LayoutInflater mInflater;

        private class ViewHolder {
            public TextView title_text;
            public TextView des_text;
            public TextView date_text;
        }

        public ItemAdapter(Context context) {
            // TODO Auto-generated constructor stub
            super();
            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);     
        }

        //@Override
        public int getCount() {
            return title.size();
        }

        //@Override
        public Object getItem(int position) {
            return position;
        }

        //@Override
        public long getItemId(int position) {
            return position;
        }

        //@Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = convertView;
            final ViewHolder holder;
            if (convertView == null) {
                view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
                holder = new ViewHolder();
                holder.title_text = (TextView) view.findViewById(R.id.title_text);
                holder.des_text = (TextView) view.findViewById(R.id.des_text);
                holder.date_text = (TextView) view.findViewById(R.id.date_text);

                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }

            holder.title_text.setText(""+title.get(position));
            holder.des_text.setText(""+Html.fromHtml(description.get(position)));
            holder.date_text.setText(""+pubDate.get(position));         

        return view;
        }
    }
}
于 2013-08-22T05:42:59.967 回答
0

先在你的项目中做一个接口

public interface mMyInterface {

void processFinish(String response);
}

然后在您的 AsyncTaskClass 中进行以下修改

public class ConfigParser extends AsyncTask<Void, Void,Void > {


        public mMyInterface delegate=null;

private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";

@Override
protected Void doInBackground(Void... params) {
            try {
            //Log.i("inJSONPARSERCLASS","success");

            DefaultHttpClient client=new DefaultHttpClient();
            HttpPost post=new HttpPost(url);
            HttpResponse httpResponse=client.execute(post);
            HttpEntity entity=httpResponse.getEntity();

            is=entity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            Log.e("Connection Error", "Error  " + e.toString());
        }

        try {
            BufferedReader reader=new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
            StringBuilder sb=new StringBuilder();
            String line=null;

            while((line=reader.readLine())!=null){
                sb.append(line+"\n");
            }
            is.close();
            xml=sb.toString();

        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        Log.i("main XML",""+xml);
        return xml;
}
@Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        delegate.processFinish(result);


    }
}

现在在扩展活动的类中,实现接口 mMyInterface,这将覆盖其方法 processFinish(String response),现在使用“response”作为字符串并将其传递给正在完成解析的类

    @Override
    public void processFinish(String response) {
       String xml=response;
       //do SAXparsing stuff here, parse this xml string which contains the whole data u need to             
         parse
         } 

我希望这个提示对你有用。:)

于 2013-08-21T16:38:56.937 回答
0

我发布了一个关于如何使用带有 droidQuery 库的 android-rss 库做到这一点的要点

final RSSHandler handler = new RSSHandler(new RSSConfig());
$.ajax(new AjaxOptions().url(options.url())
                        .type("GET")
                        .dataType("XML")
                        .context(this)
                        .SAXContentHandler(handler)
                        .success(new Function() {
                            @Override
                            public void invoke($ droidQuery, Object... params) {
                                RSSFeed feed = handler.feed();
                                //TODO: handle feed here.
                            }
                        }));
于 2013-08-21T15:17:18.340 回答