Friday, April 3, 2020

My Quick Find Gallery (Part 2 - GridView to Show Images)


4) Show images in GridView and after clicking a image, move to Display Photo Screen

We show data in gridview via adapter. Adapter is a medium between Data and Gridview.

Data ( eg:Array)  ------>      Adapter  ------->     GridView

Subtasks:
i) Our Data i.e, image files present in a particular folder. All Files path of that folder will be stored in a string array variable (for transferring string array to adabter to Gridview):
    Subtasks:
   a) A list of files of a folder will be stored in a File Array variable
   b) Files in a File array variable will be sorted by modification date (new modified file comes first)
   c) Fetch Absolute path of files from Sorted File Array Variable and store into string array variable
   d) Fetch File Name without extension of files from Sorted File Array Variable and store into another string array variable
   e) Files Name is repeated in a string array therefor make a string array where all file names are unique. That will be use in suggestion list in search box.
ii) Actual Data which will be shown in GridView will come by three different actions of user. We will discuss in point iv) later. Now move to Adabter. Data transfer Array Data to Adabter via below line code:
     ImageCustomAdapter customAdapter = new ImageCustomAdapter(getApplicationContext(), ArrayList<String> variable name);
iii) Suppose Gridview will show 3 images in a row. Data transfer Adapter to GridView via this line code:               mImageGrid.setAdapter(customAdapter);

Note: Array Data --->  Adabter ------> GridView 
public void showImageInGrid(ArrayList<String> imagesPath){
      ImageCustomAdapter customAdapter = new ImageCustomAdapter(getApplicationContext(),imagesPath);
      mImageGrid.setAdapter(customAdapter);
    }
iv) GridView displays images when
   a) click the Show All Button:  All Images will show
   b) File Name is selected from suggestion list of search box and then click the search button: Suggestion List File Name matches Images will show
   c) Random file name enter in search box and then click the search button: Random File Name contains Images will show
Note: Text Change in Search Box should not searched because communication break to writing in search box due to system searching  & showing image files in grid view after each letter typing in search box, make system inconstancy state
v) GridView Item Click event

SearchActivity.java

ArrayList<String> allFilePath;// list of all file paths
ArrayList<String> allFileName;// list of all file name
ArrayList<String> uniqueFileName;// list of unique file name without extension

public void getAllFilesPathAndName() {
        allFilePath = new ArrayList<String>();
        allFileName = new ArrayList<String>();
        try {
//i)a)
            //path to /internal storage/ERS/0/my directory
            File directory = new File(Environment.getExternalStorageDirectory().getPath(), getResources().getString(R.string.tag_image_directory_name));
            if (directory.isDirectory()) {
                File[] listFile = directory.listFiles();
//i)b)
                Arrays.sort(listFile, new Comparator<File>() {
                    @Override
                    public int compare(File a, File b) {
                        if(a.lastModified() < b.lastModified() )
                            return 1;
                        if(a.lastModified() > b.lastModified() )
                            return -1;
                        return 0;
                    }
                });
//i)c)&d)
                for (int i = 0; i < listFile.length; i++) {
                    allFilePath.add(listFile[i].getAbsolutePath());
                    allFileName.add(getFileNameWithoutExtension(listFile[i].getName()));
                }
            }
//i)e)
            List<String> allfilename =  this.allFileName;
            Set<String> uniquefilename = new HashSet<String>(allfilename);//unique filename
            this.uniqueFileName=new ArrayList<String>(uniquefilename);

        }
        catch(Exception e){
            Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
        }
    }
//i)d)
    public String getFileNameWithoutExtension(String fileName){
        String[] fileNameParts;
        if(fileName.contains("[")){
            fileNameParts = fileName.split("\\[");
            return fileNameParts[0];
        }
        else{
            int pos = fileName.lastIndexOf(".");//"\\." is not working
            return fileName.substring(0, pos);
        }
    }

//ii)
galleryitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="1dp"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/thumbImage"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:scaleType="fitXY"
        android:layout_gravity="center_horizontal"/>
