从sqlite数据库检索图像并在listview中显示

7dl7o3gd  于 2021-07-12  发布在  Java
关注(0)|答案(3)|浏览(426)

被一个问题困住了。我是android开发的新手。我的问题是我有一个sqlite数据库,我在其中保存图像和一些数据,但当我检索数据时,图像不会显示在listview中。其他数据正在显示。
这是我的自定义列表布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/petImageView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="5dp"
        android:layout_marginTop="0dp"
        android:src="@drawable/cat1"/>

    <TextView
        android:id="@+id/petNameTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="22dp"
        android:layout_marginRight="50dp"
        android:layout_toEndOf="@id/petImageView"
        android:layout_toRightOf="@id/petImageView"
        android:background="@android:color/background_light"
        android:textAlignment="center"
        android:textSize="35sp"
        android:textStyle="bold" />

    </RelativeLayout>

这是我的自定义适配器

public class CustomAdapter extends BaseAdapter {

private int layout;
private ArrayList<DataList> recordList;
private Context context;

public CustomAdapter(Context context, int layout, ArrayList<DataList> recordList) {
    this.context = context;
    this.recordList = recordList;
    this.layout=layout;
}

public int getCount() {
    return recordList.size();
}

public Object getItem(int position) {
    return recordList.get(position);
}

public long getItemId(int position) {
    return position;
}

private class ViewHolder{

    ImageView petImageView;
    TextView petNameTextView;
}

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

    View v = convertView;
    ViewHolder holder = new ViewHolder();
    if (v == null) {
        LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = layoutInflater.inflate(layout, null);
        holder.petImageView =  v.findViewById(R.id.petImageView);
        holder.petNameTextView = v.findViewById(R.id.petNameTextView);
        v.setTag(holder);
    }else{
        holder = (ViewHolder)v.getTag();
    }

    DataList datalist = recordList.get(position);
    holder.petNameTextView.setText(datalist.getName());

    byte[] recordImage = datalist.getImage();
    Bitmap bitmap = BitmapFactory.decodeByteArray(recordImage, 0, recordImage.length);
    holder.petImageView.setImageBitmap(bitmap);

    return v;
}

}
这就是活动

public class myPetsActivity extends AppCompatActivity {

ListView myPetList;
ArrayList<DataList> petList = new ArrayList<DataList>();
CustomAdapter customAdapter;
ImageView petImageView;
DatabaseHelper mDatabaseHelper;

String name;
byte[] image;
int id;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_pets);

    myPetList = findViewById(R.id.petsListView);
    petList = new ArrayList<>();
    customAdapter = new CustomAdapter(this, R.layout.custom_list_layout, petList);
    myPetList.setAdapter(customAdapter);

    mDatabaseHelper = new DatabaseHelper(this);

    Cursor data = mDatabaseHelper.getData("SELECT * FROM pet_table");
    petList.clear();
    while(data.moveToNext()) {

        id = data.getInt(0);
        name = data.getString(1);
        image = data.getBlob(2);

        petList.add(new DataList(id, name, image));
        Log.i("image",String.valueOf(image));
    }
    customAdapter.notifyDataSetChanged();
    }
    }

这是数据表

public class DataList {

private int id;
private byte[] image ;
private String name;

public DataList(int id, String name, byte[] image){

    this.id=id;
    this.name=name;
    this.image=image;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public byte[] getImage() {
    return image;
}

public void setImage(byte[] image) {
    this.image = image;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}
gojuced7

gojuced71#

尝试使用recyclerview而不是listview,后者已被弃用:developer.android.com/guide/topics/ui/layout/recyclerview如果显示的是图像,而不是正确的图像,则它可能在适配器代码中。
您也可以在while循环之后示例化适配器。
删除这行代码:

View v = convertView;

在java中,将对象分配给其他对象并不意味着它们是同一个对象,它们只是指向内存中的同一个引用。java对待原始对象和其他对象有些不同。
遵循以下示例:https://www.javacodegeeks.com/2013/09/android-viewholder-pattern-example.html

7uzetpgm

7uzetpgm2#

您是否考虑过将图像作为字符串保存到数据库(base64)?在从db读取它之后,简单地将它转换回来。这里有一些方法:如何将捕获的图像或从gallary中选择的图像转换为base64?

deyfvvtc

deyfvvtc3#

如图所示,代码本质上没有任何问题。因此,问题可能在于将图像存储到数据库中。
注意:请参阅有关在数据库中存储图像的注解。

工作示例

下面的工作示例,只对代码做了一些小的更改,然后实际上只提供了一些建议(一个例外是mypetsactivity被命名为mypetsactivity以遵循常见约定)。但是,databasehelper.java是完整编写的,可能不会完全反映databasehelper.java
一个不同之处是,图像本身已被放置到assets文件夹中,并从该文件夹中检索以存储到petètable表中请参见databasehelper.java类中的addpetwithimagefromsassets方法。
另一个区别是,上面的方法已经被用来用一些测试数据填充数据库(请参阅mypetsactivity.java中的addsomedata方法)。名为mr.invisible pet的宠物的一行被赋予了一个不存在的图像(这将导致blob使用图像的默认值x'00',这很好,因为它不显示)。
custom_list_layout.xml已删除不必要的relativelayout(如果未删除它,它仍然有效)。为了适合我的测试(使用android4.1.1设备),它还添加了marginleft和alignparentleft两个属性。

图像

我刚刚将一些小的可用jpg图像复制到assets文件夹中,如下所示:-

注意名字是相关的,实际的图像不是(正如我所说的,只是一些我躺在周围的照片)

代码

数据库助手.java

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mypets.db";
    public static final int DBVERSION = 1;
    public static final String TABLE_PET = "pet_table";
    public static final String COLUMN_PET_ID = BaseColumns._ID;
    public static final String COLUMN_PET_NAME = "name";
    public static final String COLUMN_PET_IMAGE = "image";
    public static final String COLUMN_PET_IMAGEPATH = "imagepath";

    SQLiteDatabase mDB;
    Context mContext;

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        String crt_pet_table = "CREATE TABLE IF NOT EXISTS " + TABLE_PET + "(" +
                COLUMN_PET_ID + " INTEGER PRIMARY KEY, " +
                COLUMN_PET_NAME + " TEXT," +
                COLUMN_PET_IMAGE + " BLOB DEFAULT x'00'," +
                COLUMN_PET_IMAGEPATH + " TEXT DEFAULT ''" +
                ")";
        db.execSQL(crt_pet_table);
    }

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

