如何获取图像路径(URI)并将其发送到数据库?

时间:2022-03-18 19:35:17

I have a code to get an image if I click the button, in my problem, I wanna get the URI/path of the image and send it into the database, after that I wanna show it in ImageView. And this is my code.

如果我点击按钮,我有一个代码来获取图像,在我的问题中,我想获取图像的URI /路径并将其发送到数据库,之后我想在ImageView中显示它。这是我的代码。

       @Override
public void onActivityResult(int req, int res, Intent imageIntent) {
    super.onActivityResult(req, res, imageIntent);

    switch (req) {
        case SELECT_ICON:
            if (res == RESULT_OK) {
                try {
                    final Uri iconUri = imageIntent.getData();
                    final String imgUri = iconUri.toString();
                    final InputStream iconStream = getContentResolver().openInputStream(iconUri);
                    final Bitmap selectedIcon = BitmapFactory.decodeStream(iconStream);
                    imageView.setImageBitmap(selectedIcon);

                    saveButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            String tname = text1.getText().toString();
                            String date = textView.getText().toString();
                            String priority = spinner1.getSelectedItem().toString();
                            String notes = text2.getText().toString();
                            String path = imgUri;

                            dbHelper.addTask(new Task(tname, date, priority, notes, path));
                            Toast.makeText(getApplicationContext(), "Success!!!", Toast.LENGTH_LONG).show();
                            TaskListActivity.tasklist.RefreshList();
                            finish();
                        }
                    });
                } catch (FileNotFoundException err) {
                    err.printStackTrace();
                }
            }
    }
}

2 个解决方案

#1


1  

You can use String strUri = uri.toString() to convert Uri to String save this strUri to database and while retrieving from database you can use Uri uri = Uri.parse(strUri) for converting string back to Uri

您可以使用String strUri = uri.toString()将Uri转换为String将此strUri保存到数据库,从数据库中检索时可以使用Uri uri = Uri.parse(strUri)将字符串转换回Uri

#2


0  

I used these methods to get path from URI

我使用这些方法从URI获取路径

private String getActualFilePath(Context context, Uri fileUri) throws URISyntaxException{
    Uri uri = Uri.parse(fileUri);
    final boolean needToCheckUri = Build.VERSION.SDK_INT >= 19;
    String selection = null;
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    // deal with different Uris.
    if (needToCheckUri && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            return Environment.getExternalStorageDirectory() + "/" + split[1];
        } else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            uri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
        } else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("image".equals(type)) {
                uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            selection = "_id=?";
            selectionArgs = new String[]{ split[1] };
        }
    }
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}
 /**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}
 private void LogException(Exception ex){
    if(ex != null){
        try{
            ex.printStackTrace(logPrintWriter);
            String data = logStringWriter.toString();

            AddErrorLogEntry(data);
        }finally {
            Log.d(TAG, "Logged exception in file");
        }
    }
 }

#1


1  

You can use String strUri = uri.toString() to convert Uri to String save this strUri to database and while retrieving from database you can use Uri uri = Uri.parse(strUri) for converting string back to Uri

您可以使用String strUri = uri.toString()将Uri转换为String将此strUri保存到数据库,从数据库中检索时可以使用Uri uri = Uri.parse(strUri)将字符串转换回Uri

#2


0  

I used these methods to get path from URI

我使用这些方法从URI获取路径

private String getActualFilePath(Context context, Uri fileUri) throws URISyntaxException{
    Uri uri = Uri.parse(fileUri);
    final boolean needToCheckUri = Build.VERSION.SDK_INT >= 19;
    String selection = null;
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    // deal with different Uris.
    if (needToCheckUri && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            return Environment.getExternalStorageDirectory() + "/" + split[1];
        } else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            uri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
        } else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("image".equals(type)) {
                uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            selection = "_id=?";
            selectionArgs = new String[]{ split[1] };
        }
    }
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}
 /**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}
 private void LogException(Exception ex){
    if(ex != null){
        try{
            ex.printStackTrace(logPrintWriter);
            String data = logStringWriter.toString();

            AddErrorLogEntry(data);
        }finally {
            Log.d(TAG, "Logged exception in file");
        }
    }
 }