0

I'm setting image adapter in grid view in fragments from particular folder by capturing image through my application camera button. But it does not refresh the image adapter after capturing images.

Here is my code:

public class FragmentTab1 extends Fragment {

public ImageAdapter imageAdapter;
private final static int TAKE_IMAGE = 1;
private final static int UPLOAD_IMAGES = 2;
private final static int VIEW_IMAGE = 3;
private Uri imageUri;
private MediaScannerConnection mScanner;
public GridView imagegrid;
private long lastId;
android.hardware.Camera.Parameters parameters;
android.hardware.Camera.Size size;
public Context ctx;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);

    ctx=getActivity();
    imageAdapter = new ImageAdapter(ctx);
    imageAdapter.initialize();
    imagegrid = (GridView) rootView.findViewById(R.id.PhoneImageGrid);

    final Button PhotoBtn = (Button) rootView.findViewById(R.id.PhotoBtn);
    PhotoBtn.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String fileName = "IMG_" + sdf.format(new Date()) + ".jpg";
            File myDirectory = new File(Environment
                    .getExternalStorageDirectory() + "/PHOTOAPP/");
            myDirectory.mkdirs();
            File file = new File(myDirectory, fileName);
            imageUri = Uri.fromFile(file);
            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            //parameters=Camera.
            //intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT,153600L);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, TAKE_IMAGE);
        }
    });

    imagegrid.setAdapter(imageAdapter);
    return rootView;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case TAKE_IMAGE:
            try {
                if (resultCode ==Activity. RESULT_OK) {

                    // we need to update the gallery by starting MediaSanner service.
                    mScanner = new MediaScannerConnection(
                            getActivity(),
                            new MediaScannerConnection.MediaScannerConnectionClient() {
                                public void onMediaScannerConnected() {
                                    mScanner.scanFile(imageUri.getPath(), null /* mimeType */);
                                }

                                public void onScanCompleted(String path, Uri uri) {

                                    if (path.equals(imageUri.getPath())) {
                                        mScanner.disconnect();
                                        //we need to create new UI thread because, we can't update our mail thread from here
                                        //Both the thread will run one by one, see documentation of android  
                                        getActivity()
                                                .runOnUiThread(new Runnable() {
                                                    public void run() {
                                                        updateUI();
                                                    }
                                                });
                                    }
                                }
                            });
                    mScanner.connect();

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        case UPLOAD_IMAGES:
            if (resultCode == Activity.RESULT_OK){
                //do some code where you integrate this project
            }
            break;
        }
    }

    public void updateUI() {
        ctx=getActivity().getParent();
        imageAdapter = new ImageAdapter(ctx);
        //imageAdapter.initialize();
        imageAdapter.checkForNewImages();

    }


 public class ImageAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        public ArrayList<ImageItem> images = new ArrayList<ImageItem>();

        public ImageAdapter(Context c) {
            ctx=c;
            mInflater = (LayoutInflater)getActivity(). getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
        }

        @SuppressWarnings("deprecation")
        public void initialize() {
            images.clear();
            final String[] columns = { MediaStore.Images.Thumbnails._ID };
            final String orderBy = MediaStore.Images.Media._ID;
         ContentResolver Resolver = getActivity().getContentResolver();
            Cursor imagecursor = Resolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    columns,MediaStore.Images.Media.DATA + " like ? ",
                    new String[] {"%PHOTOAPP%"},orderBy);
            if(imagecursor != null){
                int image_column_index = imagecursor
                        .getColumnIndex(MediaStore.Images.Media._ID);
                int count = imagecursor.getCount();
                for (int i = 0; i < count; i++) {
                    imagecursor.moveToPosition(i);
                    int id = imagecursor.getInt(image_column_index);
                    ImageItem imageItem = new ImageItem();
                    imageItem.id = id;
                    lastId = id;
                    imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(
                            getActivity().getContentResolver(), id,
                            MediaStore.Images.Thumbnails.MINI_KIND, null);
                    images.add(imageItem);
                }
                //imagecursor.close();
            }
            notifyDataSetChanged();
        }

        @SuppressWarnings("deprecation")
        public void checkForNewImages(){
            //Here we'll only check for newer images
            final String[] columns = { MediaStore.Images.Thumbnails._ID };
            final String orderBy = MediaStore.Images.Media._ID;
            Cursor imagecursor=null;
            ContentResolver Resolver = getActivity().getContentResolver();
            System.out.println("SIZE="+images.size());
            if(images.size()==0){

                imagecursor = Resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        columns,MediaStore.Images.Media.DATA + " like ? ",
                        new String[] {"%PHOTOAPP%"},orderBy);
            }

            else{
                imagecursor = Resolver.query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
                        MediaStore.Images.Media._ID + " > " + lastId , null, orderBy);
            }

            int image_column_index = imagecursor
                    .getColumnIndex(MediaStore.Images.Media._ID);
            int count = imagecursor.getCount();
            for (int i = 0; i < count; i++) {
                imagecursor.moveToPosition(i);
                int id = imagecursor.getInt(image_column_index);
                ImageItem imageItem = new ImageItem();
                imageItem.id = id;
                lastId = id;
                imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(
                        getActivity().getContentResolver(), id,
                        MediaStore.Images.Thumbnails.MINI_KIND, null);
                imageItem.selection = true; //newly added item will be selected by default
                images.add(imageItem);
            }
            //imagecursor.close();
            notifyDataSetChanged();
        }


        public int getCount() {
            return images.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.galleryitem, null);
                holder.imageview = (ImageView) convertView
                        .findViewById(R.id.thumbImage);
                holder.checkbox = (CheckBox) convertView
                        .findViewById(R.id.itemCheckBox);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            ImageItem item = images.get(position);
            holder.checkbox.setId(position);
            holder.imageview.setId(position);
            holder.checkbox.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    CheckBox cb = (CheckBox) v;
                    int id = cb.getId();
                    if (images.get(id).selection) {
                        cb.setChecked(false);
                        images.get(id).selection = false;
                    } else {
                        cb.setChecked(true);
                        images.get(id).selection = true;
                    }
                }
            });

            holder.imageview.setImageBitmap(item.img);
            holder.checkbox.setChecked(item.selection);
            holder.checkbox.setVisibility(View.GONE);
            return convertView;
        }
 }
 class ViewHolder {
        ImageView imageview;
        CheckBox checkbox;
    }

    class ImageItem {
        boolean selection;
        int id;
        Bitmap img;
    }

}

