tags:

views:

432

answers:

1

I have a problem when use "ViewHolder" class. I use "ViewHolder" to improve my List display speech. I think the code is ok, but why It throw exception when "setText" with data from "Cursor". My code here:

if(row==null){
   LayoutInflater inflater = LayoutInflater.from(context);   
   row = inflater.inflate(R.layout.sbooks_row, null);
   holder = new ViewHolder();

   holder.id = (TextView)row.findViewById(R.id.id);
   holder.title = (TextView)row.findViewById(R.id.title);
   holder.icon = (ImageView)row.findViewById(R.id.icon);

   row.setTag(holder);
  }
  else
  {
   holder = (ViewHolder)row.getTag();
  }

  holder.title.setText(cursor.getString(cursor.getColumnIndex(SBooksDbAdapter.KEY_TITLE)));
  holder.id.setText(cursor.getString(cursor.getColumnIndex(SBooksDbAdapter.KEY_ROWID)));
+2  A: 

You do not say what the exception is. I am going to guess it is a NullPointerException, which means either:

  1. You do not have a widget in your row with android:id="@+id/title", or
  2. You do not have a column in your result set named SBooksDbAdapter.KEY_TITLE, or
  3. Somehow you are creating rows with no holder in its tag
CommonsWare
My code run everything ok without "ViewHolder", but when I edit my code to used "ViewHolder" it throw exception. So, the First, Seconds maybe not this case. And what about the Third? Can you explain clearly? I don't understand about "creating rows with no holder" ?
Dennie
Again, you have not said what the exception is, so you are forcing me to keep guessing. One guess is that it is a NullPointerException. One thing that might be null is your holder local variable. It would be null if you have some row whose getTag() returns null. getTag() would return null if you never called setTag() on that row. That is what I mean by "creating rows with no holder".
CommonsWare
Sorry, your guess is exactly. when I debug my code It "said" NullPointerException. And It's helpful if you show me some code snippet depend on my code above. Anyway, I will check it, thanks!
Dennie