我有一个adapter.getCount()
给我一个零值。 ListView
不可见。
我不知道为什么Adapter
为空。有人可以提出解决方案吗?
ListActivity:
/**
* 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;
}
}
}
的RSSFeed:
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;
}
}
MainActivity:
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();
}
}
}
DOM_Parser:
/**
* 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;
}
}
答案 0 :(得分:0)
我怀疑(根据你的说法)DOM_Parser中的长度为= 0。代码
int length = nl.getLength();
我说这是因为RSSItem _item = new RSSItem();
此代码应该至少为您提供1项,而getCount()应该&gt;你的xml标签可能不正确,但我希望你的计数&gt; 0.但是如果你的root / parent xml元素不是&#34; item&#34;,那么长度= 0。
答案 1 :(得分:-2)