Android 为什么我的ListView';s Adapter.getCount()是否返回0?
我有一个Android 为什么我的ListView';s Adapter.getCount()是否返回0?,android,listview,Android,Listview,我有一个适配器.getCount(),它给了我一个零值。列表视图不可见 我不知道为什么我的适配器是空的。有人能提出解决办法吗 列表活动: /** * Created by RAMANA on 2/16/2015. */ public class ListActivity extends ActionBarActivity { Application myApp; RSSFeed feed; ListView lv; CustomListAdapter ada
适配器.getCount()
,它给了我一个零值。列表视图不可见
我不知道为什么我的适配器是空的。有人能提出解决办法吗
列表活动:
/**
* Created by RAMANA on 2/16/2015.
*/
public class ListActivity extends ActionBarActivity {
Application myApp;
RSSFeed feed;
ListView lv;
CustomListAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feed_list);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getSupportActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
myApp = getApplication();
// Get feed form the file
feed = (RSSFeed) getIntent().getExtras().get("feed");
// Initialize the variables:
lv = (ListView) findViewById(R.id.listView);
// lv.setVerticalFadingEdgeEnabled(true);
// lv.setEmptyView(findViewById(R.id.empty));
// Set an Adapter to the ListView
adapter = new CustomListAdapter(this);
int test = adapter.getCount();
String tes = Integer.toString(test);
Log.i("SRI",tes );
lv.setAdapter(adapter);
// Set on item click listener to the ListView
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
// actions to be performed when a list item clicked
int pos = arg2;
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
/* // Intent intent = new Intent(ListActivity.this,
DetailActivity.class);
intent.putExtras(bundle);
intent.putExtra("pos", pos);
startActivity(intent);*/
}
});
}
@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_main, 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);
}
@Override
protected void onDestroy() {
super.onDestroy();
//adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
// public ImageLoader imageLoader;
public CustomListAdapter(ListActivity activity) {
layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader = new ImageLoader(activity.getApplicationContext());
}
@Override
public int getCount() {
// Set the total list item count
return feed.getItemCount();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Inflate the item layout and set the views
View listItem = convertView;
int pos = position;
if (listItem == null) {
listItem = layoutInflater.inflate(R.layout.list_item,parent,false);
}
// Initialize the views in the layout
/*ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);*/
TextView tvTitle = (TextView) listItem.findViewById(R.id.title);
TextView tvStatusMsg = (TextView) listItem.findViewById(R.id.txtStatusMsg);
TextView tvUrl = (TextView)listItem.findViewById(R.id.txtUrl);
// Set the views in the layout
// imageLoader.DisplayImage(feed.getItem(pos).getImage(), iv);
tvTitle.setText(feed.getItem(pos).getTitle());
tvStatusMsg.setText(feed.getItem(pos).getDescription());
tvUrl.setText(feed.getItem(pos).getUrl());
return listItem;
}
}
}
public class RSSFeed implements Serializable {
private static final long serialVersionUID = 1L;
private int _itemcount = 0;
private List _itemlist;
RSSFeed() {
_itemlist = new Vector(0);
}
void addItem(RSSItem item) {
_itemlist.add(item);
_itemcount++;
}
public RSSItem getItem(int location) {
return (RSSItem) _itemlist.get(location);
}
public int getItemCount() {
return _itemcount;
}
}
public class MainActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private String RSSFEEDURL = "http://www.thehindu.com/news/cities/Hyderabad/?service=rss";
RSSFeed feed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getSupportActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null
&& !conMgr.getActiveNetworkInfo().isConnected()
&& !conMgr.getActiveNetworkInfo().isAvailable()) {
// No connectivity - Show alert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
@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_main, 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);
}
private class AsyncLoadXMLFeed extends AsyncTask {
@Override
protected Object doInBackground(Object[] params) {
// Obtain feed
DOM_Parser myParser = new DOM_Parser();
feed = myParser.parseXml(RSSFEEDURL);
int test = feed.getItemCount();
String tes = Integer.toString(test);
Log.i("SRI", tes );
return null;
}
@Override
protected void onPostExecute(Object o) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
}
}
/**
* Created by RAMANA on 2/16/2015.
*/
public class DOM_Parser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
for (int j = 0; j < clength; j++) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
theString = nchild.item(j).getFirstChild().getNodeValue();
if (theString != null) {
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
}
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
/* String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));*/
}
else if ("link".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
/* String formatedDate = theString.replace(" +0000",
"");*/
_item.setLink(theString);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
RSSFeed:
/**
* Created by RAMANA on 2/16/2015.
*/
public class ListActivity extends ActionBarActivity {
Application myApp;
RSSFeed feed;
ListView lv;
CustomListAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feed_list);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getSupportActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
myApp = getApplication();
// Get feed form the file
feed = (RSSFeed) getIntent().getExtras().get("feed");
// Initialize the variables:
lv = (ListView) findViewById(R.id.listView);
// lv.setVerticalFadingEdgeEnabled(true);
// lv.setEmptyView(findViewById(R.id.empty));
// Set an Adapter to the ListView
adapter = new CustomListAdapter(this);
int test = adapter.getCount();
String tes = Integer.toString(test);
Log.i("SRI",tes );
lv.setAdapter(adapter);
// Set on item click listener to the ListView
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
// actions to be performed when a list item clicked
int pos = arg2;
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
/* // Intent intent = new Intent(ListActivity.this,
DetailActivity.class);
intent.putExtras(bundle);
intent.putExtra("pos", pos);
startActivity(intent);*/
}
});
}
@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_main, 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);
}
@Override
protected void onDestroy() {
super.onDestroy();
//adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
// public ImageLoader imageLoader;
public CustomListAdapter(ListActivity activity) {
layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader = new ImageLoader(activity.getApplicationContext());
}
@Override
public int getCount() {
// Set the total list item count
return feed.getItemCount();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Inflate the item layout and set the views
View listItem = convertView;
int pos = position;
if (listItem == null) {
listItem = layoutInflater.inflate(R.layout.list_item,parent,false);
}
// Initialize the views in the layout
/*ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);*/
TextView tvTitle = (TextView) listItem.findViewById(R.id.title);
TextView tvStatusMsg = (TextView) listItem.findViewById(R.id.txtStatusMsg);
TextView tvUrl = (TextView)listItem.findViewById(R.id.txtUrl);
// Set the views in the layout
// imageLoader.DisplayImage(feed.getItem(pos).getImage(), iv);
tvTitle.setText(feed.getItem(pos).getTitle());
tvStatusMsg.setText(feed.getItem(pos).getDescription());
tvUrl.setText(feed.getItem(pos).getUrl());
return listItem;
}
}
}
public class RSSFeed implements Serializable {
private static final long serialVersionUID = 1L;
private int _itemcount = 0;
private List _itemlist;
RSSFeed() {
_itemlist = new Vector(0);
}
void addItem(RSSItem item) {
_itemlist.add(item);
_itemcount++;
}
public RSSItem getItem(int location) {
return (RSSItem) _itemlist.get(location);
}
public int getItemCount() {
return _itemcount;
}
}
public class MainActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private String RSSFEEDURL = "http://www.thehindu.com/news/cities/Hyderabad/?service=rss";
RSSFeed feed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getSupportActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null
&& !conMgr.getActiveNetworkInfo().isConnected()
&& !conMgr.getActiveNetworkInfo().isAvailable()) {
// No connectivity - Show alert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
@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_main, 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);
}
private class AsyncLoadXMLFeed extends AsyncTask {
@Override
protected Object doInBackground(Object[] params) {
// Obtain feed
DOM_Parser myParser = new DOM_Parser();
feed = myParser.parseXml(RSSFEEDURL);
int test = feed.getItemCount();
String tes = Integer.toString(test);
Log.i("SRI", tes );
return null;
}
@Override
protected void onPostExecute(Object o) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
}
}
/**
* Created by RAMANA on 2/16/2015.
*/
public class DOM_Parser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
for (int j = 0; j < clength; j++) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
theString = nchild.item(j).getFirstChild().getNodeValue();
if (theString != null) {
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
}
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
/* String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));*/
}
else if ("link".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
/* String formatedDate = theString.replace(" +0000",
"");*/
_item.setLink(theString);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
main活动:
/**
* Created by RAMANA on 2/16/2015.
*/
public class ListActivity extends ActionBarActivity {
Application myApp;
RSSFeed feed;
ListView lv;
CustomListAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feed_list);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getSupportActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
myApp = getApplication();
// Get feed form the file
feed = (RSSFeed) getIntent().getExtras().get("feed");
// Initialize the variables:
lv = (ListView) findViewById(R.id.listView);
// lv.setVerticalFadingEdgeEnabled(true);
// lv.setEmptyView(findViewById(R.id.empty));
// Set an Adapter to the ListView
adapter = new CustomListAdapter(this);
int test = adapter.getCount();
String tes = Integer.toString(test);
Log.i("SRI",tes );
lv.setAdapter(adapter);
// Set on item click listener to the ListView
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
// actions to be performed when a list item clicked
int pos = arg2;
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
/* // Intent intent = new Intent(ListActivity.this,
DetailActivity.class);
intent.putExtras(bundle);
intent.putExtra("pos", pos);
startActivity(intent);*/
}
});
}
@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_main, 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);
}
@Override
protected void onDestroy() {
super.onDestroy();
//adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
// public ImageLoader imageLoader;
public CustomListAdapter(ListActivity activity) {
layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader = new ImageLoader(activity.getApplicationContext());
}
@Override
public int getCount() {
// Set the total list item count
return feed.getItemCount();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Inflate the item layout and set the views
View listItem = convertView;
int pos = position;
if (listItem == null) {
listItem = layoutInflater.inflate(R.layout.list_item,parent,false);
}
// Initialize the views in the layout
/*ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);*/
TextView tvTitle = (TextView) listItem.findViewById(R.id.title);
TextView tvStatusMsg = (TextView) listItem.findViewById(R.id.txtStatusMsg);
TextView tvUrl = (TextView)listItem.findViewById(R.id.txtUrl);
// Set the views in the layout
// imageLoader.DisplayImage(feed.getItem(pos).getImage(), iv);
tvTitle.setText(feed.getItem(pos).getTitle());
tvStatusMsg.setText(feed.getItem(pos).getDescription());
tvUrl.setText(feed.getItem(pos).getUrl());
return listItem;
}
}
}
public class RSSFeed implements Serializable {
private static final long serialVersionUID = 1L;
private int _itemcount = 0;
private List _itemlist;
RSSFeed() {
_itemlist = new Vector(0);
}
void addItem(RSSItem item) {
_itemlist.add(item);
_itemcount++;
}
public RSSItem getItem(int location) {
return (RSSItem) _itemlist.get(location);
}
public int getItemCount() {
return _itemcount;
}
}
public class MainActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private String RSSFEEDURL = "http://www.thehindu.com/news/cities/Hyderabad/?service=rss";
RSSFeed feed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getSupportActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null
&& !conMgr.getActiveNetworkInfo().isConnected()
&& !conMgr.getActiveNetworkInfo().isAvailable()) {
// No connectivity - Show alert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
@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_main, 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);
}
private class AsyncLoadXMLFeed extends AsyncTask {
@Override
protected Object doInBackground(Object[] params) {
// Obtain feed
DOM_Parser myParser = new DOM_Parser();
feed = myParser.parseXml(RSSFEEDURL);
int test = feed.getItemCount();
String tes = Integer.toString(test);
Log.i("SRI", tes );
return null;
}
@Override
protected void onPostExecute(Object o) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
}
}
/**
* Created by RAMANA on 2/16/2015.
*/
public class DOM_Parser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
for (int j = 0; j < clength; j++) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
theString = nchild.item(j).getFirstChild().getNodeValue();
if (theString != null) {
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
}
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
/* String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));*/
}
else if ("link".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
/* String formatedDate = theString.replace(" +0000",
"");*/
_item.setLink(theString);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
DOM\u解析器:
/**
* Created by RAMANA on 2/16/2015.
*/
public class ListActivity extends ActionBarActivity {
Application myApp;
RSSFeed feed;
ListView lv;
CustomListAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feed_list);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getSupportActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
myApp = getApplication();
// Get feed form the file
feed = (RSSFeed) getIntent().getExtras().get("feed");
// Initialize the variables:
lv = (ListView) findViewById(R.id.listView);
// lv.setVerticalFadingEdgeEnabled(true);
// lv.setEmptyView(findViewById(R.id.empty));
// Set an Adapter to the ListView
adapter = new CustomListAdapter(this);
int test = adapter.getCount();
String tes = Integer.toString(test);
Log.i("SRI",tes );
lv.setAdapter(adapter);
// Set on item click listener to the ListView
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
// actions to be performed when a list item clicked
int pos = arg2;
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
/* // Intent intent = new Intent(ListActivity.this,
DetailActivity.class);
intent.putExtras(bundle);
intent.putExtra("pos", pos);
startActivity(intent);*/
}
});
}
@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_main, 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);
}
@Override
protected void onDestroy() {
super.onDestroy();
//adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
// public ImageLoader imageLoader;
public CustomListAdapter(ListActivity activity) {
layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader = new ImageLoader(activity.getApplicationContext());
}
@Override
public int getCount() {
// Set the total list item count
return feed.getItemCount();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Inflate the item layout and set the views
View listItem = convertView;
int pos = position;
if (listItem == null) {
listItem = layoutInflater.inflate(R.layout.list_item,parent,false);
}
// Initialize the views in the layout
/*ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);*/
TextView tvTitle = (TextView) listItem.findViewById(R.id.title);
TextView tvStatusMsg = (TextView) listItem.findViewById(R.id.txtStatusMsg);
TextView tvUrl = (TextView)listItem.findViewById(R.id.txtUrl);
// Set the views in the layout
// imageLoader.DisplayImage(feed.getItem(pos).getImage(), iv);
tvTitle.setText(feed.getItem(pos).getTitle());
tvStatusMsg.setText(feed.getItem(pos).getDescription());
tvUrl.setText(feed.getItem(pos).getUrl());
return listItem;
}
}
}
public class RSSFeed implements Serializable {
private static final long serialVersionUID = 1L;
private int _itemcount = 0;
private List _itemlist;
RSSFeed() {
_itemlist = new Vector(0);
}
void addItem(RSSItem item) {
_itemlist.add(item);
_itemcount++;
}
public RSSItem getItem(int location) {
return (RSSItem) _itemlist.get(location);
}
public int getItemCount() {
return _itemcount;
}
}
public class MainActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private String RSSFEEDURL = "http://www.thehindu.com/news/cities/Hyderabad/?service=rss";
RSSFeed feed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getSupportActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null
&& !conMgr.getActiveNetworkInfo().isConnected()
&& !conMgr.getActiveNetworkInfo().isAvailable()) {
// No connectivity - Show alert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
@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_main, 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);
}
private class AsyncLoadXMLFeed extends AsyncTask {
@Override
protected Object doInBackground(Object[] params) {
// Obtain feed
DOM_Parser myParser = new DOM_Parser();
feed = myParser.parseXml(RSSFEEDURL);
int test = feed.getItemCount();
String tes = Integer.toString(test);
Log.i("SRI", tes );
return null;
}
@Override
protected void onPostExecute(Object o) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
}
}
/**
* Created by RAMANA on 2/16/2015.
*/
public class DOM_Parser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
for (int j = 0; j < clength; j++) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
theString = nchild.item(j).getFirstChild().getNodeValue();
if (theString != null) {
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
}
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
/* String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));*/
}
else if ("link".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
/* String formatedDate = theString.replace(" +0000",
"");*/
_item.setLink(theString);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
/**
*由拉马纳于2015年2月16日创建。
*/
公共类DOM_解析器{
私有RSSFeed_feed=新RSSFeed();
公共RSSFeed解析xml(字符串xml){
URL=null;
试一试{
url=新url(xml);
}捕获(格式错误的异常e1){
e1.printStackTrace();
}
试一试{
//创建所需的实例
DocumentBuilderFactoryDBF;
dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
//解析xml
Document doc=db.parse(新的输入源(url.openStream());
doc.getDocumentElement().normalize();
//获取所有标签。
NodeList nl=doc.getElementsByTagName(“项目”);
int length=nl.getLength();
for(int i=0;i
您没有将arraylist传递给适配器
有关更多参考信息,请参阅此链接
根据您所说的,我怀疑DOM_解析器中的长度为=0。代码如下
int length = nl.getLength();
我之所以这么说是因为RSSItem\u item=newrssitem()代码>此代码应至少获取1项,getCount()应>0。您的xml标记可能不正确,但我希望您的计数>0。但是,如果根/父xml元素不是“item”,则长度为0。在初始化适配器之前,是否进行过任何调试,例如检查提要的值。
?在记录提要的值时,我得到的值为零。getCount();好的,您可能想检查这一行getIntent().getExtras().get(“feed”)
。确保您实际传递的是您认为的内容。如果feed
为空,则您可能已在RSSFeed
中使用空列表启动了ListActivity
,此时:Intent Intent=new Intent(上下文,ListActivity.class);意向。额外投入(“饲料”,饲料);星触觉(意向)代码>我已经添加了相关的类,你可以指导我吗?当我尝试记录它时,我在AsyncLoadXMLFeed类中获得了feed 0的值。他实际上不需要,因为适配器
是一个内部类,它可以访问活动
feed
属性最终解决了问题。我不得不更改DOM_解析器类并重写代码。