</LinearLayout>

ImageCustomAdapter.java

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import java.util.ArrayList;

public class ImageCustomAdapter extends BaseAdapter {

    Context mContext;
    ArrayList<String> mFileArray;// list of file paths
    LayoutInflater mInflater;
    public int selectedImage = 0;

    public ImageCustomAdapter(Context applicationContext, ArrayList<String> fileArray) {
        this.mContext = applicationContext;
        this.mFileArray = fileArray;
        mInflater = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return mFileArray.size();
    }
    @Override
    public Object getItem(int i) {
        return null;
    }
    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {

        convertView = mInflater.inflate(R.layout.galleryitem, null); // inflate the layout
        ImageView icon = (ImageView) convertView.findViewById(R.id.thumbImage); // get the reference of ImageView
        Bitmap myBitmap = BitmapFactory.decodeFile(mFileArray.get(i));
        Bitmap thumbnail = ThumbnailUtils.extractThumbnail(myBitmap,300,300);
        //Bitmap scaled = Bitmap.createScaledBitmap(myBitmap, 100, 100, true);
        icon.setImageBitmap(thumbnail);
        return convertView;
    }

}

//iii)
activity_search.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SearchActivity">

    <GridView
        android:id="@+id/ImageGrid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numColumns="3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />
 
</android.support.constraint.ConstraintLayout>.

//iv)
SearchActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
//iv)a)         
case R.id.action_show_all:
                search.setQuery("", false);//this is because when i am adding photo then search box has adding file name. when i click on show all button then should be it clear it.
                isSearchAction=1;//Show All
                if(getFilePathArray(isSearchAction,"")>0) {
                    showImageInGrid(searchFilesPath);////ByFilePathArrayStringAndImageCustomAdapter
                    search.clearFocus();
                }
                else {
                    mImageGrid.setAdapter(null);
                    emptyResult();
                }
                break;
            default:
                break;
        }
        return true;
    }

ArrayList<String> searchFilesPath;// list of filter files path
ArrayList<String> searchFilesName;// list of filter files name

public int getFilePathArray(int isSearchAction, String searchTag){

        searchFilesPath=new ArrayList<String>();
        searchFilesName=new ArrayList<String>();
//iv)a)
        if(isSearchAction==1) {//show all
            searchFilesPath=allFilePath;
            searchFilesName=allFileName;
        }
//iv)b)
else if(isSearchAction==2) {//autocomplete name
            for (int i = 0; i < allFileName.size(); i++) {
                if (allFileName.get(i).equalsIgnoreCase(searchTag)) {
                    searchFilesPath.add(allFilePath.get(i));
                    searchFilesName.add(allFileName.get(i));
                }
            }
        }
//iv)c)
else if(isSearchAction==3){//random name
            for (int i = 0; i < allFileName.size(); i++) {
                if (allFileName.get(i).toLowerCase().contains(searchTag.toLowerCase())) {
                    searchFilesPath.add(allFilePath.get(i));
                    searchFilesName.add(allFileName.get(i));
                }
            }
        } else{ }
        return searchFilesPath.size();
    }

public void showImageInGrid(ArrayList<String> searchFilesPath){ //ByFilePathArrayStringAndImageCustomAdapter
        mImageGrid.setAdapter(null);
        ImageCustomAdapter customAdapter = new ImageCustomAdapter(getApplicationContext(), searchFilesPath);
        mImageGrid.setAdapter(customAdapter);
    }

private void emptyResult() {
        Toast toast = Toast.makeText(this, "No image found", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

//v)
SearchActivity.java
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

mImageGrid = findViewById(R.id.ImageGrid);     
//GridView Item Click Event
        mImageGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(SearchActivity.this, ShowPhoto.class);
                intent.putExtra("selectedImagePosition", position);
                intent.putStringArrayListExtra("searchFilesPath",searchFilesPath);
                intent.putStringArrayListExtra("searchFilesName",searchFilesName);
                startActivity(intent); // start Intent
            }
        });
}

No comments:

Post a Comment