4

I am a newbie in android app development and I am following this tutorial to create an image gallery. https://deepshikhapuri.wordpress.com/2017/03/20/get-all-images-from-gallery-in-android-programmatically/.
It's working perfectly but now I want to display images in ViewPager for being able to display images by swiping left/right.I am using an adapter for doing it. I have tried doing it but its not working I dont know why.I am not able to swipe images. Can anyone help me with it ? Am i using correct path for the images?

This project is available on github here :
https://github.com/avi003/MyApp0-master-master

ImageGallery.java:

public class ImageGallery 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_image_gallery);
        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(ImageGallery.this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale( ImageGallery.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE))) {

            } else {
                ActivityCompat.requestPermissions( ImageGallery.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;
        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(ImageGallery.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();
                    }
                }
            }
        }
    }

}

PhotosActivity.java:

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_image_gallery);
        gridView = (GridView)findViewById(R.id.gv_folder);
        int_position = getIntent().getIntExtra("value", 0);
        adapter = new GridViewAdapter(this, al_images,int_position);
        gridView.setAdapter(adapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String abc = "file://" + al_images.get(int_position).getAl_imagepath().get(position);

                Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
                i.putExtra("id", position);
                i.putExtra("abc",abc);
                startActivity(i);
            }
        });
    }
}

GridViewAdapter.java:

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.activity_adapter__photos_folder, 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.activity_adapter__photos_folder, 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;

    }
}

Adapter_PhotosFolder.java:

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.activity_adapter__photos_folder, 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.activity_adapter__photos_folder, 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;


    }
}

Model_images.java:

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

FullImageActivity.java:

public class FullImageActivity extends AppCompatActivity {
    ImageView images;
    int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_image);
        Intent i = getIntent();
        images = (ImageView) findViewById(R.id.fullImage);

        // Selected image id
        position = i.getExtras().getInt("id");
        Bundle extras = getIntent().getExtras();
        String value = extras.getString("abc");

        Glide.with(FullImageActivity.this)
                .load(value)
                .skipMemoryCache(false)
                .into(images);

        ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mViewPager.setAdapter(new TouchImageAdapter(this,al_images));
    }
}

activity_full_image.xml:

<?xml version="1.0" encoding="utf-8"?>

     <LinearLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/jazzy_pager"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

     <ImageView
            android:id="@+id/fullImage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:scaleType="centerCrop"
         />

     <android.support.v4.view.ViewPager
         android:id="@+id/viewpager"
         android:layout_width="match_parent"
         android:layout_height="match_parent" />

</LinearLayout>

TouchImageAdapter.java:

class TouchImageAdapter extends PagerAdapter {
    Context context;
    String filename;
    ArrayList<Model_images> al_menu = new ArrayList<>();
    int position,int_position;

    public TouchImageAdapter(Context context,ArrayList<Model_images> al_menu){
        this.al_menu = al_menu;
        this.context = context;
    }

    @Override
    public int getCount() {
        return al_menu.size();
    }

    @Override
    public View instantiateItem(ViewGroup container, int position) {
        ImageView img = new ImageView(container.getContext());
        img.setImageDrawable(getImageFromSdCard(filename,position));
        container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        return img;
    }

    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }


    public Drawable getImageFromSdCard(String imageName,int position) {
        Drawable d = null;
        try {
            String path = al_menu.get(int_position).getAl_imagepath().get(position)
                    + "/";
            Bitmap bitmap = BitmapFactory.decodeFile(path + "/" + imageName
                    + ".jpeg");
            d = new BitmapDrawable(context.getResources(),bitmap);
        } catch (IllegalArgumentException e) {
            // TODO: handle exception
        }
        return d;

    }
}
  • did you **** permission in manifest file – AskNilesh Sep 18 '17 at 06:50
  • yes , I did and images are being displayed in app, its just that next image doesn't get displayed on swiping @NileshRathod –  Sep 18 '17 at 06:52
  • what is the size of your **al_menu** print size in **LOG** – AskNilesh Sep 18 '17 at 06:57
  • maybe I didn't understand what you are asking clearly, but I think its same as the number of images in the folder ,like when I open the app, it prints in LOG "09-18 12:33:05.792 21586-21586/com.example.dell_1.Myapp3 E/ADAPTER LIST SIZE: 10", and when I open any folder containing images , it prints similar statement with ADAPTER LIST SIZE : "number of images in the folder". @NileshRathod –  Sep 18 '17 at 07:09
  • @RedViper Please post the XML of your `FullImageActivity`. – Rohan Stark Sep 23 '17 at 08:47
  • I have updated the question and included the xml file @RohanStark ..Its available on github too –  Sep 23 '17 at 09:28
  • push the code. Verify it and let me know if it works for you. – Jitesh Mohite Sep 24 '17 at 07:13
  • Thanks, Its working Like a charm @jiteshmohite, Thanks a lot really. Accepted your answer and awarded bounty –  Sep 24 '17 at 10:36
  • welcome @RedViper, if you need any help in future, please drop me mail jiteshmohite619@gmail.com. – Jitesh Mohite Sep 24 '17 at 14:01

3 Answers3

1