    /**
     * NOT USED
     * @param petname
     * @return
     */
    public long addPet(String petname) {
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_PET_NAME,petname);
        return mDB.insert(TABLE_PET,null,cv);
    }

    public long addPetWithImageFromAssets(String petname, String petimagename)  {
        byte[] petimage = new byte[0];
        int image_size = 0;

        try {
            InputStream is = mContext.getAssets().open(petimagename);
            image_size = is.available();
            petimage = new byte[image_size];
            is.read(petimage);
            is.close();

        } catch (IOException e) {
        }
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_PET_NAME,petname);
        if (image_size > 0) {
            cv.put(COLUMN_PET_IMAGE,petimage);
        }
        return mDB.insert(TABLE_PET,null,cv);
    }

    public Cursor getData(String query) {
        return mDB.rawQuery(query,null);
    }
}

注意!!!你必须调整上述内容以适应。
数据列表.java

public class DataList {

    /**
     * NOTE changed id to use long rather than int
     */

    private long id;
    private byte[] image ;
    private String name;

    public DataList(int id, String name, byte[] image){

        this.id=id;
        this.name=name;
        this.image=image;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

这只被更改为对id使用long,因为如果有成千上万的行,int可能太小。
mypetsactivity.java文件

public class MyPetsActivity extends AppCompatActivity {

    ListView myPetList;
    ArrayList<DataList> petList = new ArrayList<DataList>();
    CustomAdapter customAdapter;
    ImageView petImageView;
    DatabaseHelper mDatabaseHelper;

    String name;
    byte[] image;
    int id;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_pets);

        myPetList = findViewById(R.id.petsListView);
        petList = new ArrayList<>();
        customAdapter = new CustomAdapter(this, R.layout.custom_list_layout, petList);
        myPetList.setAdapter(customAdapter);

        mDatabaseHelper = new DatabaseHelper(this);
        addSomeData(); //<<<<<<<<<< FOR DEMO

        Cursor data = mDatabaseHelper.getData("SELECT * FROM pet_table");
        petList.clear();
        while(data.moveToNext()) {

            id = data.getInt(0);
            name = data.getString(1);
            image = data.getBlob(2);

            petList.add(new DataList(id, name, image));
            Log.i("image",String.valueOf(image));
        }
        data.close(); //<<<<<<<<<< SHOULD ALWAYS CLOSE CURSOR WHEN DONE WITH IT
        customAdapter.notifyDataSetChanged();
    }

    private void addSomeData() {
        mDatabaseHelper.getWritableDatabase().delete(DatabaseHelper.TABLE_PET,null,null); //<<<<<<<<<< Delete all pets
        mDatabaseHelper.addPetWithImageFromAssets("Fluffy","mypet001.JPG");
        mDatabaseHelper.addPetWithImageFromAssets("Not Fluffy","mypet002.JPG");
        mDatabaseHelper.addPetWithImageFromAssets("Petty","mypet003.JPG");
        mDatabaseHelper.addPetWithImageFromAssets("Mr. Invisible Pet","noimageforthispet"); //<<<<<<< ooops!!!!!
    }
}

注意,添加addsomedata方法是为了加载一些测试数据,包括图像(除了添加的最后一行命名不存在的图像文件(asset))。
自定义适配器.java
不变。
活动\u my\u pets.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"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    <ListView
        android:id="@+id/petsListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>
</LinearLayout>

自定义\列表\布局.xml
微小的、无关紧要的变化

<TextView
    android:id="@+id/petNameTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="50dp"
    android:layout_marginTop="22dp"
    android:layout_marginRight="50dp"
    android:layout_toEndOf="@id/petImageView"
    android:layout_toRightOf="@id/petImageView"
    android:background="@android:color/background_light"
    android:textAlignment="center"
    android:textSize="35sp"
    android:textStyle="bold" />

结果

相关问题