una studio seleccionar programacion para móviles imagen galeria edición desde desarrollo curso cargar aplicaciones android image android-gallery

studio - programacion android pdf 2018



Cargando todas las imágenes de la galería en la aplicación en Android (6)

Estoy creando una aplicación en la que necesito todas las imágenes de la galería en mi aplicación que tiene una vista panorámica en ella. Quiero que todas las imágenes de todas las carpetas aparezcan en la vista de cuadrícula.

String[] proj = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID }; actualimagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj, null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER); actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID); actualimagecursor.moveToPosition(position); String i = actualimagecursor.getString(actual_image_column_index);

He añadido este código en mi código, pero solo obtengo las imágenes de la tarjeta SD que no se obtienen otras imágenes de carpeta. ¿Cómo puedo obtener todas las imágenes de la galería?

Gracias por adelantado.


Descargue el código fuente desde aquí ( Obtenga todas las imágenes de la galería en Android programáticamente )

activity_main.xml

<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" xmlns:android="http://schemas.android.com/apk/res/android"> <GridView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/gv_folder" android:numColumns="2" android:layout_marginLeft="10dp" android:layout_marginRight="10dp"></GridView> </RelativeLayout>

MainActivity.java

package galleryimages.galleryimages; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { public static ArrayList<Model_images> al_images = new ArrayList<>(); boolean boolean_folder; Adapter_PhotosFolder obj_adapter; GridView gv_folder; private static final int REQUEST_PERMISSIONS = 100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gv_folder = (GridView)findViewById(R.id.gv_folder); gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent intent = new Intent(getApplicationContext(), PhotosActivity.class); intent.putExtra("value",i); startActivity(intent); } }); if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) { if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE))) { } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS); } }else { Log.e("Else","Else"); fn_imagespath(); } } public ArrayList<Model_images> fn_imagespath() { al_images.clear(); int int_position = 0; Uri uri; Cursor cursor; int column_index_data, column_index_folder_name; String absolutePathOfImage = null; uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME}; final String orderBy = MediaStore.Images.Media.DATE_TAKEN; cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC"); column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME); while (cursor.moveToNext()) { absolutePathOfImage = cursor.getString(column_index_data); Log.e("Column", absolutePathOfImage); Log.e("Folder", cursor.getString(column_index_folder_name)); for (int i = 0; i < al_images.size(); i++) { if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) { boolean_folder = true; int_position = i; break; } else { boolean_folder = false; } } if (boolean_folder) { ArrayList<String> al_path = new ArrayList<>(); al_path.addAll(al_images.get(int_position).getAl_imagepath()); al_path.add(absolutePathOfImage); al_images.get(int_position).setAl_imagepath(al_path); } else { ArrayList<String> al_path = new ArrayList<>(); al_path.add(absolutePathOfImage); Model_images obj_model = new Model_images(); obj_model.setStr_folder(cursor.getString(column_index_folder_name)); obj_model.setAl_imagepath(al_path); al_images.add(obj_model); } } for (int i = 0; i < al_images.size(); i++) { Log.e("FOLDER", al_images.get(i).getStr_folder()); for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) { Log.e("FILE", al_images.get(i).getAl_imagepath().get(j)); } } obj_adapter = new Adapter_PhotosFolder(getApplicationContext(),al_images); gv_folder.setAdapter(obj_adapter); return al_images; } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_PERMISSIONS: { for (int i = 0; i < grantResults.length; i++) { if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) { fn_imagespath(); } else { Toast.makeText(MainActivity.this, "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show(); } } } } } }

adapter_photosfolder.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:orientation="vertical" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:background="@drawable/drawable_photofolder" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:layout_height="match_parent"> <ImageView android:layout_width="150dp" android:layout_gravity="center" android:layout_height="150dp" android:id="@+id/iv_image"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_folder" android:textStyle="bold" android:textColor="#000000" android:layout_marginLeft="10dp" android:textSize="15dp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_folder2" android:textColor="#dfdfdf" android:layout_marginBottom="10dp" android:layout_marginLeft="10dp" android:textSize="15dp"/> </LinearLayout> <RelativeLayout android:layout_width="match_parent" android:id="@+id/rl_select" android:alpha="0.5" android:layout_height="match_parent"> </RelativeLayout> </RelativeLayout>

Adapter_PhotosFolder.java

package galleryimages.galleryimages; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.util.ArrayList; public class Adapter_PhotosFolder extends ArrayAdapter<Model_images> { Context context; ViewHolder viewHolder; ArrayList<Model_images> al_menu = new ArrayList<>(); public Adapter_PhotosFolder(Context context, ArrayList<Model_images> al_menu) { super(context, R.layout.adapter_photosfolder, al_menu); this.al_menu = al_menu; this.context = context; } @Override public int getCount() { Log.e("ADAPTER LIST SIZE", al_menu.size() + ""); return al_menu.size(); } @Override public int getItemViewType(int position) { return position; } @Override public int getViewTypeCount() { if (al_menu.size() > 0) { return al_menu.size(); } else { return 1; } } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { viewHolder = new ViewHolder(); convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_photosfolder, parent, false); viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder); viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2); viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.tv_foldern.setText(al_menu.get(position).getStr_folder()); viewHolder.tv_foldersize.setText(al_menu.get(position).getAl_imagepath().size()+""); Glide.with(context).load("file://" + al_menu.get(position).getAl_imagepath().get(0)) .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .into(viewHolder.iv_image); return convertView; } private static class ViewHolder { TextView tv_foldern, tv_foldersize; ImageView iv_image; } } **PhotosActivity.java** package galleryimages.galleryimages; import android.app.Activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.GridView; public class PhotosActivity extends AppCompatActivity { int int_position; private GridView gridView; GridViewAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridView = (GridView)findViewById(R.id.gv_folder); int_position = getIntent().getIntExtra("value", 0); adapter = new GridViewAdapter(this,MainActivity.al_images,int_position); gridView.setAdapter(adapter); } } **GridViewAdapter.java** package galleryimages.galleryimages; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.util.ArrayList; import java.util.List; public class GridViewAdapter extends ArrayAdapter<Model_images> { Context context; ViewHolder viewHolder; ArrayList<Model_images> al_menu = new ArrayList<>(); int int_position; public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) { super(context, R.layout.adapter_photosfolder, al_menu); this.al_menu = al_menu; this.context = context; this.int_position = int_position; } @Override public int getCount() { Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + ""); return al_menu.get(int_position).getAl_imagepath().size(); } @Override public int getItemViewType(int position) { return position; } @Override public int getViewTypeCount() { if (al_menu.get(int_position).getAl_imagepath().size() > 0) { return al_menu.get(int_position).getAl_imagepath().size(); } else { return 1; } } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { viewHolder = new ViewHolder(); convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_photosfolder, parent, false); viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder); viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2); viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.tv_foldern.setVisibility(View.GONE); viewHolder.tv_foldersize.setVisibility(View.GONE); Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position)) .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .into(viewHolder.iv_image); return convertView; } private static class ViewHolder { TextView tv_foldern, tv_foldersize; ImageView iv_image; } }

