简体   繁体   中英

How to display image in list view for an Android app from an already made database?

I want to display a product's name, image, desc, category and price through list view. Everything is displayed except the image because I don't know how to. These are my codes:

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 //database

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

For the line

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

it won't work and keeps on generating errors. I'm asking for any alternatives. The error says it can't work for bytes. May I ask what code should I replace that line in order for my image to display?

Use Picasso or Glide library for this-:

Compile this in your build.gradle

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

Implement this code in your Adapter Area-:

 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

Use BLOB type column to store image in your table. so first you have to convert image file to byte array to store into table when you retrieve image back from table you a byte now you have to convert it back to image file.

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

Here is the code to convert bitmap to base64 string.

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

And here is the code to convert base64 to bitmap.

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

In your code copy this getBitmap method and call it like this.

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

EDIT: I updated my answer as per your requirement. I also provided a example call, You just need to pass your byte value as an argument to the method.

I used these codes and finally retrieved the images.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM