1

当我只解析一个然后它正常运行时,我在我的应用程序中解析 RSS 提要,但我有 8 个不同的 URL 地址要在按钮上设置,我想为每个按钮单击解析 RSS 提要。我正在使用 SAX 解析器。我的代码如下

BaseFeedParser.java

package com.example.shareslab;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.example.shareslab.Message;

import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Xml;

public class BaseFeedParser {

    static String feedUrlString = "http://www.xxxx.com/rss.xml";

    // names of the XML tags
    static final String RSS = "rss";
    static final String CHANNEL = "channel";
    static final String ITEM = "item";

    static final String PUB_DATE = "pubDate";
    static final String DESCRIPTION = "description";
    static final String LINK = "link";
    static final String TITLE = "title";    
    private final URL feedUrl;

    protected BaseFeedParser(){
        try {
            this.feedUrl = new URL(feedUrlString);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    protected InputStream getInputStream() {
        try {
            return feedUrl.openConnection().getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Message> parse() {
        final Message currentMessage = new Message();
        RootElement root = new RootElement(RSS);
        final List<Message> messages = new ArrayList<Message>();
        Element itemlist = root.getChild(CHANNEL);
        Element item = itemlist.getChild(ITEM);
        item.setEndElementListener(new EndElementListener(){
            @Override
            public void end() {
                messages.add(currentMessage.copy());
            }
        });
        item.getChild(TITLE).setEndTextElementListener(new EndTextElementListener(){
            @Override
            public void end(String body) {
                currentMessage.setTitle(body);
            }
        });
        item.getChild(LINK).setEndTextElementListener(new EndTextElementListener(){
            @Override
            public void end(String body) {
                currentMessage.setLink(body);
            }
        });
        item.getChild(DESCRIPTION).setEndTextElementListener(new EndTextElementListener(){
            @Override
            public void end(String body) {
                currentMessage.setDescription(body);
            }
        });
        item.getChild(PUB_DATE).setEndTextElementListener(new EndTextElementListener(){
            @Override
            public void end(String body) {
                currentMessage.setDate(body);
            }
        });
        try {
            Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return messages;
    }
}

我有 8 个按钮和 8 个 RSS 提要的 URL 地址,我想为每个按钮解析它

消息列表.java

    package com.example.shareslab;


import java.util.ArrayList;
import java.util.Arrays;


import com.example.shareslab.R;


import android.app.ListActivity;

import android.content.Context;
import android.content.Intent;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;


import android.widget.ImageView;
import android.widget.ListView;


import android.widget.TextView;


public class MessageList extends ListActivity implements OnClickListener {

    Button home,socialmedia,tech,usworld,business,fashion,people,political;


    public static String singleDescription;
    public static String title,URLToPost,imageURL;
    public static ArrayList<String> galleryImages;
    private static class EfficientAdapter extends BaseAdapter 
    {    
        private LayoutInflater mInflater;
        public EfficientAdapter(Context context)
        {
            mInflater = LayoutInflater.from(context);
        }
        @Override
        public int getCount() {
            System.out.println("description COUNT : "+SplashActivity.description.size());
            return SplashActivity.description.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) 
        {

            ViewHolder holder;
            if (convertView == null)
            {
                convertView = mInflater.inflate(R.layout.inflate_list_item, null);
                holder = new ViewHolder();              
                holder.title = (TextView) convertView.findViewById(R.id.inflate_title);
                holder.des = (TextView) convertView.findViewById(R.id.inflate_description);
                holder.im=    (ImageView) convertView.findViewById(R.id.inflate_image);
                convertView.setTag(holder);           
            }
            else 
            {
                holder = (ViewHolder) convertView.getTag();

            }   

            UrlImageViewHelper.setUrlDrawable(holder.im, SplashActivity.imageURLAmit.get(position),null);
            holder.title.setText(SplashActivity.titles.get(position));
            holder.des.setText(SplashActivity.description.get(position));

            return convertView;
        }   

        public static class ViewHolder {
            TextView title,des;
            ImageView im;
        }

    } // close class Efficent adapter


    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        home=(Button)findViewById(R.id.buttonhome);
        socialmedia=(Button)findViewById(R.id.buttonsocial);
        tech=(Button)findViewById(R.id.buttontech);
        usworld=(Button)findViewById(R.id.buttonusworld);
        business=(Button)findViewById(R.id.buttonbusiness);
        fashion=(Button)findViewById(R.id.buttonfashion);
        people=(Button)findViewById(R.id.buttonpeople);
        political=(Button)findViewById(R.id.buttonpolitical);


        home.setOnClickListener(this);
        socialmedia.setOnClickListener(this);
        tech.setOnClickListener(this);
        usworld.setOnClickListener(this);
        business.setOnClickListener(this);
        fashion.setOnClickListener(this);
        people.setOnClickListener(this);
        political.setOnClickListener(this);



        ListView listView = getListView();
        listView.setTextFilterEnabled(true);
        this.setListAdapter(new EfficientAdapter(this));
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // When clicked, show a toast with the TextView text
                galleryImages=new ArrayList<String>();
                singleDescription=SplashActivity.description.get(position);
                title=SplashActivity.titles.get(position);
                URLToPost=SplashActivity.link.get(position);
                imageURL=SplashActivity.imageURLAmit.get(position);
                System.out.println("ON CLICK URL: "+URLToPost);
                galleryImages.addAll(Arrays.asList(SplashActivity.arrays[position]));               
                startActivity(new Intent(MessageList.this,MessageListDetail.class));
            }
        });


    }


    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

    }
}
4

