ギャラリー内のすべての画像を必要とするアプリケーションを作成しています。これには、ガードビューを含むアプリケーションが含まれています。すべてのフォルダのすべての画像をグリッドビューに表示したい。
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);
このコードをコードに追加しましたが、SDカードの画像のみが取得され、他のフォルダー画像は取得されません。ギャラリーからすべての画像を取得するにはどうすればよいですか?
前もって感謝します。
Glideを使用した実用的なソリューション。ボーナス部分はGlideが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;
}
}
}
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>
Kotlin
およびLoderManager
で2019を更新:** 2)LoderManagerを使用して非同期ロードイメージをロードします。**
アクティビティクラスまたはフラグメントクラスにLoaderManager.LoaderCallbacks<Cursor>
を実装します
LoaderCallbacksのオーバーライド:
private val IMAGE_LOADER_ID = 1
private val listOfAllImages = ArrayList<String>()
override fun onCreateLoader(p0: Int, p1: Bundle?): Loader<Cursor> {
val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME)
val selection: String? = null //Selection criteria
val selectionArgs = arrayOf<String>() //Selection criteria
val sortOrder: String? = null
return CursorLoader(
activity!!.applicationContext,
uri,
projection,
selection,
selectionArgs,
sortOrder)
}
override fun onLoadFinished(loader: Loader<Cursor>, cursor: Cursor?) {
cursor?.let {
val columnIndexData = it.getColumnIndexOrThrow(MediaColumns.DATA);
while (it.moveToNext()) {
listOfAllImages.add(it.getString(columnIndexData));
}
}
}
override fun onLoaderReset(loader: Loader<Cursor>) {
}
最後にonCreateメソッドの初期化ローダー:
loaderManager.initLoader(IMAGE_LOADER_ID,
null,
this)
Kotlin Coroutine
およびViewModel
の使用実装 'androidx.core:core-ktx:1.0.2'
実装 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0-M2'
実装「org.jetbrains.kotlinx:kotlinx-coroutines-Android:1.3.0-M2」
Coroutine
コンテキストを使用したビューモデルの作成
/**
* Use Coroutines To Load Images
*/
class ImageViewModel : ViewModel(), CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
private var imagesLiveData: MutableLiveData<List<String>> = MutableLiveData()
fun getImageList(): MutableLiveData<List<String>> {
return imagesLiveData
}
/**
* Getting All Images Path.
*
* Required Storage Permission
*
* @return ArrayList with images Path
*/
internal fun loadImagesfromSDCard(): ArrayList<String> {
val uri: Uri = Android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val cursor: Cursor?
val column_index_data: Int
val column_index_folder_name: Int
val listOfAllImages = ArrayList<String>()
var absolutePathOfImage: String? = null
val projection = arrayOf(MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME)
cursor = AppController.globalContentResolvere!!.query(uri, projection, null, null, null)
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)
listOfAllImages.add(absolutePathOfImage)
}
return listOfAllImages
}
fun getAllImages() {
launch(Dispatchers.Main) {
imagesLiveData.value = withContext(Dispatchers.IO) {
loadImagesfromSDCard()
}
}
}
}
そしてviewModel
を使用します
val imageViewModel = ViewModelProviders.of(this).get(ImageViewModel::class.Java)
imageViewModel.getImageList().observe(this, Observer<List<String>> { listOfImage ->
imageWidgetStatus.text = """ Found ${listOfImage.size} Images"""
// load images
imageViewModel.getAllImages()
外部ストレージのみであるMediaStore.Images.Media.EXTERNAL_CONTENT_URI
を使用しています。内部にはMediaStore.Images.Media.INTERNAL_CONTENT_URI
があります。 MergeCursor を使用して、両方のクエリ結果を組み合わせることができます。
1つのクエリだけで結果を取得することはできません。2つの異なるカーソルをインスタンス化してみてください。 EXTERNAL_CONTENT_URI をすでに追加しているので、ここに別のものがあります。
actualimagecursor2 = managedQuery(MediaStore.Images.Media.INTERNAL_CONTENT_URI, proj,
null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
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);
ここからソースコードをダウンロードします( ギャラリーからすべての画像を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>