已经往数据库插入图片了,现在可以去除图片了,这里我用的是游标
package 你的包名;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import com.example.garden.database.Mydb;
public class SearchResult extends AppCompatActivity implements AdapterView.OnItemClickListener {
//定义游标
private Cursor cursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
Intent rit = getIntent();
String text = rit.getStringExtra("key");
ListView listview=findViewById(R.id.listview);
//帮助器和管理器两个老朋友了,实例化数据库对象
SQLiteOpenHelper helper=new Mydb(this);
SQLiteDatabase db=helper.getWritableDatabase();
//游标读取数据库
cursor=db.rawQuery("select * from KNOW where name like '%"+text+"%'",null);
cursor.moveToFirst();
//数据库的简单游标适配器,简单来说就是往模板填充内容的一个桥梁
SimpleCursorAdapter mAdapter=new SimpleCursorAdapter(this,R.layout.item_list,
cursor,new String[]{"NAME","image","TITLE"},new int[]{R.id.iv1,R.id.iv2,R.id.iv3},0);//自己的xml组件名R.id.iv1,R.id.iv2,R.id.iv3与数据库字段名"NAME","image","TITLE"对应,更多用法自己查
//仅仅是上面的简单游标适配器是不能读取图片的,重点来了,此处用到了ViewBinder
SimpleCursorAdapter.ViewBinder binder=new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
//判断是否是ImageView,这个判断非常关键,详细可以按ctr去查找ViewBinder,就去文档看,不要找其他资料,如果想真的搞懂一定要看!
if (view instanceof ImageView) {
ImageView imageView = (ImageView) view;
imageView.setImageBitmap(readImageFromDb(cursor.getString(cursor.getColumnIndex("_id"))));//为imageView配置id所对应的图片
return true;
}
return false;
}
};
//配置ViewBinder
mAdapter.setViewBinder(binder);
//配置适配器
listview.setAdapter(mAdapter);
//点击监听器
listview.setOnItemClickListener(this);
}
//
@SuppressLint("Range")
private Bitmap readImage(String id) {
//至于为什么又要实例化,是因为sqlite不能同时使用,术语不专业,总之要重新实例化,不然会报错
Mysql mySqlLite2 = new Mysql(this);
SQLiteDatabase database2 = mySqlLite2.getReadableDatabase();
Bitmap image= null;
byte[] bytes;
Cursor cursor = database2.rawQuery( "SELECT * FROM INFORMATION WHERE _id = ?", new String[]{id});
if (cursor.moveToFirst()) {
if ((bytes = cursor.getBlob(cursor.getColumnIndex("image"))) != null) {
image= BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
}
cursor.close();
return image;
}
//listview的点击事件
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//此处写点击事件,我用来传值以及跳转页面
Intent it=new Intent(this, Show.class);
it.putExtra("ID",(int)id-1);
startActivity(it);
finish();
}
}