2015-02-18 2 views
1

У меня есть adapter.getCount(), который дает мне значение нуля. ListView не отображается.Почему Adapter.getCount() возвращает ListView ListView 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; 
    } 

} 
+1

Вы сделали ** любую ** отладку, такую ​​как проверка значения 'feed', прежде чем инициализировать свой« адаптер »? – codeMagic

+0

Я получаю значение нуля, когда я регистрирую значение feed.getCount(); – Srikanth86in

+0

Итак, вы, вероятно, захотите проверить эту строку 'getIntent(). GetExtras(). Get (" feed ")'. Убедитесь, что вы фактически передаете то, что считаете себя. – codeMagic

ответ

-2

Вы не проходя ArrayList к адаптеру.

Ссылка на эту ссылку для получения дополнительной информации.

Custom Adapter for List View

+2

Ему действительно не нужно, что 'Adapter' является внутренним классом, он может получить доступ к свойству' Activity' 'feed' – Gorcyn

0

Я подозреваю (от того, что вы сказали), что длина = в DOM_Parser 0. Код ниже

int length = nl.getLength(); 

Причина я сказал это потому, что RSSItem _item = new RSSItem(); Этот код вы должны получить по крайней мере 1 пункт, и GetCount() должны> 0. Ваши XML-теги могут быть неправильными, но я ожидаю ваш счетчик> 0. Но если ваш элемент root/parent xml не является «item», то длина = 0.

+0

Наконец, решила проблему. Мне пришлось изменить класс DOM_Parser и переписать код. – Srikanth86in