1

I have an adapter.getCount() which is giving me a value of zero. The ListView is not visible.

I have no idea why my Adapter is empty . Can anybody suggest a solution?

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;
    }

}
Victor Oliveira
  • 3,293
  • 7
  • 47
  • 77
Srikanth86in
  • 107
  • 2
  • 12
  • 1
    Have you done **any** debugging such as checking the value of `feed` before you initialize your `Adapter`? – codeMagic Feb 18 '15 at 15:30
  • I get value of zero when i log the value of feed.getCount(); – Srikanth86in Feb 18 '15 at 15:37
  • Ok, so you probably want to check this line `getIntent().getExtras().get("feed")`. Make sure you are actually passing what you think you are. – codeMagic Feb 18 '15 at 15:38
  • If `feed` is empty, you may have started the `ListActivity` with an empty list in your `RSSFeed` when you did : `Intent intent = new Intent(context, ListActivity.class); intent.putExtra('feed', feed); startActivity(intent);` – Gorcyn Feb 18 '15 at 15:43
  • I have added the relevant classes can u guide me ? I get the value of feed 0 in AsyncLoadXMLFeed class when i try to log it. – Srikanth86in Feb 18 '15 at 15:51
  • Time to do heavy debugging Srikanth. You have to tell us what is happening. I suspect RSSFeed object is not getting any data. Where is the source? file? database? hardware interface? Is feed.getItem(pos) (in getView method) getting any data text? – The Original Android Feb 20 '15 at 07:24
  • I am curious. This is a lot of code to start asking the basic functionality. Is it for a project, or work? – The Original Android Feb 20 '15 at 07:26
  • I have some debugging and came to conclusion that DOM_Parser had some problem theString = nchild.item(j).getFirstChild().getNodeValue(); It was giving me the number of Tags in the XML but not theString value. Well, it is for a project. – Srikanth86in Feb 20 '15 at 11:49
  • Good, with that said, I'll post an answer. I just noticed the name Ramana is involved. The author may know a possible problem. – The Original Android Feb 20 '15 at 17:04

2 Answers2

0

I suspect (from what you said) that the length is = 0 in DOM_Parser. Code below

int length = nl.getLength();

The reason I said this is because RSSItem _item = new RSSItem(); This code should get you at least 1 item, and getCount() should > 0. Your xml tags may be incorrect but I expect your count > 0. But if your root/parent xml element is not "item", then the length = 0.

The Original Android
  • 6,147
  • 3
  • 26
  • 31
-2

You are not passing arraylist to your adapter.

Refer this link for more reference.

Custom Adapter for List View

Community
  • 1
  • 1
Fahim
  • 12,198
  • 5
  • 39
  • 57
  • 2
    He does not really need to, the `Adapter` being an inner class, it can access the `Activity` `feed` property – Gorcyn Feb 18 '15 at 15:39