wake-up-neo.net

Laden Sie alle Bilder aus der Galerie in die Anwendung in Android

Ich erstelle eine Anwendung, bei der ich alle Bilder in der Galerie für meine Anwendung benötige, die eine Übersicht enthält. Ich möchte, dass alle Bilder aus allen Ordnern in der Rasteransicht angezeigt werden. 

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);

Ich habe diesen Code in meinen Code eingefügt, aber ich erhalte nur die SD-Karten-Bilder, die keine anderen Ordner-Bilder erhalten. Wie kann ich alle Bilder aus der Galerie erhalten?

Danke im Voraus.

19

Arbeitslösung mit Hilfe von Glide. Bonus Teil ist Glide wird automatisch Gif spielen.

 enter image description here

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;
        }
    }
}

Layoutdatei für 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>
16
Hitesh Sahu

Sie verwenden MediaStore.Images.Media.EXTERNAL_CONTENT_URI, der nur der externe Speicher ist. Für den internen Speicherplatz MediaStore.Images.Media.INTERNAL_CONTENT_URI Sie können ein MergeCursor verwenden, um beide Abfrageergebnisse zu kombinieren.

5
electrofant

Sie können keine Ergebnisse mit nur einer Abfrage erhalten. Versuchen Sie, zwei verschiedene Cursors zu instanziieren ..__ Da Sie bereits EXTERNAL_CONTENT_URI hinzugefügt haben, gibt es einen anderen:

 actualimagecursor2 = managedQuery(MediaStore.Images.Media.INTERNAL_CONTENT_URI, proj,
                      null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
2
zionpi
 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;
    }
1
Anil Singhania
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);

Laden Sie den Quellcode von hier herunter ( Holen Sie sich programmgesteuert alle Bilder aus der Galerie in Android )

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>
0
Deepshikha Puri