2 回答 2

0

您可以将每个字段的 URL 存储为相应按钮的标记。

// ...
    home.setOnClickListener(this);
    home.setTag(new URL("http://example.com/feed1.xml"));
    socialmedia.setOnClickListener(this);
    socialmedia.setTag(new URL("http://example.com/feed2.xml"));
    tech.setOnClickListener(this);
    tech.setTag(new URL("http://example.com/feed3.xml"));    
}

@Override
public void onClick(View v) {
  URL feedUrl = (URL) v.getTag();

  // Then do your thing
  new FeedParser(feedUrl);
}

并为解析器创建一个公共构造函数:

public BaseFeedParser(URL feedUrl){
    this.feedUrl = feedUrl;
}
于 2012-10-23T09:46:31.223 回答
-1
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="@drawable/background"
 android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="20dp"
    android:text="SPORTS LIVE"
    android:textColor="#000000"
    android:textSize="25dp" />

<Button
    android:id="@+id/button1"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center"
    android:layout_marginTop="48dp"
    android:background="@drawable/nfl"/>

<Button
    android:id="@+id/button2"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button1"
    android:layout_below="@+id/button1"
    android:layout_gravity="center"
    android:layout_marginTop="50dp"
    android:background="@drawable/nba" />

<Button
    android:id="@+id/button3"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button2"
    android:layout_below="@+id/button2"
    android:layout_gravity="center"
    android:layout_marginTop="50dp"  
    android:background="@drawable/mlb" />

<Button
    android:id="@+id/button4"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button3"
    android:layout_below="@+id/button3"
    android:layout_gravity="center"
    android:layout_marginTop="50dp"
    android:background="@drawable/ncaa" />

 </LinearLayout>

public class MainActivity extends Activity {

Button NFL,NBA,MLB,NCAA;
Intent i;

 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    NFL= (Button) findViewById(R.id.button1);
    NBA= (Button) findViewById(R.id.button2);
    MLB= (Button) findViewById(R.id.button3);
    NCAA= (Button) findViewById(R.id.button4);
    i= new Intent("idss.sportslive.All");
    // NFL
    NFL.setOnTouchListener( new OnTouchListener()
    {

        @Override
        public boolean onTouch(View arg0, MotionEvent event) {
            // TODO Auto-generated method stub
            switch(event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    NFL.setBackgroundResource(R.drawable.nflhigh);
                break;
                case MotionEvent.ACTION_UP:
                    NFL.setBackgroundResource(R.drawable.nfl);
                    // i= new Intent("idss.sportslive.All");
                     i.putExtra("url", 0);
                     startActivity(i);
                break;
            }
            return false;
        }

    });
    // NBA
    NBA.setOnTouchListener( new OnTouchListener()
    {

        @Override
        public boolean onTouch(View arg0, MotionEvent event) {
            // TODO Auto-generated method stub
            switch(event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    NBA.setBackgroundResource(R.drawable.nbahigh);
                break;
                case MotionEvent.ACTION_UP:
                    NBA.setBackgroundResource(R.drawable.nba);
                    //i= new Intent("idss.sportslive.ALL");
                     i.putExtra("url", 1);
                     startActivity(i);
                break;
            }
            return false;
        }

    });
    //MLB
   MLB.setOnTouchListener( new OnTouchListener()
    {

        @Override
        public boolean onTouch(View arg0, MotionEvent event) {
            // TODO Auto-generated method stub
            switch(event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    MLB.setBackgroundResource(R.drawable.mlbhigh);
                break;
                case MotionEvent.ACTION_UP:
                    MLB.setBackgroundResource(R.drawable.mlb);
                    //i= new Intent("idss.sportslive.ALL");
                     i.putExtra("url", 2);
                     startActivity(i);
                break;
            }
            return false;
        }

    });
   //NCAA
   NCAA.setOnTouchListener( new OnTouchListener()
   {

        @Override
        public boolean onTouch(View arg0, MotionEvent event) {
            // TODO Auto-generated method stub
            switch(event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    NCAA.setBackgroundResource(R.drawable.ncaahigh);
                break;
                case MotionEvent.ACTION_UP:
                    NCAA.setBackgroundResource(R.drawable.ncaa);
                    //i= new Intent("idss.sportslive.ALL");
                     i.putExtra("url", 3);
                     startActivity(i);
                break;
            }
            return false;
        }

   });
  }

  }

