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

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

android-rssライブラリとdroidQueryライブラリを使用してこれを行う方法に関するGistを投稿しました。

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 に答える