我想将Image保存为sqlite的路径并检索它,然后在ImageView上显示

时间:2018-11-03 15:05:40

标签: java android sqlite

这是我的代码:

public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (resultCode != RESULT_OK) {
        return;
    }
    ImageButton imageButton = (ImageButton) textEntryView.findViewById(R.id.imageButton);
    imageUri = data.getData();
    showToast(imageUri.getPath());
  1. 我是否正确准备在吐司面包上显示图像路径?

这是另外一个要显示在ImageView上的图片:

public void setIvImg(String path) {
    this.ivImg.setImageURI(Uri.fromFile(new File(path)));
}
  1. 我可以在ImageView上显示图像吗?

PS:我已经使用了READ_EXTERNAL_STORAGE权限。

1 个答案:

答案 0 :(得分:0)

下面是一个示例,该示例将路径存储在名为image_path的表的数据库(名为itdb)中,该表每行具有两列 _id rowid 的别名,因此唯一地标识一行为长)和 image_path ,用于图像文件的实际路径。

在此示例中,为简单起见(无需权限),将图像(一些JPG)拖放到了资产文件夹中。

该应用程序在启动时会查看资产并存储包含.JPG的资产文件路径(此处没有任何花哨的地方)。 loadImagePaths方法可以做到这一点。

  • 请注意,由于 image_path 列已使用UNIQUE约束进行定义,因此现有图像将被忽略(尽管会将异常写入日志)。

然后,handleListView将通过Cursor从表中提取行,该Cursor是附加到ListView的SimpleCursorAdapter的源数据。设置了两个侦听器:-

  • 一个用于 onItemClick 的对象,它会填充ImageView。
  • 另一个用于 onItemLongClick ,它将从数据库中删除条目,然后刷新ListView。 (运行该应用程序会将所有已删除的图像路径添加到数据库中。)

具有4个文件:-

  • MyEnlighten20180927_Consumption.JPG
  • MyEnlighten20180927_Overview.JPG
  • MyEnlighten20180927_Production.JPG
  • MyEnlighten20180927_ProductionGridView.JPG

该应用程序看起来像在启动时(未单击任何项​​目):-

enter image description here

单击一个项目会导致显示图像,例如:-

enter image description here

该应用程序包含3个组件,布局 activity_main.xml ,DatabaseHelper DatabaseHelper.java 和Activity MainActivity.java

activity_main.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#FFAAAAFF"
        />

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#FFAAFFAA"
        />

</LinearLayout>

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DBNAME = "itdb";
    public static final int DBVERSION = 1;

    public static final String TBNAME = "image_path";
    public static final String IMAGEPATH_COL_ID = BaseColumns._ID;
    public static final String IMAGEPATH_COL_PATH = "image_path";

    SQLiteDatabase mDB;

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

    @Override
    public void onCreate(SQLiteDatabase db) {

        String crt_imagepath_table = "CREATE TABLE IF NOT EXISTS " + TBNAME + "(" +
                IMAGEPATH_COL_ID + " INTEGER PRIMARY KEY, " +
                IMAGEPATH_COL_PATH + " TEXT UNIQUE" +
                ")";
        db.execSQL(crt_imagepath_table);
    }

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

    }

    public long addImagePath(String imagePath) {
        ContentValues cv = new ContentValues();
        cv.put(IMAGEPATH_COL_PATH,imagePath);
        return mDB.insert(TBNAME,null,cv);
    }

    public int deleteImagePathById(long id) {
        String whereclause = IMAGEPATH_COL_ID + "=?";
        String[] whereargs = new String[]{String.valueOf(id)};
        return mDB.delete(TBNAME,whereclause,whereargs);
    }

    public Cursor getImageList() {
        return mDB.query(TBNAME,null,null,null,null,null,null);
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    String[] mAssetList;
    String mPath = "" ;
    String mImageExtension = ".JPG";
    ListView mLV;
    ImageView mIV;

    DatabaseHelper mDBHlpr;
    Cursor mCsr;
    SimpleCursorAdapter mSCA;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLV = this.findViewById(R.id.listview);
        mIV = this.findViewById(R.id.imageview);

        mDBHlpr = new DatabaseHelper(this);
        loadImagePaths();
        handleListView();
    }

    /**
     * Handle displaying the ListView, initialising it or refreshing it
     *
     * When initialising the
     */
    private void handleListView() {
        mCsr = mDBHlpr.getImageList();
        if (mSCA == null) {
            mSCA = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_1,mCsr,
                    new String[]{DatabaseHelper.IMAGEPATH_COL_PATH},
                    new int[]{android.R.id.text1},
                    0
            );
            mLV.setAdapter(mSCA);
            mLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    displayImage(mCsr.getString(mCsr.getColumnIndex(DatabaseHelper.IMAGEPATH_COL_PATH)));
                }
            });
            mLV.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                    mDBHlpr.deleteImagePathById(l);
                    handleListView(); // Refresh Listview as underlying image path has been deleted
                    return true; // indicate event has been handled
                }
            });
        } else {
            mSCA.swapCursor(mCsr);
        }
    }

    @Override
    protected void onDestroy() {
        mCsr.close();
        super.onDestroy();
    }

    private void displayImage(String imagepath) {
        InputStream is = null;
        try {
            is = this.getResources().getAssets().open(imagepath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Bitmap image = BitmapFactory.decodeStream(is);
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mIV.setImageBitmap(image);
    }

    private void loadImagePaths() {
        try {
            mAssetList = this.getAssets().list(mPath);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        for (String s: mAssetList) {
            if (s.contains(mImageExtension)) {
                mDBHlpr.addImagePath(s);
            }
        }
    }
}

这演示了使用图像及其路径存储在数据库中的基本知识。

  • 请注意,如果使用上述格式,则必须将某些扩展名为JPG的文件复制到资产文件夹中(除非更改了代码以处理其他位置)。