0

Also habe ich Code implementiert, um Bilder aus meinem Dateisystem mit der Standardbildauswahl in Android auszuwählen, aber aus irgendeinem Grund ist jedes Bild ausgegraut. Es erlaubt mir nicht, ein Bild zu wählen. Ich habe es auf Marshmallow 6.0.1 (von wo Screenshot gemacht wird) und auf Lollipop 5.1.1 getestet.Ich kann kein Bild aus der Systembildauswahl auswählen

enter image description here

Hier ist meine Implementierung:

Manifest:

<uses-permission android:name="android.permission.WAKE_LOCK" /> 
<uses-permission android:name="com.company.app.permission.C2D_MESSAGE" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

Beachten Sie, dass all dies hat sich auf die gleiche Tätigkeit, LaunchActivity.java

Variablen wie verwendet getan worden:

private ImageView picturebutton; 
private Bitmap imageBitmap; 
final private int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE=1; 
private int PICK_IMAGE_REQUEST = 1; 

Image als Taster handeln:

picturebutton = (ImageView) findViewById(R.id.chose_picture); 
View.OnClickListener picturebuttonClickListener = new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      checkStorageReadPermission(LaunchActivity.this); 
     } 
    }; 
    picturebutton.setOnClickListener(picturebuttonClickListener); 

Verfahren checkStorageReadPermission() die Speicherzugangsberechtigungsanfragen:

public void checkStorageReadPermission(final Context context){ 
    if(ContextCompat.checkSelfPermission(LaunchActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){ 
     if(ActivityCompat.shouldShowRequestPermissionRationale(LaunchActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)){ 
     } 
     else { 
      ActivityCompat.requestPermissions(LaunchActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); 
     } 
    } 
    else{ 
     Log.d("Permissions","Permission was already granted"); 
     startActivity(openGallery()); 
    } 
} 

Der Aufhebungscode für onRequestPermissionsResult():

@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
    switch (requestCode) { 
     case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       startActivity(openGallery()); 
       Log.d("Permissions","Can read storage"); 
      } else { 
       //code for deny 
       Log.e("Permissions","Can't read storage"); 
      } 
      break; 
    } 
} 

Die Absicht openGallery(), die das Bild Picker ruft:

public Intent openGallery() { 
     Intent og = new Intent(); 
     og.setType("image*/"); 
     og.setAction(Intent.ACTION_GET_CONTENT); 
     startActivityForResult(Intent.createChooser(og,"Pick a picture"),PICK_IMAGE_REQUEST); 
     return og; 
    } 