Aparana
  • 59
  • 1
  • 11

1 Answers1

0

The problem is here,

public void updateUI() {
        ctx=getActivity().getParent();
        imageAdapter = new ImageAdapter(ctx);
        //imageAdapter.initialize();
        imageAdapter.checkForNewImages();

    }

You do not need to create a new instance of your ImageAdapter. So your updateUI() can be like this,

public void updateUI() {

            imageAdapter.checkForNewImages();

        }

But still you endup with duplicates of last captured image in the grid.

To avoid that, you need to clear the ArrayList before you add new item into that.

Either you can simply use your initialize() method or

do images.clear() in checkForNewImages() method.

If you are using checkForNewImages() method here, you do not need notifyDataSetchanged() call in initialize() method.

Anyway finally requirement will become same like, you need to clear the list before you add your last captured item. So in my view you do not need checkFornewImages() method at all and you can use your initialize() method with notifyDataSetChanged() call.

Finally my solution is, remove your checkForNewImages() method and modify your updateUI() method like the following one,

public void updateUI() {

        imageAdapter.initialize();


    }

Note: Removing checkForNewImages() will not resolve your issue. That is just to have DRY code.

Kartihkraj Duraisamy
  • 3,171
  • 2
  • 25
  • 36
  • As you told that remove checkForNewImages() and call only initialize() in updateUI(); – Aparana Apr 15 '15 at 07:45
  • I copied your code and have a working sample. It is working fine for me. Either I have to see your complete code of Fragment or you may need to try my working code. Let me know if you want my working code? – Kartihkraj Duraisamy Apr 15 '15 at 07:50
  • I am using this code with TABHOST and fragment thats why it is not working but it works fine with using fragments... so if you help me with your code then please do. – Aparana Apr 15 '15 at 07:53
  • Ok, Then check for following things. 1. Are you able to receive onActivityRsult() call back successfully. 2. Is your images list count increased after the update in checkForNewImages() 3. Is getView() updated with the latest set – Kartihkraj Duraisamy Apr 15 '15 at 07:58
  • Can you tell me whether onActivityResult() call back in tabhost fragment or not ? As i think this is the main problem and your 1 point is right as i'm not able to receive onActivityResult() call back successfully. – Aparana Apr 15 '15 at 12:44
  • Just have a look into this link http://stackoverflow.com/questions/6147884/onactivityresult-not-being-called-in-fragment. Check for all answers, you will get some variety of situations and answers. Something may fits for you. – Kartihkraj Duraisamy Apr 15 '15 at 15:08
  • yes,i have reviewed this link and apply all given answers but non of them work properly. The problem is **onActivityResult() not called in new nested fragment** and i have also checked the solution for this problem but didn't work either. Please suggest something. – Aparana Apr 16 '15 at 12:07
  • None of them worked?Strange. Check is the responsibile activity receives onActivityResult(). If yes, then have a callback in your Activity, trigger the callback method in your activity and receive it in your fragment, do your list update. You can alter the following solution for your need, http://developer.android.com/training/basics/fragments/communicating.html. May be in a reverse way. – Kartihkraj Duraisamy Apr 17 '15 at 06:56