2013-07-12 2 views
0

Я немного новичок в этом. Я пытаюсь реализовать Staggered Gridview, и использование его с моим адаптером приводит к тому, что активность ничего не отображает. Вот мой код:Разнесенный сеткой пустой

public class ImageAdapter extends BaseAdapter { 

    private Context mContext; 
    ArrayList<String> itemList = new ArrayList<String>(); 

    public ImageAdapter(Context c) { 
     mContext = c; 
    } 

    void add(String path) { 
     itemList.add(path); 
    } 

    @Override 
    public int getCount() { 
     return itemList.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     // TODO Auto-generated method stub 
     return itemList.get(position); 
    } 

    @Override 
    public long getItemId(int position) { 
     // TODO Auto-generated method stub 
     return 0; 
    } 

    @SuppressLint("NewApi") 
    @Override 
    public View getView(final int position, View convertView, ViewGroup parent) { 
     // ImageView imageView; 
     SQLite db = new SQLite(mContext); 
     View grid; 
     LayoutInflater layoutInflater = getLayoutInflater(); 
     int int_id = 0; 

     String cat_id = db.getCategoryID(allWishCategory.get(position)); 
     try { 
      int_id = Integer.parseInt(cat_id); 
     } catch (NumberFormatException nfe) { 

     } 
     List<String> cat_headings = db.getAllItemsMainHeadingsWish(); 

     if (convertView == null) { 
      grid = new View(mContext); 
      grid = layoutInflater.inflate(R.layout.category_grid_item, null); 
     } else { 
      grid = (View) convertView; 
     } 
     TextView text_cat_heading = (TextView) grid.findViewById(R.id.txtCategoryName); 

     Bitmap bm = null; 

     ImageView imageView = (ImageView) grid.findViewById(R.id.category_main_pic); 
     try { 
      // Log.d("heading name", ""+cat_headings.get(int_id)); 
      text_cat_heading.setText(cat_headings.get(position)); 
      if (itemList.get(position).toString().trim().contains("DCIM")) { 
       bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220); 
      } else if (itemList.get(position).toString().trim().contains("external")) { 

       Uri myUri = Uri.parse(itemList.get(position)); 
       String[] proj = { MediaStore.Images.Media.DATA }; 
       Cursor cursor = managedQuery(myUri, proj, null, null, null); 
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
       cursor.moveToFirst(); 
       bm = decodeSampledBitmapFromUri(cursor.getString(column_index), 220, 220); 
      } else { 
       bm = BitmapFactory.decodeResource(getResources(), R.drawable.no_image1); 
      } 
     } catch (NullPointerException e) { 
      bm = BitmapFactory.decodeResource(getResources(), R.drawable.no_image1); 
     } 
     imageView.setImageBitmap(bm); 
     imageView.setAdjustViewBounds(true); 
     imageView.setMaxHeight(160); 
     imageView.setMaxWidth(160); 
     return grid; 
    } 

    private Bitmap getItemPicBitmap(String string) { 
     // TODO Auto-generated method stub 
     Bitmap bm = null; 
     // ImageView imageView = (ImageView) 
     // grid.findViewById(R.id.category_main_pic); 
     try { 
      if (string.toString().trim().contains("DCIM")) { 
       bm = decodeSampledBitmapFromUri(string, 220, 220); 
      } else if (string.toString().trim().contains("external")) { 

       Uri myUri = Uri.parse(string); 
       String[] proj = { MediaStore.Images.Media.DATA }; 
       Cursor cursor = managedQuery(myUri, proj, null, null, null); 
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
       cursor.moveToFirst(); 
       bm = decodeSampledBitmapFromUri(cursor.getString(column_index), 220, 220); 
      } else { 
       bm = BitmapFactory.decodeResource(getResources(), R.drawable.no_image1); 
      } 
     } catch (NullPointerException e) { 
      bm = BitmapFactory.decodeResource(getResources(), R.drawable.no_image1); 
     } 
     return bm; 
    } 

    public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) { 

     Bitmap bm = null; 
     final BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(path, options); 

     options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

     options.inJustDecodeBounds = false; 
     bm = BitmapFactory.decodeFile(path, options); 

     return bm; 
    } 

    public int calculateInSampleSize(

    BitmapFactory.Options options, int reqWidth, int reqHeight) { 
     // Raw height and width of image 
     final int height = options.outHeight; 
     final int width = options.outWidth; 
     int inSampleSize = 1; 

     if (height > reqHeight || width > reqWidth) { 
      if (width > height) { 
       inSampleSize = Math.round((float) height/(float) reqHeight); 
      } else { 
       inSampleSize = Math.round((float) width/(float) reqWidth); 
      } 
     } 

     return inSampleSize; 
    } 

} 

ImageAdapter myImageAdapter; 

public void initializeFirstAdapter() { 
    SQLite db = new SQLite(this); 
    StaggeredGridView gridview = (StaggeredGridView) findViewById(R.id.gridview_main); 
    myImageAdapter = new ImageAdapter(this); 
    gridview.setAdapter(myImageAdapter); 
    Log.d("myImageAdapter = ", "set"); 
    List<String> itemOwnCat = db.getWishCategoryMainPic(); 
    for (String cn : itemOwnCat) { 
     Log.d("CHECK cat_pic = ", "" + cn); 
     myImageAdapter.add(cn); 
    } 
    db.close(); 

} 

основной XML файл:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <com.origamilabs.library.views.StaggeredGridView 
     android:id="@+id/gridview_main" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_margin="5sp" 
     android:columnWidth="60sp" 
     android:gravity="center" 
     android:horizontalSpacing="10sp" 
     android:numColumns="2" 
     android:stretchMode="columnWidth" 
     android:verticalSpacing="10sp" /> 

</LinearLayout> 

category_grid_item.xml файл

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="#dddddd" 
    android:orientation="vertical" 
    android:padding="8sp" > 

    <TextView 
     android:id="@+id/txtCategoryName" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:layout_marginBottom="5sp" 
     android:text="Category name" 
     android:textAppearance="?android:attr/textAppearanceSmall" /> 

    <ImageView 
     android:id="@+id/category_num_items" 
     android:layout_width="50sp" 
     android:layout_height="25sp" 
     android:layout_above="@+id/category_main_pic" 
     android:layout_marginBottom="5sp" 
     android:layout_toRightOf="@+id/txtCategoryName" 
     android:src="@drawable/numbers" /> 

</RelativeLayout> 

Это работает с нормальным GridView, так что я делаю не так?

+0

У кого-нибудь есть предложение или помощь? – Lunchbox

+0

Значит, никто не имеет никакого представления? – Lunchbox

+0

вздох, я не решил это еще – Lunchbox

ответ

1

Позвонить notifyDataSetChanged сразу после setAdapter.

gridView.setAdapter(adapter); 
adapter.notifyDataSetChanged(); 
+0

Простите, я попробовал, я должен делать что-то еще неправильно. Мое приложение просто рушится. – Lunchbox

+0

Сбой при запуске, так как добавлен вызов notifyDataSetChanged? Я подозреваю, что до добавления вызова notifyDataSetChanged метод getView на вашем адаптере не был бы вызван. Поэтому это может быть что-то, что вы делаете в методе getView, вызывающем крах. – Smalesy

+0

Глядя на ваш метод getView, вы выполняете различные вызовы SQLite. Это не очень хорошая идея, так как это блокирует поток пользовательского интерфейса, и я подозреваю, что это послужит причиной вашего сбоя. – Smalesy

Смежные вопросы