解析器

   public class All extends Activity {
List headlines;
List links;
static Context c;
ProgressDialog pd;
List team1l,score1l,team2l,score2l,matchtype;
String url1[]={ "http://www.mpiii.com/scores/nfl.php/",
         "http://www.mpiii.com/scores/nba.php/",
         "http://www.mpiii.com/scores/mlb.php/",
         "http://www.mpiii.com/scores/ncaa.php/"};
;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.listview_main);
    pd= new ProgressDialog(this);
    pd.setMessage("Loading....");
    headlines = new ArrayList();
    links = new ArrayList();
    team1l= new ArrayList();
    score1l= new ArrayList();
    team2l= new ArrayList();
    score2l= new ArrayList();
    matchtype= new ArrayList();
    c= this;
    new TheTask().execute();
    //System.out.println("URL iSSSSSSSSSSS"+d.get("url"));


    }
class TheTask extends AsyncTask<Void, Void, Void>{
    Bundle d;
    URL url ;
    @Override
    protected void onPreExecute() {
        //Intent intent= new Intent();
        d= ((Activity) c).getIntent().getExtras();
        pd.show();
    }

    @Override
    protected Void doInBackground(Void... params) {


        try {

            if(d.get("url").toString().equals("0"))
            {
                 url = new URL(url1[0]);
            }
            if(d.get("url").toString().equals("1"))
            {
                 url = new URL(url1[1]);
            }
            if(d.get("url").toString().equals("2"))
            {
                 url = new URL(url1[2]);
            }
            if(d.get("url").toString().equals("3"))
            {
                 url = new URL(url1[3]);
            }


            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(false);
            XmlPullParser xpp = factory.newPullParser();
            xpp.setInput(url.openConnection().getInputStream(), "UTF_8"); 
            //xpp.setInput(getInputStream(url), "UTF-8");

            boolean insideItem = false;

                // Returns the type of current event: START_TAG, END_TAG, etc..
            int eventType = xpp.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG) {

                    if (xpp.getName().equalsIgnoreCase("item")) {
                        insideItem = true;
                    } else if (xpp.getName().equalsIgnoreCase("title")) {
                        if (insideItem)
                            headlines.add(xpp.nextText()); //extract the headline
                    } else if (xpp.getName().equalsIgnoreCase("link")) {
                        if (insideItem)
                            links.add(xpp.nextText()); //extract the link of article
                    }
                }else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
                    insideItem=false;
                }

                eventType = xpp.next(); //move to next element
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

for(int i=0;i<headlines.size();i++)
{
      String s=headlines.get(i).toString();
      Pattern pc = Pattern.compile("([a-zA-Z ]+)\\s+(\\d+)\\s+([a-zA-Z ]+)\\s+(\\d+)\\s+\\((\\w+)\\)"); 
      Matcher matcher = pc.matcher(s);
             while (matcher.find( ))
             {
             String team1 = matcher.group(1); 
                String score1 = matcher.group(2); 
                String team2 = matcher.group(3); 
                String score2 = matcher.group(4); 
                String result = matcher.group(5); 
                team1l.add(team1);
                score1l.add(score1);
                team2l.add(team2);
                score2l.add(score2);
                matchtype.add(result);
                System.out.println( team1 + " scored " + score1 + ", " + team2 + " scored " + score2 + ", which was " + result); 
             }
}

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        setContentView(R.layout.listview_main);
        if(CheckNetwork.isInternetAvailable(c))
        {   
        if(team1l.isEmpty())
        {
            Toast.makeText(c, "No data Available now. Try again Later", 1000).show();
            finish();
        }
        {
            ListView lv= (ListView) findViewById(R.id.list1);
            lv.setAdapter(new CustomAdapter(getApplicationContext(),team1l,score1l,team2l,score2l,matchtype,links));
        //setContentView(R.layout.contentcatalog);
    //  setUI();
            pd.dismiss();
        }
    }
        else
        {
            Toast.makeText(c, "Check Network Connection!. Try again Later", 1000).show();
            finish();
        }
    }
}
}

我不确定它是否是正确的方法。我有类似的要求来解析基于按钮点击的 rss 提要。希望这会有所帮助

于 2012-10-23T09:49:04.607 回答