2015-12-28 4 views
0

Я пытаюсь получить изображение из галереи на Android, но, к сожалению, оно не получилось с разрешения.Как получить изображение из галереи?

это мой код:

public void loadImagefromGallery(View view) { 
    // Create intent to Open Image applications like Gallery, Google Photos 
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, 
      android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
    // Start the Intent 
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    try { 
     // When an Image is picked 
     if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK 
       && null != data) { 
      // Get the Image from data 

      Uri selectedImage = data.getData(); 
      String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

      // Get the cursor 
      Cursor cursor = getContentResolver().query(selectedImage, 
        filePathColumn, null, null, null); 
      // Move to first row 
      cursor.moveToFirst(); 

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      Toast.makeText(this, "Image picked" + 
          columnIndex, 
        Toast.LENGTH_LONG).show(); 

     } else { 
      Toast.makeText(this, "You haven't picked Image", 
        Toast.LENGTH_LONG).show(); 
     } 
    } catch (Exception e) { 
     Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG) 
       .show(); 
     Log.d("ERROR",e.getMessage()); 
    } 

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.melas.app_3" > 

    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.CALL_PHONE" /> 
    <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 

    <application 
    android:name=".StartApps" 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/Theme.AppCompat.NoActionBar" > 
<meta-data 
    android:name="com.parse.APPLICATION_ID" 
    android:value="" /> 
<meta-data 
    android:name="com.parse.CLIENT_KEY" 
    android:value="" /> 

<activity 
    android:name=".MainActivity" 
    android:label="@string/app_name"> 
    <intent-filter> 
     <action android:name="android.intent.action.MAIN" /> 

     <category android:name="android.intent.category.LAUNCHER" /> 
    </intent-filter> 
</activity> 
<activity android:name=".Register" > 
</activity> 
<activity android:name=".Register2" > 
</activity> 
<activity android:name=".LoginActivity" > 
</activity> 

Ошибка:

12-28 15:15:07.100 1847-1859/android.process.media E/DatabaseUtils: Writing exception to parcel 
12-28 15:15:07.100 1847-1859/android.process.media E/DatabaseUtils: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/28 from pid=13141, uid=10060 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission() 
12-28 15:15:07.100 1847-1859/android.process.media E/DatabaseUtils:  at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:605) 
12-28 15:15:07.100 1847-1859/android.process.media E/DatabaseUtils:  at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:480) 
12-28 15:15:07.100 1847-1859/android.process.media E/DatabaseUtils:  at android.content.ContentProvider$Transport.query(ContentProvider.java:211) 
12-28 15:15:07.100 1847-1859/android.process.media E/DatabaseUtils:  at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112) 
12-28 15:15:07.100 1847-1859/android.process.media E/DatabaseUtils:  at android.os.Binder.execTransact(Binder.java:453) 
+0

размещает всю AndroidManifest.xml – Blackbelt

+0

у меня нет времени, чтобы увидеть код прямо сейчас проверить это «https: //github.com/crosswall/Android-PickPhotos " –

+0

Thx Anvesh! как это сделать для моего приложения? – user3480753

ответ

0

весь AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
     package="com.example.melas.app_3" > 

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.CALL_PHONE" /> 
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> 

<application 
    android:name=".StartApps" 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/Theme.AppCompat.NoActionBar" > 
    <meta-data 
     android:name="com.parse.APPLICATION_ID" 
     android:value="" /> 
    <meta-data 
     android:name="com.parse.CLIENT_KEY" 
     android:value="" /> 

    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <activity android:name=".Register" > 
    </activity> 
    <activity android:name=".Register2" > 
    </activity> 
    <activity android:name=".LoginActivity" > 
    </activity> 
</application> 

0

Я предлагаю вам бросить запросы разрешений на хранение и использовать ACTION_GET_CONTENT.

Использование будет какая-то вроде этого:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("image/*"); 
    startActivity(Intent.createChooser(intent, "Select image")); 

Этот путь супер удивительным, потому что ваше приложение не любое разрешение для хранения на всех. Только если вы нацеливаете API < 18, вам необходимо запросить разрешение. В таком случае вы можете использовать maxSdkVersion=18 в своем манифесте, чтобы запросить разрешение только тогда, когда другого пути нет.

+0

, а затем? как я могу получить выбранное изображение? – user3480753

+0

Я нашел его! Спасибо всем! – user3480753

+0

Рад помочь! Пожалуйста, отметьте правильный ответ! –

0

Это работает, но я стараюсь, чтобы получить имя файла, чтобы положить на разборе ....

public void loadImagefromGallery(View view) { 
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, 
      android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
    // Start the Intent 
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG); 


} 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
txttest = (TextView)findViewById(R.id.textViewtest); 
     ImageView ig=(ImageView)findViewById(R.id.imageViewTest); 


     try { 
      // When an Image is picked 
      if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK 
        && null != data) { 
       // Get the Image from data 

       Uri selectedImage = data.getData(); 
       String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

       // Get the cursor 
       Cursor cursor = getContentResolver().query(selectedImage, 
         filePathColumn, null, null, null); 
       // Move to first row 
       cursor.moveToFirst(); 

       int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 

       Bitmap bitmap = BitmapFactory.decodeFile(selectedImage.toString()); 
       ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
       bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); 
       byte[] image = stream.toByteArray(); 
       Glide.with(this) 
         .load(selectedImage) 
         .into(ig); 

       Toast.makeText(this, "Image picked" + 
           selectedImage, 
         Toast.LENGTH_LONG).show(); 

//txttest.setText(); 
       } else { 
        Toast.makeText(this, "You haven't picked Image", 
          Toast.LENGTH_LONG).show(); 
       } 
      } catch (Exception e) { 
       Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG) 
         .show(); 
       Log.d("ERROR", e.getMessage()); 
      } 


    } 
Смежные вопросы