Model_images.java

package galleryimages.galleryimages; import java.util.ArrayList; public class Model_images { String str_folder; ArrayList<String> al_imagepath; public String getStr_folder() { return str_folder; } public void setStr_folder(String str_folder) { this.str_folder = str_folder; } public ArrayList<String> getAl_imagepath() { return al_imagepath; } public void setAl_imagepath(ArrayList<String> al_imagepath) { this.al_imagepath = al_imagepath; } }

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="galleryimages.galleryimages"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".PhotosActivity"></activity> </application> </manifest>


Está utilizando MediaStore.Images.Media.EXTERNAL_CONTENT_URI que es solo el almacenamiento externo. Para el interno hay MediaStore.Images.Media.INTERNAL_CONTENT_URI . Puede usar un MergeCursor para combinar ambos resultados de la consulta.


No puede obtener resultados con una sola consulta, intente crear una instancia de dos Cursores diferentes. Como ya has agregado EXTERNAL_CONTENT_URI , aquí hay otro:

actualimagecursor2 = managedQuery(MediaStore.Images.Media.INTERNAL_CONTENT_URI, proj, null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);


Solución de trabajo con la ayuda de Glide . La parte de bonificación es Glide se reproducirá automáticamente Gif.

import java.util.ArrayList; import android.app.Activity; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.provider.MediaStore.MediaColumns; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.Toast; import com.bumptech.glide.Glide; /** * The Class GallarySample. */ public class GallarySample extends Activity { /** The images. */ private ArrayList<String> images; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gallery_activity); GridView gallery = (GridView) findViewById(R.id.galleryGridView); gallery.setAdapter(new ImageAdapter(this)); gallery.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { if (null != images && !images.isEmpty()) Toast.makeText( getApplicationContext(), "position " + position + " " + images.get(position), 300).show(); ; } }); } /** * The Class ImageAdapter. */ private class ImageAdapter extends BaseAdapter { /** The context. */ private Activity context; /** * Instantiates a new image adapter. * * @param localContext * the local context */ public ImageAdapter(Activity localContext) { context = localContext; images = getAllShownImagesPath(context); } public int getCount() { return images.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(final int position, View convertView, ViewGroup parent) { ImageView picturesView; if (convertView == null) { picturesView = new ImageView(context); picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER); picturesView .setLayoutParams(new GridView.LayoutParams(270, 270)); } else { picturesView = (ImageView) convertView; } Glide.with(context).load(images.get(position)) .placeholder(R.drawable.ic_launcher).centerCrop() .into(picturesView); return picturesView; } /** * Getting All Images Path. * * @param activity * the activity * @return ArrayList with images Path */ private ArrayList<String> getAllShownImagesPath(Activity activity) { Uri uri; Cursor cursor; int column_index_data, column_index_folder_name; ArrayList<String> listOfAllImages = new ArrayList<String>(); String absolutePathOfImage = null; uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI; String[] projection = { MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME }; cursor = activity.getContentResolver().query(uri, projection, null, null, null); column_index_data = cursor.getColumnIndexOrThrow(MediaColumns.DATA); column_index_folder_name = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME); while (cursor.moveToNext()) { absolutePathOfImage = cursor.getString(column_index_data); listOfAllImages.add(absolutePathOfImage); } return listOfAllImages; } } }

Archivo de diseño para gridView

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <GridView android:id="@+id/galleryGridView" android:layout_width="match_parent" android:layout_height="wrap_content" android:columnWidth="280dp" android:gravity="center" android:horizontalSpacing="2dp" android:numColumns="2" android:padding="2dp" android:stretchMode="columnWidth" android:verticalSpacing="2dp" > </GridView> </RelativeLayout>


public static ArrayList<String> fetchGalleryImages(Activity context) { ArrayList<String> galleryImageUrls; final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};//get all columns of type images final String orderBy = MediaStore.Images.Media.DATE_TAKEN;//order data by date Cursor imagecursor = context.managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy + " DESC");//get all data in Cursor by sorting in DESC order galleryImageUrls = new ArrayList<String>(); for (int i = 0; i < imagecursor.getCount(); i++) { imagecursor.moveToPosition(i); int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);//get column index galleryImageUrls.add(imagecursor.getString(dataColumnIndex));//get Image from column index } Log.e("fatch in","images"); return galleryImageUrls; }


Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);