2017-02-11 6 views
0

Я работаю над небольшим проектом. Я вставил файл базы данных .sqlite в папку с ресурсами и получив информацию в списке. Теперь мне нужно отображать изображение с текстом. Я создал изображение в xml-файле, а затем добавлю некоторые функции в свой код. Но это не сработает. Вот источник.Показать изображение из sqlite в listview?

MainActivity.java

package com.example.arlequina.sqlitefromassetexample; 
import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.ListView; 
import android.widget.Toast; 
import com.example.arlequina.sqlitefromassetexample.adapter.ListProductAdapter; 
import com.example.arlequina.sqlitefromassetexample.database.DatabaseHelper; 
import com.example.arlequina.sqlitefromassetexample.model.Product; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.List; 
/** 
* Created by ARLEQUINA on 2/10/2017. 
*/ 
public class MainActivity extends Activity { 
    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_main); 
     lvProduct = (ListView)findViewById(R.id.listview_product); 
     mDBHelper = new DatabaseHelper(this); 

     //Check exists database 
     File database = getApplicationContext().getDatabasePath(DatabaseHelper.dbname); 
     if(false == database.exists()){ 
      mDBHelper.getReadableDatabase(); 

      //Copy db 
      if(copyDatabase(this)){ 
       Toast.makeText(this,"Copy database success", Toast.LENGTH_SHORT).show(); 
      }else{ 
       Toast.makeText(this, "Copy data error", 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.v("MainActivity", "DB copied"); 
      return true; 
     } catch(Exception e){ 
      e.printStackTrace(); 
      return false; 
     } 
    } 
} 

Product.java

package com.example.arlequina.sqlitefromassetexample.model; 

import java.sql.Blob; 

/** 
* Created by ARLEQUINA on 2/10/2017. 
*/ 

public class Product { 

    private int id; 
    private String name; 
    private String price; 
    private String desc; 
    private Blob img; 

    public Product(int id, String name, String price, String desc, Blob img){ 
     this.id = id; 
     this.name = name; 
     this.price = price; 
     this.desc = desc; 
     this.img = img; 
    } 

    public int getId(){ 
     return id; 
    } 
    public void setId(int id){ 
     this.id = id; 
    } 
    public String getName(){ 
     return name; 
    } 
    public void setName(String name){ 
     this.name = name; 
    } 
    public String getPrice(){ 
     return price; 
    } 
    public void setPrice(String price){ 
     this.price = price; 
    } 
    public String getDesc(){ 
     return desc; 
    } 
    public void setDesc(){ 
     this.desc = desc; 
    } 
    public Blob getImage(){ 
     return img; 
    } 
    public void setImage(Blob img){ 
     this.img = img; 
    } 
} 

DatabaseHelper.java

package com.example.arlequina.sqlitefromassetexample.database; 

import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 

import com.example.arlequina.sqlitefromassetexample.model.Product; 

import java.util.ArrayList; 
import java.util.List; 
import java.sql.Blob; 

/** 
* Created by ARLEQUINA on 2/10/2017. 
*/ 

public class DatabaseHelper extends SQLiteOpenHelper { 
    public static final String dbname = "sample.db"; 
    public static final String dblocation = "/data/data/com.example.arlequina.sqlitefromassetexample/databases/"; 
    private Context mContext; 
    private SQLiteDatabase mDatabase; 

    public DatabaseHelper(Context context){ 
     super(context, dbname, null, 1); 
     this.mContext = context; 
    } 
    @Override 
    public void onCreate(SQLiteDatabase sqLiteDatabase) { 

    } 

    @Override 
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { 

    } 
    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.getString(2),cursor.getString(3),cursor.getBlob(4)); 
      productList.add(product); 
      cursor.moveToNext(); 
     } 
     cursor.close(); 
     closeDatabase(); 
     return productList; 
    } 
} 

ListProductAdapter.java

package com.example.arlequina.sqlitefromassetexample.adapter; 

import android.content.Context; 
import android.os.Build; 
import android.support.annotation.RequiresApi; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.ImageView; 
import android.widget.TextView; 

import com.example.arlequina.sqlitefromassetexample.R; 
import com.example.arlequina.sqlitefromassetexample.model.Product; 

import org.w3c.dom.Text; 

import java.util.List; 

/** 
* Created by ARLEQUINA on 2/10/2017. 
*/ 

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

    @RequiresApi(api = Build.VERSION_CODES.M) 
    @Override 
    public View getView(int position, View view, ViewGroup viewGroup) { 
     View v = View.inflate(mContext, R.layout.item_listview, null); 
     TextView tvName = (TextView)v.findViewById(R.id.tv_product_name); 
     TextView tvPrice = (TextView)v.findViewById(R.id.tv_product_price); 
     TextView tvDesc = (TextView)v.findViewById(R.id.tv_product_desc); 
     ImageView tvImage = (ImageView)v.findViewById(R.id.tv_product_img); 
     tvName.setText(mProductList.get(position).getName()); 
     tvPrice.setText(String.valueOf(mProductList.get(position).getPrice()) + " $"); 
     tvDesc.setText(mProductList.get(position).getDesc()); 
     // tvImage.setImageIcon(mProductList.get(position).getImage()); 
     return v; 
    } 
} 

item_listview.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#ffffff" 
    android:paddingBottom="5dp" 
    android:paddingLeft="10dp" 
    android:paddingRight="10dp" 
    android:paddingTop="5dp"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/tv_product_name" 
     android:text = "Name" 
     android:textColor="#4bb6d6" 
     android:textSize="20dp"/> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id = "@+id/tv_product_price" 
     android:text="100$" 
     android:textColor="#b30000" 
     android:textSize="18dp"/> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id = "@+id/tv_product_desc" 
     android:text="Description" 
     android:textSize="16dp" 
     android:textStyle="italic"/> 
    <ImageView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id = "@+id/tv_product_img" 
     android:layout_gravity="right" 
     android:paddingRight="10dp" 
     android:paddingBottom="10dp"/> 
</LinearLayout> 

activity_main.xml

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

    <ListView 
     android:id = "@+id/listview_product" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_marginLeft="10dp" 
     android:layout_marginTop="10dp" 
     android:divider="#d1d1d1" 
     android:dividerHeight="10dp"></ListView> 
</LinearLayout> 

А вот образ SQLite базы данных прикрепленного файла изображения. enter image description here

Адрес источника базы данных. имя базы данных - «образец» и продукт таблицы.

CREATE TABLE `Product` (
    `ID` INTEGER PRIMARY KEY AUTOINCREMENT, 
    `Name` TEXT, 
    `Price` TEXT, 
    `Desc` TEXT, 
    `Image` BLOB 
); 
+1

Я думаю, что хранение изображения в БД является идеей _bad_, вместо этого сохраняйте изображение в другом месте и сохраняйте относительный путь к этому изображению вместе с именем изображения в хранилище SQLite. – Shashanth

ответ

0

cursor.getBlob() возвращает байт [] массив, использовать метод BitmapFactory.decodeByteArray(), чтобы преобразовать массив байтов в изображение. В вашем Product.java измените тип img с Blob на байт []. Вот официальная документация a link.