如何在已经建立的数据库中显示Android应用程序的列表视图中的图像?

时间:2018-01-05 03:27:19

标签: java android image listview bitmap

我想通过列表视图显示产品的名称,图像,设计,类别和价格。除了图像之外,所有内容都会显示,因为我不知道如何操作。这些是我的代码:

MainActivity.java

public class CLARTIPS_Home extends AppCompatActivity {

    private ListView lvProduct;
    private ListProductAdapter adapter;
    private List<Product> mProductList;
    private DatabaseHelper mDBHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clartips__home);

        lvProduct = (ListView) findViewById(R.id.listview_product);
        mDBHelper = new DatabaseHelper(this);

        //Button tryMe = (Button) findViewById(R.id.tryMe);

        //Check exists database
        File database = getApplicationContext().getDatabasePath(DatabaseHelper.DBNAME);
        if(false==database.exists()) {
            mDBHelper.getReadableDatabase();
            //Copy db
            if (copyDatabase(this)) {
                Toast.makeText(this, "Success Copying Database", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Error Copying Database", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        //Get product list in db when db exists
        mProductList = mDBHelper.getListProduct();
        //Init adapter
        adapter = new ListProductAdapter(this,mProductList);
        //Set adapter for listview
        lvProduct.setAdapter(adapter);
    }

    private boolean copyDatabase(Context context) {
        try {
            InputStream inputStream = context.getAssets().open(DatabaseHelper.DBNAME);
            String outFileName = DatabaseHelper.DBLOCATION + DatabaseHelper.DBNAME;
            OutputStream outputStream = new FileOutputStream(outFileName);
            byte[]buff = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buff)) > 0) {
                outputStream.write(buff, 0, length);
            }
            outputStream.flush();
            outputStream.close();
            Log.w("MainActivity","DB copied");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

DatabaseHelper.java //数据库

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DBNAME = "sample.sqlite";
    public static final String DBLOCATION = "/data/data/nerds.thesis.clartips/databases/";
    private Context mContext;
    private SQLiteDatabase mDatabase;

    public DatabaseHelper(Context context) {
        super(context, DBNAME, null, 1);
        this.mContext = context;
    }

    public DatabaseHelper(Context context) {
        super(context, DBNAME, null, 1);
        this.mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void openDatabase() {
        String dbPath = mContext.getDatabasePath(DBNAME).getPath();
        if(mDatabase != null && mDatabase.isOpen()) {
            return;
        }
        mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    public void closeDatabase() {
        if(mDatabase!=null) {
            mDatabase.close();
        }
    }

    public List<Product> getListProduct() {
        Product product = null;
        List<Product> productList = new ArrayList<>();
        openDatabase();
        Cursor cursor = mDatabase.rawQuery("SELECT * FROM PRODUCT", null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            product = new Product(cursor.getInt(0), cursor.getString(1), cursor.getBlob(2), cursor.getInt(3), cursor.getString(4), cursor.getString(5));
            productList.add(product);
            cursor.moveToNext();
        }
        cursor.close();
        closeDatabase();
        return productList;
    }
}

ListViewAdapter.java // adapter

public class ListProductAdapter extends BaseAdapter {
    private Context mContext;
    private List<Product> mProductList;

    public ListProductAdapter(Context mContext, List<Product> mProductList) {
        this.mContext = mContext;
        this.mProductList = mProductList;
    }

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

    @Override
    public Object getItem(int position) {
        return mProductList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return mProductList.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = View.inflate(mContext, R.layout.listview, null);
        TextView pName = (TextView)v.findViewById(R.id.product_name);
        ImageView pImage = (ImageView)v.findViewById(R.id.product_image);
        TextView pPrice = (TextView)v.findViewById(R.id.product_price);
        TextView pDescription = (TextView)v.findViewById(R.id.product_description);
        TextView pCategory = (TextView)v.findViewById(R.id.product_category);
        pName.setText(mProductList.get(position).getName());

        **//pImage.setImageBitmap(mProductList.get(position).getImage());**

        pPrice.setText("$" + String.valueOf(mProductList.get(position).getPrice()));
        pDescription.setText(mProductList.get(position).getDescription());
        pCategory.setText(mProductList.get(position).getCategory());
        return v;
    }
}

Product.java // model

public class Product{
    private int id;
    private String name;
    private byte image;
    private int price;
    private String description;
    private String category;

    public Product(int id, String name, byte image, int price, String description, String category) {
        this.id = id;
        this.name = name;
        this.image = image;
        this.price = price;
        this.description = description;
        this.category = category;
     }

    public int getId(){
        return id;
    }

    public String getName(){
        return name;
    }

    public byte getImage(){
        return image;
    }

    public int getPrice(){
        return price;
    }

    public String getDescription(){
        return description;
    }

    public String getCategory(){
        return category;
    }
}

对于

**//pImage.setImageBitmap(mProductList.get(position).getImage());**

它将无法正常工作并继续产生错误。我要求任何替代方案。该错误表明它无法用于字节。请问我应该用哪些代码替换该行以显示我的图像?

4 个答案:

答案 0 :(得分:0)

使用Picasso或Glide库 - :

在build.gradle中编译它

compile 'com.squareup.picasso:picasso:2.5.2'

在适配器区域中实现此代码 - :

 if (mProductList.get(position).getImage().length() > 0)
                Picasso.with(context).load(mProductList.get(position).getImage()).placeholder(R.mipmap.ic_other_health_issues).into(holder.disease_image);
            else
                holder.disease_image.setImageResource(R.mipmap.ic_other_health_issues);  //your default image

答案 1 :(得分:0)

使用BLOB类型列将图像存储在表格中。 所以首先你必须将图像文件转换为byte数组以存储到表中,当你从表中检索图像时byte现在你必须将它转换回图像文件。

 public byte[] convetBitmapToByteArray(Bitmap bm)
{
    int size = bm.getRowBytes() * bm.getHeight();
    ByteBuffer byteBuffer = ByteBuffer.allocate(size);
    bm.copyPixelsToBuffer(byteBuffer);
   return byteBuffer.array();
}
public Bitmap convertByteToBitmap(byte[] evidence)
{
    Bitmap bmp= BitmapFactory.decodeByteArray(evidence, 0, evidence.length);
    return bmp;
}

答案 2 :(得分:0)

以下是将位图转换为base64字符串的代码。

    Bitmap bitmap=Your Bitmap;
    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG,90,stream);
    byte[] bytes=stream.toByteArray();

以下是将base64转换为位图的代码。

    public Bitmap getBitmap(byte[] decodedString){
        Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        return decodedBitmap;
    }

在你的代码中复制这个getBitmap方法并像这样调用它。

pImage.setImageBitmap(getBitmap(your byte value of image from database));

修改 我按照你的要求更新了我的答案。我还提供了一个示例调用,您只需要将您的字节值作为参数传递给方法。

答案 3 :(得分:0)

我使用这些代码并最终检索图像。

byte[] img = image.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
pImage.setImageBitmap(bitmap);