Показать реальный путь двух изображений, загруженных из хранилища в Android
Я делаю приложение, которое позволит пользователям загружать два изображения из хранилища в виде изображений вместе с их реальными путями. и позже, если пути одинаковы, в текстовом представлении отображаются "одинаковые изображения", а если нет, то отображаются "не похожие изображения". Ниже приведен код для этого,MainActivity.java
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private static final String TAG = "MainActivity";
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
findViewById(R.id.btnSelectImage).setOnClickListener(this);
}
boolean showingFirst = true;
public void generate(View view){
if(showingFirst){
Random vol = new Random();
int number = vol.nextInt(80 - 65) + 65;
TextView myText = (TextView)findViewById(R.id.tv);
String myString = String.valueOf(number);
myText.setText(myString);
showingFirst = false;
}else{
TextView myText = (TextView)findViewById(R.id.tv);
String myString = "same image";
myText.setText(myString);
showingFirst = true;
}
}
/* Choose an image from Gallery */
void openImageChooser() {
Intent intent = new Intent();
Intent intent1 = new Intent();
intent.setType("image/*");
intent1.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent1.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 101);// change request
startActivityForResult(Intent.createChooser(intent1, "Select Picture"), 102); // change request code
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 101) {
// Get the url from data
Uri selectedImageUri = data.getData();
String realPath = ImageFilePath.getPath(MainActivity.this, data.getData());
TextView editText = (TextView) findViewById(R.id.tv1);
editText.setText(realPath);
if ((null != selectedImageUri)) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
Log.i(TAG, "Image Path : " + path);
// Set the image in ImageView
((ImageView) findViewById(R.id.imgView)).setImageURI(selectedImageUri);
}
} else if (requestCode == 102) {
Uri selectedImageUri1 = data.getData();
String realPath = ImageFilePath.getPath(MainActivity.this, data.getData());
TextView editText = (TextView) findViewById(R.id.tv1);
editText.setText(realPath);
if ((null != selectedImageUri1)) {
// Get the path from the Uri
String path1 = getPathFromURI(selectedImageUri1);
Log.i(TAG, "Image Path : " + path1);
// Set the image in ImageView
((ImageView) findViewById(R.id.imgView2)).setImageURI(selectedImageUri1);
}
}
}
}
/* Get the real path from the URI */
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
@Override
public void onClick(View v) {
openImageChooser();
}
ImageFilePath.java
//import android.provider.<span id="IL_AD11"
class="IL_AD">MediaStore</span>;
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.KITKAT)
public class ImageFilePath {
/**
* Method for return file path of Gallery image
*
* @param context
* @param uri
* @return path of the selected image file from gallery
*/
static String nopath = "Select Video Only";
@TargetApi(Build.VERSION_CODES.KITKAT)
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
// check here to KITKAT or new version
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { split[1] };
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return nopath;
}
/**
* Get the value of the data column for this Uri. This is <span id="IL_AD2"
* class="IL_AD">useful</span> for MediaStore Uris, and other file-based
* ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @param selection
* (Optional) Filter used in the query.
* @param selectionArgs
* (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return nopath;
}
/**
* @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());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
}
}AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
но когда я запускаю это, я получаю сообщение об ошибке
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=11581, uid=10260 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
Пожалуйста, помогите, и ваши предложения приветствуются, спасибо.