Here you are not passing count of images inside that folder, So in TouchImageAdapter you have passing the count of folder like :

 al_menu.size() // it always give you size of folder, 

al_menu.get(int_position).getAl_imagepath().size(); 

// passing the folder position so that correct folder images are to be shown.
public TouchImageAdapter(Context context,ArrayList<Model_images> al_menu, int position){
        this.al_menu = al_menu;
        this.context = context;
        this.int_position = position;
    }

    @Override
    public int getCount() {
        return al_menu.get(int_position).getAl_imagepath().size();
    }

Here is the updated code I pushed on https://github.com/redviper00/game

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
  • I don't get it, this code you provided isn't any different from the code in the question ,is it ? –  Sep 21 '17 at 09:54
  • As mention above please check file path value you are passing inside setImageDrawable, It is same. You have to pass different file path. – Jitesh Mohite Sep 21 '17 at 10:07
  • I tried passing different file path,but it changes nothing –  Sep 21 '17 at 10:24
  • Can you add entire code here, you can edit your question. – Jitesh Mohite Sep 21 '17 at 10:44
  • I've added entire code for app, please check the updated question –  Sep 21 '17 at 11:04
  • Also please add your .xml files inside layout folder, Also if possible can push your code to github for sometime so that I can easily commit the changes that you want. – Jitesh Mohite Sep 21 '17 at 12:55
  • where you are facing the problem, internal Storage or Sd card. – Jitesh Mohite Sep 23 '17 at 15:37
  • Internal storage –  Sep 23 '17 at 15:39
  • In internal storage when i click on images option its showing list of folder name with top image as their screenshot. after click on that it open its internal images which lies in the folder. If I tap on that it open in full view, and then able to swipe left and right. So i m not getting exactly where you are facing problem? can you mention steps so that i can follow ? – Jitesh Mohite Sep 23 '17 at 15:43
  • are you able to swipe left and right for all images? I am unable to swipe after 8-10 images –  Sep 23 '17 at 15:49
  • I fixed your issue at my end but not able to push at your repository, can you give access to it so I can push my code – Jitesh Mohite Sep 23 '17 at 16:42
  • Also I find other issues as it always showing first folder images in viewpager, Also it not opening the image which i tap, it is always opening the first image from that folder, I fixed it please check once you got my code. – Jitesh Mohite Sep 23 '17 at 16:44
  • yes, I can give access.I need your username or email address and I will add you to the collaborators –  Sep 23 '17 at 18:24
  • jiteshmohite619@gmail.com – Jitesh Mohite Sep 24 '17 at 04:32
  • I have added jiteshmohite619 as a collaborator –  Sep 24 '17 at 04:40
  • my username is jiteshmohite can you add that ? – Jitesh Mohite Sep 24 '17 at 05:16
  • I see only jiteshmohite jits and jiteshmohite619, which one are you ? It says jiteshmohite619 doesn't have a github account –  Sep 24 '17 at 05:37
  • Or you can just answer here ? –  Sep 24 '17 at 05:38
  • jiteshmohite and jits are both my account give access to them – Jitesh Mohite Sep 24 '17 at 05:42
  • done for jiteshmohite jits and jiteshmohite619, added to collaborators –  Sep 24 '17 at 06:08
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/155177/discussion-between-jitesh-mohite-and-red-viper). – Jitesh Mohite Sep 24 '17 at 07:13
0

try this

String[] filenames = new String[0];
        File path = new File(Environment.getExternalStorageDirectory() + "/your folder");
        if (path.exists()) {
            filenames = path.list();
        }
        for (int i = 0; i < filenames.length; i++) {
            imagesPathArrayList.add(path.getPath() + "/" + filenames[i]);
            Log.e("FAV_Images", imagesPathArrayList.get(i));
            adapter = new ImageAdapter(FavActivity.this, imagesPathArrayList);
            myviewpager.setAdapter(adapter);

        }

create adapter class like this

public class ImageAdapter extends PagerAdapter {

        Context context;
        ArrayList<String> arrayList;

        ImageAdapter(Context context, ArrayList<String> arrayList) {
            this.context = context;
            this.arrayList = arrayList;
        }

        @Override
        public int getCount() {
            return arrayList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((ImageView) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            viewPagerImageView = new ImageView(context);



            viewPagerImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

            Bitmap bitmap = BitmapFactory.decodeFile(arrayList.get(position));
            viewPagerImageView.setImageBitmap(bitmap);


            ((ViewPager) container).addView(viewPagerImageView, 0);

            return viewPagerImageView;

        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((ImageView) object);
        }
    }
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
  • actually my app displays images in different folders, or folder-wise, please see the updated question above , its according to the tutorial I am following –  Sep 18 '17 at 07:31
0

It seems like you are showing Imageview above view pager

images = (ImageView) findViewById(R.id.fullImage);

that is why when you are trying to swipe imageview handle your tocuh action instead of view pager. Remove it.

Jaiprakash Soni
  • 4,100
  • 5
  • 36
  • 67
  • I am able to swipe, but why same image gets displayed on full screen again and again ? –  Sep 21 '17 at 07:33
  • I am sorry, I am completely new to android, just started a couple of months ago –  Sep 22 '17 at 11:59