我正在为一个活动中的Show RSS feed构建Android应用程序, 我在EditText中编写RSS链接并单击按钮,然后显示RSS提要(新闻)。
当我进入RSS链接并在第一次点击按钮时,正常显示新闻,但我的问题是当我输入新的链接&按下按钮:新链接的新闻出现在旧消息下(我在EditText中输入的第一个链接的消息)。
但是,当我按下按钮时,我想删除旧消息并显示新链接的RSS提要。
有什么想法吗?
提前致谢。
我的代码:
在MainActivity中:
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static String rss_url = "http://www.thehindu.com/news/cities/chennai/chen-health/?service=rss";
ProgressDialog progressDialog;
Handler handler = new Handler();
RSSListView list;
RSSListAdapter adapter;
ArrayList<RSSNewsItem> newsItemList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
list = new RSSListView(this);
adapter = new RSSListAdapter(this);
list.setAdapter(adapter);
list.setOnDataSelectionListener(new OnDataSelectionListener() {
public void onDataSelected(AdapterView parent, View v,
int position, long id) {
RSSNewsItem curItem = (RSSNewsItem) adapter.getItem(position);
String curTitle = curItem.getTitle();
Toast.makeText(getApplicationContext(),
"Selected : " + curTitle, 1000).show();
}
});
newsItemList = new ArrayList<RSSNewsItem>();
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
mainLayout.addView(list, params);
final EditText edit01 = (EditText) findViewById(R.id.edit01);
edit01.setText(rss_url);
Button show_btn = (Button) findViewById(R.id.show_btn);
show_btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String inputStr = edit01.getText().toString();
showRSS(inputStr);
}
});
}
private void showRSS(String urlStr) {
try {
progressDialog = ProgressDialog.show(this, "RSS Refresh",
"RSS Lodeing..", true, true);
RefreshThread thread = new RefreshThread(urlStr);
thread.start();
} catch (Exception e) {
Log.e(TAG, "Error", e);
}
}
class RefreshThread extends Thread {
String urlStr;
public RefreshThread(String str) {
urlStr = str;
}
public void run() {
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
URL urlForHttp = new URL(urlStr);
InputStream instream = getInputStreamUsingHTTP(urlForHttp);
// parse
Document document = builder.parse(instream);
int countItem = processDocument(document);
Log.d(TAG, countItem + " news item processed.");
// post for the display of fetched RSS info.
handler.post(updateRSSRunnable);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public InputStream getInputStreamUsingHTTP(URL url) throws Exception {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
int resCode = conn.getResponseCode();
Log.d(TAG, "Response Code : " + resCode);
InputStream instream = conn.getInputStream();
return instream;
}
private int processDocument(Document doc) {
newsItemList.clear();
Element docEle = doc.getDocumentElement();
NodeList nodelist = docEle.getElementsByTagName("item");
int count = 0;
if ((nodelist != null) && (nodelist.getLength() > 0)) {
for (int i = 0; i < nodelist.getLength(); i++) {
RSSNewsItem newsItem = dissectNode(nodelist, i);
if (newsItem != null) {
newsItemList.add(newsItem);
count++;
}
}
}
return count;
}
private RSSNewsItem dissectNode(NodeList nodelist, int index) {
RSSNewsItem newsItem = null;
try {
Element entry = (Element) nodelist.item(index);
Element title = (Element) entry.getElementsByTagName("title").item(
0);
Element link = (Element) entry.getElementsByTagName("link").item(0);
Element description = (Element) entry.getElementsByTagName(
"description").item(0);
NodeList pubDataNode = entry.getElementsByTagName("pubDate");
if (pubDataNode == null) {
pubDataNode = entry.getElementsByTagName("dc:date");
}
Element pubDate = (Element) pubDataNode.item(0);
Element author = (Element) entry.getElementsByTagName("author")
.item(0);
Element category = (Element) entry.getElementsByTagName("category")
.item(0);
String titleValue = null;
if (title != null) {
Node firstChild = title.getFirstChild();
if (firstChild != null) {
titleValue = firstChild.getNodeValue();
}
}
String linkValue = null;
if (link != null) {
Node firstChild = link.getFirstChild();
if (firstChild != null) {
linkValue = firstChild.getNodeValue();
}
}
String descriptionValue = null;
if (description != null) {
Node firstChild = description.getFirstChild();
if (firstChild != null) {
descriptionValue = firstChild.getNodeValue();
}
}
String pubDateValue = null;
if (pubDate != null) {
Node firstChild = pubDate.getFirstChild();
if (firstChild != null) {
pubDateValue = firstChild.getNodeValue();
}
}
String authorValue = null;
if (author != null) {
Node firstChild = author.getFirstChild();
if (firstChild != null) {
authorValue = firstChild.getNodeValue();
}
}
String categoryValue = null;
if (category != null) {
Node firstChild = category.getFirstChild();
if (firstChild != null) {
categoryValue = firstChild.getNodeValue();
}
}
Log.d(TAG, "item node : " + titleValue + ", " + linkValue + ", "
+ descriptionValue + ", " + pubDateValue + ", "
+ authorValue + ", " + categoryValue);
newsItem = new RSSNewsItem(titleValue, linkValue, descriptionValue,
pubDateValue, authorValue, categoryValue);
} catch (DOMException e) {
e.printStackTrace();
}
return newsItem;
}
Runnable updateRSSRunnable = new Runnable() {
public void run() {
try {
Resources res = getResources();
Drawable rssIcon = res.getDrawable(R.drawable.rss_icon);
for (int i = 0; i < newsItemList.size(); i++) {
RSSNewsItem newsItem = (RSSNewsItem) newsItemList.get(i);
newsItem.setIcon(rssIcon);
adapter.addItem(newsItem);
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
并在OnDataSelectionListener类中:
public interface OnDataSelectionListener {
public void onDataSelected(AdapterView parent, View v, int position, long id);
}
并在RSSListAdapter中:
public class RSSListAdapter extends BaseAdapter {
private Context mContext;
private List<RSSNewsItem> mItems = new ArrayList<RSSNewsItem>();
public RSSListAdapter(Context context) {
mContext = context;
}
public void addItem(RSSNewsItem it) {
mItems.add(it);
}
public void setListItems(List<RSSNewsItem> lit) {
mItems = lit;
}
public int getCount() {
return mItems.size();
}
public Object getItem(int position) {
return mItems.get(position);
}
public boolean areAllItemsSelectable() {
return false;
}
public boolean isSelectable(int position) {
return true;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
RSSNewsItemView itemView;
if (convertView == null) {
itemView = new RSSNewsItemView(mContext, mItems.get(position));
} else {
itemView = (RSSNewsItemView) convertView;
itemView.setIcon(mItems.get(position).getIcon());
itemView.setText(0, mItems.get(position).getTitle());
itemView.setText(1, mItems.get(position).getPubDate());
itemView.setText(2, mItems.get(position).getCategory());
itemView.setText(3, mItems.get(position).getDescription());
}
return itemView;
}
}
并在RSSListView类中:
public class RSSListView extends ListView {
/**
* DataAdapter for this instance
*/
private RSSListAdapter adapter;
/**
* Listener for data selection
*/
private OnDataSelectionListener selectionListener;
public RSSListView(Context context) {
super(context);
init();
}
public RSSListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* set initial properties
*/
private void init() {
// set OnItemClickListener for processing OnDataSelectionListener
setOnItemClickListener(new OnItemClickAdapter());
}
/**
* set DataAdapter
*
* @param adapter
*/
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
}
/**
* get DataAdapter
*
* @return
*/
public BaseAdapter getAdapter() {
return (BaseAdapter) super.getAdapter();
}
/**
* set OnDataSelectionListener
*
* @param listener
*/
public void setOnDataSelectionListener(OnDataSelectionListener listener) {
this.selectionListener = listener;
}
/**
* get OnDataSelectionListener
*
* @return
*/
public OnDataSelectionListener getOnDataSelectionListener() {
return selectionListener;
}
class OnItemClickAdapter implements OnItemClickListener {
public OnItemClickAdapter() {
}
public void onItemClick(AdapterView parent, View v, int position,
long id) {
if (selectionListener == null) {
return;
}
// get row and column
int rowIndex = -1;
int columnIndex = -1;
// call the OnDataSelectionListener method
selectionListener.onDataSelected(parent, v, position, id);
}
}
}
并在RSSNewsItem类中:
public class RSSNewsItem {
private String title;
private String link;
private String description;
private String pubDate;
private String author;
private String category;
private Drawable mIcon;
/**
* Initialize with icon and data array
*/
public RSSNewsItem() {
}
/**
* Initialize with icon and strings
*/
public RSSNewsItem(String title, String link, String description, String pubDate, String author, String category) {
this.title = title;
this.link = link;
this.description = description;
this.pubDate = pubDate;
this.author = author;
this.category = category;
}
/**
* Set icon
*
* @param icon
*/
public void setIcon(Drawable icon) {
mIcon = icon;
}
/**
* Get icon
*
* @return
*/
public Drawable getIcon() {
return mIcon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
/**
* Compare with the input object
*
* @param other
* @return
*/
public int compareTo(RSSNewsItem other) {
if (title.equals(other.getTitle())) {
return -1;
} else if (link.equals(other.getLink())) {
return -1;
} else if (description.equals(other.getDescription())) {
return -1;
} else if (pubDate.equals(other.getPubDate())) {
return -1;
} else if (author.equals(other.getAuthor())) {
return -1;
} else if (category.equals(other.getCategory())) {
return -1;
}
return 0;
}
}
最后,在RSSNewsItemView类中:
public class RSSNewsItem {
private String title;
private String link;
private String description;
private String pubDate;
private String author;
private String category;
private Drawable mIcon;
/**
* Initialize with icon and data array
*/
public RSSNewsItem() {
}
/**
* Initialize with icon and strings
*/
public RSSNewsItem(String title, String link, String description, String pubDate, String author, String category) {
this.title = title;
this.link = link;
this.description = description;
this.pubDate = pubDate;
this.author = author;
this.category = category;
}
/**
* Set icon
*
* @param icon
*/
public void setIcon(Drawable icon) {
mIcon = icon;
}
/**
* Get icon
*
* @return
*/
public Drawable getIcon() {
return mIcon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
/**
* Compare with the input object
*
* @param other
* @return
*/
public int compareTo(RSSNewsItem other) {
if (title.equals(other.getTitle())) {
return -1;
} else if (link.equals(other.getLink())) {
return -1;
} else if (description.equals(other.getDescription())) {
return -1;
} else if (pubDate.equals(other.getPubDate())) {
return -1;
} else if (author.equals(other.getAuthor())) {
return -1;
} else if (category.equals(other.getCategory())) {
return -1;
}
return 0;
}
}
答案 0 :(得分:0)
我认为您需要拨打adapter.clear()
并在点击按钮时再次使用adapter.notifyDataSet()
使列表无效。