【问题标题】:How to display image in list view for an Android app from an already made database?如何在列表视图中显示来自已创建数据库的 Android 应用程序的图像?
【发布时间】:2018-01-05 03:27:18
【问题描述】:

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

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 //适配器

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 //模型

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());**

它不起作用并不断产生错误。我正在寻求任何替代方案。该错误表示它不适用于字节。请问我应该用什么代码替换该行才能显示我的图像?

【问题讨论】:

  • 也许是private byte[] image;? (以及所有其他提到 byte 的地方)。
  • 我已经找到了答案:)

标签: java android image listview bitmap


【解决方案1】:

为此使用 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

【讨论】:

  • 除了使用 Picasso/Glide 还有其他选择吗?
  • 是的,您可以使用圆形 imagview。
  • 您能详细说明一下吗?
【解决方案2】:

使用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;
}

【讨论】:

  • 是的,我在数据库中为我的图像使用了 blob 数据类型。我可以知道(仅当您愿意帮助我时)用于将图像文件转换为字节数组的代码,反之亦然,因为我很难在网上找到任何代码。非常感谢!
  • 向表中插入数据时调用convetBitmapToByteArray,从表中检索数据时调用convertByteToBitmap
  • 真的很抱歉,我现在可能看起来很笨,但你能告诉我显示图像的实际代码(放在哪里,调用什么),因为我真的很困惑 T_T跨度>
【解决方案3】:

这是将位图转换为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));

编辑: 我根据您的要求更新了我的答案。我还提供了一个示例调用,您只需将字节值作为参数传递给方法。

【讨论】:

  • 对不起,为什么我必须将位图转换为字符串?我来自数据库的图像是 BLOB 类型。我对此很陌生,所以请耐心等待。
  • 您能告诉我您将图像放入数据库的代码吗?我可以帮你。
  • 您从 blob 获取的数据应该是 base64 字符串,因此您已经获得了编码格式的字符串。如果您以其他形式存储它,我将查看您的代码,并为您提供帮助,以便向我展示您的图像存储代码。
  • 为了存储,我通过数据库浏览器预先制作了数据库。然后,我把它放在我的资产文件夹中。代码请稍等。
  • 对于代码,我编辑了帖子并为 MainActivity.java 添加了代码。
【解决方案4】:

我用了这些代码,终于找回了图片。

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

【讨论】:

  • 也许是byte[] img = product.getImage(); ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多