简体   繁体   English

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

[英]I would like to save Image as path to sqlite and retrieve it then show on ImageView

Here is my code:这是我的代码:

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. Am I correct about to get the Image Path shown on the Toast?我是否正确获取 Toast 上显示的图像路径?

Here is another one to show on ImageView:这是在 ImageView 上显示的另一个:

public void setIvImg(String path) {
    this.ivImg.setImageURI(Uri.fromFile(new File(path)));
}
  1. Am I correct about showing the image on ImageView?我在 ImageView 上显示图像是否正确?

PS: I already use READ_EXTERNAL_STORAGE permission. PS:我已经使用了READ_EXTERNAL_STORAGE权限。

Here's an example that stores the paths in the Database (named itdb) in the table named image_path that has two columns per row _id (an alias of the rowid , so uniquely identifies a row as a long) and image_path which is used for the actual path to the image file.这是一个示例,该示例将数据库(名为 itdb)中的路径存储在名为 image_path 的表中,该表每行有两列_idrowid的别名,因此唯一地将一行标识为 long)和image_path用于实际图像文件的路径。

In this example the images (a few JPG's) have been dropped into the assets folder for simplicity (no need for permissions).在这个例子中,为了简单起见(不需要权限),图像(一些 JPG)被放到了资产文件夹中。

The App when it starts looks at the assets and stores asset file paths that contain .JPG (not anything fancy here).应用程序在启动时会查看资产并存储包含 .JPG 的资产文件路径(这里没有任何花哨的东西)。 The loadImagePaths method does this. loadImagePaths 方法就是这样做的。

  • Note as the image_path column has been defined with the UNIQUE constraint existing images will be ignored (although an exception will be written to the log).请注意,因为image_path列已使用 UNIQUE 约束定义,现有图像将被忽略(尽管异常将写入日志)。

The handleListView will then extract the rows from the table via a Cursor which is the source data for the SimpleCursorAdapter that is attached to the ListView.然后 handleListView 将通过 Cursor 从表中提取行,该 Cursor 是附加到 ListView 的 SimpleCursorAdapter 的源数据。 Two listeners are set :-设置了两个侦听器:-

  • one for onItemClick , which populates the ImageView.一个用于onItemClick ,它填充 ImageView。
  • the other for onItemLongClick which will delete the entry from the database and then refresh the ListView.另一个用于onItemLongClick ,它将从数据库中删除条目,然后刷新 ListView。 (rerunning the App will add any deleted image paths to the database). (重新运行应用程序会将所有已删除的图像路径添加到数据库中)。

With 4 files :-有 4 个文件:-

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

The the App looks like, when started (no item has been clicked) :-该应用程序在启动时看起来像(没有单击任何项​​目):-

在此处输入图片说明

Clicking an item results in the image being displayed eg :-单击项目会导致显示图像,例如:-

在此处输入图片说明

The App consists of 3 components, the layout activity_main.xml , the DatabaseHelper DatabaseHelper.java and the Activity MainActivity.java该应用程序由 3 个组件组成,布局activity_main.xml 、 DatabaseHelper DatabaseHelper.java和 Activity MainActivity.java

activity_main.xml活动_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主活动.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);
            }
        }
    }
}

This demonstrates the basics of using images with their paths stored in the database.这演示了使用图像及其存储在数据库中的路径的基础知识。

  • Note if using the above then some files with a JPG extension would have to be copied into the assets folder (unless the code is changed to handle a different location).请注意,如果使用上述内容,则必须将一些带有 JPG 扩展名的文件复制到资产文件夹中(除非更改代码以处理不同的位置)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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