Der Code onActivityResult() außer Kraft zu setzen, wenn die Absicht genannt wird:

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data){ 
    super.onActivityResult(resultCode,requestCode,data); 
    if(requestCode==PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){ 
     Uri imageUri = data.getData(); 
     try{ 
      imageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri); 
      x.uploadImage(imageBitmap,LaunchActivity.this); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

Es gibt kein Problem mit der Erlaubnis Wenn der Prozess angefordert wird, wird der Systemberechtigungsdialog für den externen Speicherzugriff angezeigt. Er wird gewährt und der Picker öffnet, aber ich kann kein Bild auswählen. Hilfe wird geschätzt!

+0

og.setType ("image * /"); anstelle dessen put og.setType ("image/*"); entferne zurück og; –

Antwort

0

Anstelle von startActivity(openGallery());, rufen Sie einfach openGallery(); Methode. Sie starten die Bildauswahl bereits in dieser Methode mit startActivityForResilt, so dass Sie nicht erneut startActivity() benötigen. Entfernen Sie außerdem die return-Anweisung von openGallery().

Außerdem setzen Sie den MIME-Typ falsch. Es sollte image/* sein. So soll der aktualisierte sein:

public void openGallery() { 
     Intent og = new Intent(); 
     og.setType("image/*"); 
     og.setAction(Intent.ACTION_GET_CONTENT); 
     startActivityForResult(Intent.createChooser(og,"Pick a picture"),PICK_IMAGE_REQUEST); 
    } 
0

OnChoose-Code

 chooseimage.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 



      if (Build.VERSION.SDK_INT >= 23){ 

       boolean result= Utility.checkPermission(getActivity()); 

       if(result) { 
        galleryIntent(); 
       } 

      } 

      else { 
       Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

       // Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery. 
       startActivityForResult(i,LOAD_IMAGE_RESULTS); //LOAD_IMAGE_RESULTS 
      } 




     } 
    }); 

Auch hinzugefügt Code für Permission und Set Bild

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (Build.VERSION.SDK_INT >= 23) { 
     if (resultCode == Activity.RESULT_OK) { 
      if (requestCode == LOAD_IMAGE_RESULTS) { 
       onSelectFromGalleryResult(data); 

      } 
     } 
    } 
    else { 



       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) { 

        Bitmap bitmap = null; 
        Uri selectedImage = data.getData(); 
        String wholeID = DocumentsContract.getDocumentId(selectedImage); 

        // Split at colon, use second item in the array 
        String id = wholeID.split(":")[1]; 

        String[] column = {MediaStore.Images.Media.DATA}; 

        // where id is equal to 
        String sel = MediaStore.Images.Media._ID + "=?"; 

        Cursor cursor = getActivity().getContentResolver(). 
          query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
            column, sel, new String[]{id}, null); 

        String filePath = ""; 

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

        if (cursor.moveToFirst()) { 
         //filePath = cursor.getString(columnIndex); 
         mPath = cursor.getString(columnIndex); 
        } 


        cursor.close(); 

       } 
       else { 
        if (requestCode == LOAD_IMAGE_RESULTS && resultCode == getActivity().RESULT_OK && data != null) { 
         // Let's read picked image data - its URI 
         Uri pickedImage = data.getData(); 
         // Let's read picked image path using content resolver 
         String[] filePath = {MediaStore.Images.Media.DATA}; 
         Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath, null, null, null); 
         cursor.moveToFirst(); 
         mPath = cursor.getString(cursor.getColumnIndex(filePath[0])); 
         //edAttach.setText(mPath.toString()); path set anywhere 
         cursor.close(); 
        } 

       } 
    } 
} 




private void onSelectFromGalleryResult(Intent data) { 

    Bitmap bm=null; 
    if (data != null) { 
     try { 
      bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
ivprofile.setImageBitmap(bm); 
    } 



    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) { 
     Uri selectedImage = data.getData(); 
     String wholeID = DocumentsContract.getDocumentId(selectedImage); 

     // Split at colon, use second item in the array 
     String id = wholeID.split(":")[1]; 

     String[] column = {MediaStore.Images.Media.DATA}; 

     // where id is equal to 
     String sel = MediaStore.Images.Media._ID + "=?"; 

     Cursor cursor = getActivity().getContentResolver(). 
       query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
         column, sel, new String[]{id}, null); 

     String filePath = ""; 

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

     if (cursor.moveToFirst()) { 
      //filePath = cursor.getString(columnIndex); 
      mPath = cursor.getString(columnIndex); 
      //edAttach.setText(mPath); path set anywhere 


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

     Cursor cursor = getActivity().getContentResolver().query(selectedImage, 
       filePathColumn, null, null, null); 
     cursor.moveToFirst(); 

     int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
     mPath = cursor.getString(columnIndex).toString(); 
     System.out.println("picturePath" + mPath); 
     if (!mPath.equalsIgnoreCase(null)) { 
      edAttach.setText(mPath); 
     } 
     cursor.close(); 
    } 

} 

public boolean hasPermissionInManifest(Context context, String permissionName) { 
    final String packageName = context.getPackageName(); 
    try { 
     final PackageInfo packageInfo = context.getPackageManager() 
       .getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); 
     final String[] declaredPermisisons = packageInfo.requestedPermissions; 
     if (declaredPermisisons != null && declaredPermisisons.length > 0) { 
      for (String p : declaredPermisisons) { 
       if (p.equals(permissionName)) { 
        return true; 
       } 
      } 
     } 
    } catch (PackageManager.NameNotFoundException e) { 

    } 
    return false; 
} 


public static boolean isMediaDocument(Uri uri) 
{ 
    return "com.android.providers.media.documents".equals(uri.getAuthority()); 
} 

private void galleryIntent() 
{ 
    Intent intent = new Intent(Intent.ACTION_PICK); 
    intent.setType("image/*"); 
    intent.setAction(Intent.ACTION_GET_CONTENT);// 
    startActivityForResult(Intent.createChooser(intent, "Select File"),LOAD_IMAGE_RESULTS); 
} 
@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
    switch (requestCode) { 
     case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 


       galleryIntent(); 

      } else { 
       //code for deny 
      } 
      break; 
    } 
} 

oder Erlaubnis in Ihrem mainfiest.XML

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

Utility.java

import android.Manifest; 
import android.annotation.TargetApi; 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.pm.PackageManager; 
import android.os.Build; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 

public class Utility { 
    public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123; 
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
    public static boolean checkPermission(final Context context) 
    { 
     int currentAPIVersion = Build.VERSION.SDK_INT; 
     if(currentAPIVersion>= Build.VERSION_CODES.M) 
     { 
      if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { 
       if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) { 
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context); 
        alertBuilder.setCancelable(true); 
        alertBuilder.setTitle("Permission necessary"); 
        alertBuilder.setMessage("External storage permission is necessary"); 
        alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { 
         @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
         public void onClick(DialogInterface dialog, int which) { 
          ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); 
         } 
        }); 
        AlertDialog alert = alertBuilder.create(); 
        alert.show(); 
       } else { 
        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); 
       } 
       return false; 
      } else { 
       return true; 
      } 
     } else { 
      return true; 
     } 
    } 
} 
Verwandte Themen