Android -ArrayindexboundException 在将图像的 byte[] 从数据库设置到 Listview 时出现

Android -ArrayindexboundException in setting a byte[] of image from database to Listview

我需要在 SQLite 数据库中插入和检索它们,并在自定义 ListView 中设置为图像视图。但是 运行 应用抛出一个 ArrayIndexOutOfBoundException

所以我尝试在 while 循环之外制作 j=0。但仍然导致 ArrayIndexOutOfBoundException 行:

 Bitmap b1=BitmapFactory.decodeByteArray(img[j], 0, img.length);

我该怎么办?我在数组中有图像。

MainActivity

public class MainActivity extends Activity{


ListView prd_list;
public static Integer clas;
byte [] imge;

int j;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    prd_list = (ListView) findViewById(R.id.list);
    DataBaseHandler dbh = new DataBaseHandler(this);


    Bitmap[] images = { BitmapFactory.decodeResource(getResources
            (),R.drawable.candle1),BitmapFactory.decodeResource(getResources   
            (),R.drawable.candl3),BitmapFactory.decodeResource(getResources(),R.drawable.candl4),BitmapFactory.decodeResource(getResources(),R.drawable.candl5),BitmapFactory.decodeResource(getResources(),R.drawable.candl6),BitmapFactory.decodeResource(getResources(),R.drawable.sglc10),BitmapFactory.decodeResource(getResources(),R.drawable.senson),BitmapFactory.decodeResource(getResources(),R.drawable.lawn)}; 

    byte[][] img = new byte[images.length][];
    for (j=0; j<images.length; j++) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        images[j].compress(Bitmap.CompressFormat.PNG, 100, bos);

        // use a 2D array for img if you want to retain the byte arrays for all the bitmaps
        img[j] = bos.toByteArray();
    }


    SQLiteDatabase db = dbh.getWritableDatabase();
    Cursor cr = db.rawQuery("SELECT * FROM product", null);
    final String[] pname = new String[cr.getCount()];
    String[] price = new String[cr.getCount()];

    int i = 0;
    j=0;
    while(cr.moveToNext())
    {

        String name = cr.getString(cr.getColumnIndex("pname"));
        String prprice = cr.getString(cr.getColumnIndex("pprice"));

        imge=cr.getBlob(cr.getColumnIndex("pimage"));
        img[j] = imge;

        pname[i] = name;
        price[i] = prprice;
        i++;
        j++;
    }
    ListAdapter adapter = new ListAdapter(this, img,pname, price);
    prd_list.setAdapter(adapter);

  } 
}

列表适配器

public class ListAdapter extends BaseAdapter {

private final String[] pname;
private final String[] price;
private final byte[] []img;
private Context mcontext;
int j=0;

        public ListAdapter(Context c,byte[][]img,String[] pname,String[] price){
    mcontext=c;
    this.pname=pname;
    this.price=price;
    this.img=img;
}

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return pname.length;
    }

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
         View List;
         LayoutInflater mLayoutinflater=(LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         if(convertView==null){
         List=new View(mcontext);

         List=mLayoutinflater.inflate(R.layout.mylist, parent, false);
         }
         else{
         List = (View)convertView;
         }

         TextView textView1 = (TextView)List.findViewById(R.id.pr_name);
         TextView textView2 = (TextView)List.findViewById(R.id.pr_price);
         ImageView imageview= (ImageView)List.findViewById(R.id.pr_img);
         textView1.setText(pname[position].toString());
         textView2.setText("Rs "+price[position] +" /-");
             Bitmap b1=BitmapFactory.decodeByteArray(img[j], 0, img[j].length);
             imageview.setImageBitmap(b1);

         // TODO Auto-generated method stub
         return List;

    }

}

已编辑

public class DataBaseHandler extends SQLiteOpenHelper{

   public static final int DATABASE_VERSION = 1;
   public static final String DATABASE_NAME = "products.db";
   public static final String CONTACTS_TABLE_NAME = "product";
   public static final String CONTACTS_COLUMN_ID = "pid";
   public static final String CONTACTS_COLUMN_NAME = "pname";
   public static final String CONTACTS_COLUMN_EMAIL = "pspec";
   public static final String CONTACTS_COLUMN_STREET = "pprice";
   public static final String CONTACTS_COLUMN_CITY = "pfeature";
   public static final String CONTACTS_COLUMN_PHONE = "pimage";

public DataBaseHandler(Context context) {
    super(context, DATABASE_NAME, null, 1);

    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

    db.execSQL("CREATE TABLE IF NOT EXISTS product(pimage BLOB,pid INTEGER PRIMARY KEY,pname TEXT,pprice NUMERIC,pspec TEXT,pfeature TEXT)");
    db.execSQL("INSERT INTO product(pimage,pname,pprice,pspec) VALUES('img[0]','Candle stick 1',4000,'Solar garden / pathway light,Solar Panel:1pc crystal silicon solar cell, Battery:1pc 1.2V Ni-MH/Ni-CD AA battery 600MA ,Material:Stainless steel ,WaterProof and safe ')");
    db.execSQL("INSERT INTO product(pimage,pname,pprice,pspec) VALUES('img[1]','Candle stick 3','4500','Solar garden / pathway light, Solar Panel:1pc crystal silicon solar cell, Battery:1pc 1.2V Ni-MH/Ni-CD AA battery 600MA, Material:Stainless steel, WaterProof and safe IP44 ')");
    db.execSQL("INSERT INTO product(pimage,pname,pprice,pspec) VALUES('img[2]','Candle stick 5',3500,'Solar garden / pathway light, Solar Panel:1pc crystal silicon solar cell, Battery:1pc 1.2V Ni-MH/Ni-CD AA battery 600MA, Material:Stainless steel, WaterProof and safe IP44 ')");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}

public void addEntry( byte[] image) throws SQLiteException{
    SQLiteDatabase db = getWritableDatabase(); 
    ContentValues cv = new  ContentValues();
    cv.put("pimage",   image);
    db.insert( "product", null, cv );
}

public void addEntries(byte[][] img) {
    for(int j = 0 ; j < img.length ; j++) 
        addEntry(img[j] );
}

}

您需要将解码的字节数组的长度传入decodeByteArray。您使用的是二维数组,您需要指定包含图像的字节数组的长度,而不是字节数组的数组长度。

改变

Bitmap b1=BitmapFactory.decodeByteArray(img[j], 0, img.length);

Bitmap b1=BitmapFactory.decodeByteArray(img[j], 0, img[j].length);