Android View Pager deleting images from folder not refreshing - android

Whenever i delete my Image from my ViewPager. Then sometimes next Image will be deleted.or sometime's no image delete.
where i am wrong i dont know.
My GallaryActivity
public class GalleryActivity extends AppCompatActivity implements View.OnClickListener {
ImageButton imgBtnDelete;
TextView tvImageCount;
ViewPager galleryViewPager;
GalleryAdapter adapter;
private static String filePath = "";
public int mPosition = 0;
// File Code
public File mDirectory;
File[] imageList;
ArrayList<Integer> mTotalImages = new ArrayList<>();
ArrayList<String> mFilePaths = new ArrayList<>();
Uri[] mUrls;
String[] mFiles, mFileNames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the Status bar...Write Before setContentView()
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_gallery);
imgBtnDelete = (ImageButton) findViewById(R.id.imgBtnDelete);
imgBtnDelete.setOnClickListener(this);
// File Code
mDirectory = new File(android.os.Environment.getExternalStorageDirectory(), "CameraApp/Images");
imageList = mDirectory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
int imgLength = (imageList == null) ? 0 : imageList.length;
if (imgLength > 0) {
mFiles = new String[imgLength];
// add imgLength here for set Total Images in TextView
for (int k = 0; k < imageList.length; k++) {
mTotalImages.add(imgLength);
filePath = imageList[k].getAbsolutePath();
mFilePaths.add(filePath);
}
mFileNames = new String[imgLength];
tvImageCount.setVisibility(View.VISIBLE);
tvImageCount.setText(1 + "/" + mTotalImages.size());
mUrls = new Uri[imgLength];
int i, j = 0;
for (i = imgLength - 1; i >= 0; i--) {
mFiles[j] = imageList[i].getAbsolutePath();
mFileNames[j] = imageList[i].getName();
j++;
}
galleryViewPager = (ViewPager) findViewById(R.id.galleryViewPager);
adapter = new GalleryAdapter(this, mFiles);
galleryViewPager.setAdapter(adapter);
galleryViewPager.setOnPageChangeListener(pageChangeListener);
} else {
tvImageCount.setVisibility(View.INVISIBLE);
Toast.makeText(this, "Please capture some images from App!", Toast.LENGTH_SHORT).show();
}
}
OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mPosition = position;
tvImageCount.setText((position + 1) + "/" + mTotalImages.size());
Toast.makeText(GalleryActivity.this, "mPosition is : " + mPosition, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
private void openAlert() {
new AlertDialog.Builder(this)
.setTitle("Delete Image")
.setMessage("Are you sure you want to delete this Image?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
DeleteImage();
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.setCancelable(true)
.show();
}
my DeleteImage()
private void DeleteImage() {
File file = new File(mFilePaths.get(mPosition));
boolean deleted = file.delete();
if (deleted) {
mFilePaths.remove(mPosition);
if (mFilePaths.size() == 0) {
tvImageCount.setVisibility(View.INVISIBLE);
}
if (mFilePaths.size() != 0 && mFilePaths.size() != 1) {
adapter.notifyDataSetChanged();
galleryViewPager.setCurrentItem(mPosition + 1);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imgBtnDelete:
if (mDirectory.exists() && mDirectory != null && mFilePaths.size() != 0) {
openAlert();
} else {
Toast.makeText(this, "No Images to Delete!", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
and following is my GallaryAdapter of Viewpager
public class GalleryAdapter extends PagerAdapter {
private Context mContext;
private String[] mFiles;
public GalleryAdapter(Context mContext, String[] mFiles) {
this.mContext = mContext;
this.mFiles = mFiles;
}
#Override
public int getCount() {
return mFiles.length;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = mLayoutInflater.inflate(R.layout.gallary_viewpager_item, container, false);
ImageView mImageView = (ImageView) itemView.findViewById(R.id.imgViewCenterGallery);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap;
bitmap = BitmapFactory.decodeFile(mFiles[position], options);
mImageView.setImageBitmap(bitmap);
container.addView(itemView);
return itemView;
}
public int getItemPosition(Object object) {
return PagerAdapter.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;
}
}

Try this way
if (imgLength > 0) {
mFiles = new String[imgLength];
mFileNames = new String[imgLength];
mUrls = new Uri[imgLength];
int j=0;
for (int i = imgLength-1; i >= 0; i--) {
mFiles[j] = imageList[i].getAbsolutePath();
mFileNames[j] = imageList[i].getName();
j++;
Toast.makeText(this, "Image Name - " + Arrays.toString(mFileNames), Toast.LENGTH_SHORT).show();
galleryViewPager = (ViewPager) findViewById(R.id.galleryViewPager);
adapter = new GallerySlideImageAdapter(this, mFiles, mFileNames);
galleryViewPager.setAdapter(adapter);
}
} else {
Toast.makeText(this, "Please capture some images from App !", Toast.LENGTH_SHORT).show();
}

Sort your file list as per latest to older datetime and bind files in adapter.
File[] files = directory.listFiles(); //your files object
Arrays.sort(files, new Comparator<File>(){
public int compare(File f1, File f2)
{
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});

Related

while deleting image from arraylist image get deleted but after added new image to arraylist previous image loaded

This is the class where image recycler view is set and images are added from folder in array list and it is loaded to image view..my problem is when image is deleted it gets deleted but after new image added previous image get loaded in image view please review my code and give me proper solution for it..
private ImageAdapterone imageAdapterone;
File file;
MenuItem item;
ArrayList<String> f;// list of file paths
File[] listFile;
RecyclerView recyclerImage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
f = new ArrayList<String>();
getFromSdcard();
Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
System.out.println("memory is : " + maxMemory);
recyclerImage = (RecyclerView) findViewById(R.id.recyclerImage);
imageAdapterone = new ImageAdapterone();
int numberOfColumns = 2;
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
// GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),2,LinearLayoutManager.VERTICAL,false);
//gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerImage.setLayoutManager(gridLayoutManager);
recyclerImage.setAdapter(imageAdapterone);
recyclerImage.addOnItemTouchListener(new
RecyclerItemClickListener(CustomActivity.this, recyclerImage, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
item.setVisible(false);
// correctmark.setVisibility(View.INVISIBLE);
if (position == 0) {
gotoNext(position, "rougescript_regular", R.color.colorWhite);
}
if (position == 1) {
gotoNext(position, "tangerine_regular", R.color.colorWhite);
}
if (position == 2) {
gotoNext(position, "gabriola", R.color.colorWhite);
}
if (position == 3) {
gotoNext(position, "tangerine_regular", R.color.colorBlack);
}
if (position == 4) {
gotoNext(position, "tangerine_regular", R.color.colorWhite);
}
if (position == 5) {
gotoNext(position, "tangerine_regular", R.color.colorWhite);
}
if (position == 6) {
gotoNext(position, "DancingScript-Regular", R.color.colorBlack);
}
if (position == 7) {
gotoNext(position, "jimnightshade_regular", R.color.colorWhite);
}
if (position == 8) {
gotoNext(position, "gabriola", R.color.colorPrimaryDark);
}
if (position == 9) {
gotoNext(position, "rougescript_regular", R.color.colorBlack);
}
if (position == 10) {
gotoNext(position, "rougescript_regular", R.color.colorBlack);
}
if (position == 11) {
gotoNext(position, "jimnightshade_regular", R.color.colorWhite);
}
if (position == 12) {
Intent intent = new Intent(CustomActivity.this, EditSettingActivity.class);
startActivity(intent);
}
for (int i = 13; i < f.size(); i++) {
goToNextActivity(position, "jimnightshade_regular", i, R.color.colorWhite);
}
SharedPreferences.Editor editor = MyApplication.getPref().edit();
editor.putInt("ImagePosition", position);
editor.apply();
}
#Override
public void onLongItemClick(View view, int position) {
//Toast.makeText(CustomActivity.this, position, Toast.LENGTH_SHORT).show();
System.out.println("delete file position is on: " + position);
for (int i = 13; i < f.size(); i++) {
// for (int i = 13; i >= 0; i--) {
if (position == i) {
item.setVisible(true);
SharedPreferences.Editor editor = MyApplication.getPref().edit();
editor.putInt("DeletePosition", i);
editor.apply();
System.out.println("delete file position is on: " + MyApplication.getPref().getInt("DeletePosition", 0));
}
}
}
}));
}
private void goToNextActivity(int position, String font, int i, int color) {
if (position == i) {
Intent intent = new Intent(CustomActivity.this, FullImageActivity.class);
System.out.println("array position is : " + f.get(i));
intent.putExtra("idone", f.get(i));
intent.putExtra("font", font);
intent.putExtra("CurrentFlag", "1");
SharedPreferences.Editor editor = MyApplication.getPref().edit();
editor.putString("ArrayPosition", f.get(i));
editor.putInt("Color", color);
editor.apply();
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main2, menu);
item = menu.findItem(R.id.action_delete);
item.setOnMenuItemClickListener(this);
return super.onCreateOptionsMenu(menu);
}
public void getFromSdcard() {
file = new File(android.os.Environment.getExternalStorageDirectory(), "Wallpaper Pack");
System.out.println("folder is sdcard : " + file);
if (file.isDirectory()) {
listFile = file.listFiles();
System.out.println("list of file is: " + listFile.length);
for (int i = 0; i < listFile.length; i++) {
f.add((listFile[i].getAbsolutePath()));
System.out.println("path is : " + listFile[i].getAbsolutePath());
}
}
}
public void gotoNext(int id, String font, int color) {
Intent intent = new Intent(CustomActivity.this, FullImageActivity.class);
intent.putExtra("id", id);
intent.putExtra("font", font);
intent.putExtra("fonttag", "1");
intent.putExtra("CurrentFlag", "0");
intent.putExtra("color", color);
SharedPreferences.Editor editor = MyApplication.getPref().edit();
editor.putString("NewFont", font);
editor.putInt("Color", color);
editor.apply();
startActivity(intent);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onDestroy() {
super.onDestroy();
Glide.get(this).clearMemory();
}
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_delete:
File(listFile[MyApplication.getPref().getInt("DeletePosition",0)].
getAbsolutePath());
+listFile[MyApplication.getPref().getInt("DeletePosition",0)]
.getAbsolutePath());
imageAdapterone.notifyItemRemoved(MyApplication.getPref()
.getInt("DeletePosition",0));
File file = new
File(listFile[MyApplication.getPref().getInt("DeletePosition",
0)].getAbsolutePath());
file.delete();
imageAdapterone.deleteItem(MyApplication.getPref()
.getInt("DeletePosition", 0));
imageAdapterone.notifyDataSetChanged();
item.setVisible(false);
break;
}
return false;
}
Now this is the code for adapter where image arraylist is set using an glide..
public class ImageAdapterone extends RecyclerView.Adapter<ImageAdapterone.SingleTestRowHolder> {
Context context;
Bitmap myBitmap;
#Override
public SingleTestRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.galleryitem, null);
SingleTestRowHolder mh = new SingleTestRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ImageAdapterone.SingleTestRowHolder holder, int position) {
byte[] encodeByte = Base64.decode(f.get(position), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
if (position > 12) {
holder.customText.setVisibility(View.VISIBLE);
} else {
holder.customText.setVisibility(View.INVISIBLE);
}
System.out.println("IMAGE POSITION: " + f.get(position));
Glide.with(holder.thumbImage.getContext())
.load(f.get(position))
.override(300, 300)
.centerCrop()
StringSignature(String.valueOf(System.currentTimeMillis())))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(holder.thumbImage);
}
#Override
public int getItemCount() {
return f.size();
}
public void deleteItem(int index) {
System.out.println("INDEX OF DELETED ITEM: " + index);
f.remove(index);
notifyItemRemoved(index);
notifyItemRangeChanged(index, f.size());
System.out.println("IMAGES SIZE: " + f.size());
}
public class SingleTestRowHolder extends RecyclerView.ViewHolder {
ImageView thumbImage;
TextView customText;
public SingleTestRowHolder(View itemView) {
super(itemView);
thumbImage = (ImageView) itemView.findViewById(R.id.thumbImage);
customText = (TextView) itemView.findViewById(R.id.customText);
}
}
}

How to view PPT from Listview in Android

My Fragment Activity
public class MessagesFragment extends Fragment {
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PPTAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
public MessagesFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.search_via_mobile_ppt, container, false);
lv_pdf = (ListView) rootView.findViewById(R.id.lv_pdf);
init();
// Inflate the layout for this fragment
return rootView;
}
public void init() {
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Intent intent = new Intent(getApplicationContext(), PPt.class);
// intent.putExtra("position", i);
// startActivity(intent);
//
// Log.e("Position", i + "");
File file = new File(dir.toString());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/vnd.ms-powerpoint");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
}
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
getfile(listFile[i]);
} else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(".ppt")) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {
}
}
if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PPTAdapter(getContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PPTAdapter(getContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
} else {
Toast.makeText(getContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
My Adapter Activity
public class PPTAdapter extends ArrayAdapter<File> {
Context context;
ViewHolder viewHolder;
ArrayList<File> al_pdf;
public PPTAdapter(Context context, ArrayList<File> al_pdf) {
super(context, R.layout.adapter_pdf, al_pdf);
this.context = context;
this.al_pdf = al_pdf;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_pdf.size() > 0) {
return al_pdf.size();
} else {
return 1;
}
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
if (view == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.adapter_pdf, parent, false);
viewHolder = new ViewHolder();
viewHolder.tv_filename = (TextView) view.findViewById(R.id.tv_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.tv_filename.setText(al_pdf.get(position).getName());
return view;
}
public class ViewHolder {
TextView tv_filename;
}
}
I want to open the PPT after it is being listed in my ListView.The listing of the PPT works fine but how to open it from the item of ListView I am stucked in this situation. Used the code as mentioned in onitemclicklistener of ListView.
And I got one PPT Viewer Library from here but I don't know that how to use it in Android Studio as it is for Ecllipse.
Change the code from this
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
to
startActivity(intent);
This will show the user options about any power-point viewers that they have installed and they can pick one.

How to refresh the Recyclerview when Image is deleted?

In my app, I want to delete the images, which i have done, but every time I delete image, it doesn't refresh the recyclerView. But when I again open the folder then Recyclerview is refreshed..
I want to refresh Recyclerview when image is deleted
Here is my code for Deleting an image
#Override
protected void onExternalStoragePermissionGranted() {
super.onExternalStoragePermissionGranted();
storage = SimpleStorage.getExternalStorage();
checkForGalleryDirectories();
File galleryFiles = new File(path);
pathContainerView.removeAllViews();
pathContainerView.addView(createTitleView("Location: " + galleryFiles.getAbsolutePath()));
File[] files = galleryFiles.listFiles();
List<GalleryItem> galleryItems = new ArrayList<>();
String lastModifiedDate = "UNDEFINED";
SimpleDateFormat formatter = new SimpleDateFormat("E-MMM-yyyy");
if (files != null) {
this.adapter.clearGallery();
for (File file : files) {
if (file.isDirectory()) {
}
String formattedPicDate = formatter.format(lastMod);
if (lastModifiedDate != null && !lastModifiedDate.equals(formattedPicDate)) {
lastModifiedDate = formattedPicDate;
galleryItems.add(new Header(lastModifiedDate));
countgridsize++;
}
galleryItems.add(new Picture(file.getPath(), file.getName()));
}
}
}
this.adapter.setGalleryList(galleryItems);
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
final List<String> list = GalleryAdapter.list;
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Toast.makeText(GalleryBrowserActivity.this, "Delete Successfully..", Toast.LENGTH_SHORT).show();
for (String fileNameStr : list) {
String[] parts = fileNameStr.split("/");
String part1 = parts[5]; // 004
String part2 = parts[6]; // 034556
storage.deleteFile(".AliRehman/" + part1, part2);
}
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(GalleryBrowserActivity.this);
builder.setMessage("Are you sure?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
return true;
My adapter Class
public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context;
private final LayoutInflater layoutInflater;
private List<GalleryItem> galleryList = new ArrayList<>();
private OnItemClickListener mItemClickListener;
public static List<String> list;
public GalleryAdapter(Context context, LayoutInflater layoutInflater) {
this.context = context;
this.layoutInflater = layoutInflater;
}
public void setItemClickListener(OnItemClickListener listener) {
mItemClickListener = listener;
}
public void setGalleryList(List<GalleryItem> galleryList) {
this.galleryList = galleryList;
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return this.galleryList.get(position).getItemType();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == GalleryItem.HEADER_TYPE) {
return new HeaderHolder(layoutInflater.inflate(R.layout.item_header, parent, false));
} else {
return new PictureHolder(layoutInflater.inflate(R.layout.item_picture, parent, false));
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
GalleryItem item = galleryList.get(position);
if(getItemViewType(position) == GalleryItem.HEADER_TYPE) {
bindHeaderHolder((HeaderHolder) holder, (Header) item);
}
else {
bindPictureHolder((PictureHolder) holder, (Picture) item);
}
}
private void bindPictureHolder(final PictureHolder holder, Picture picture) {
Glide.with(context).load(Uri.fromFile(new File(picture.getPath()))).into(holder.pictureThumbnail);
boolean itemselected=picture.getSelected();
if(itemselected)
{
Log.d("ViewVisiblePicture", String.valueOf(picture.getPath()));
holder.overlayView.setVisibility(View.VISIBLE);
}
else
holder.overlayView.setVisibility(View.GONE);
}
private void bindHeaderHolder(HeaderHolder holder, Header header) {
holder.headerTxt.setText(header.getName());
}
#Override
public int getItemCount() {
return this.galleryList.size();
}
public void clearGallery() {
this.galleryList.clear();
notifyDataSetChanged();
}
public class HeaderHolder extends RecyclerView.ViewHolder {
private TextView headerTxt;
public HeaderHolder(View itemView) {
super(itemView);
this.headerTxt = (TextView) itemView.findViewById(R.id.headerTxt);
}
}
public class PictureHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
public ImageView pictureThumbnail;
public FrameLayout overlayView;
public PictureHolder pictureHolder;
private boolean[] thumbnailsselection;
public PictureHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
this.pictureThumbnail = (ImageView) itemView.findViewById(R.id.pictureThumbnail);
this.overlayView = (FrameLayout) itemView.findViewById(R.id.overlayView);
}
#Override
public boolean onLongClick(View view) {
list=new ArrayList<>();
if (mItemClickListener != null) {
mItemClickListener.onItemLongClick(getAdapterPosition());
this.overlayView.setVisibility(View.VISIBLE);
Picture model=(Picture) galleryList.get(getAdapterPosition());
//galleryList.get(getAdapterPosition());
model.setSelected(true);
list.add(model.getPath());
Log.d("Path1", model.getPath());
final int len = GalleryBrowserActivity.countgridsize;
int count = 0;
/* String selectImages = "";
for (int i = 0; i < len; i++) {
*//*if (pictureHolder..get(i).selection) {
count++;
selectImages = selectImages
+ pictureHolder.images.get(i).id + ",";
}*//*
this.overlayView.setVisibility(View.VISIBLE);
}
Log.d("Length", len+"");
if (count == 0) {
Toast.makeText(context,
"Please select at least one image",
Toast.LENGTH_LONG).show();
}*/
return true;
}
Log.d("hi","hello Image");
notifyDataSetChanged();
return false;
}
#Override
public void onClick(View v)
{
int position = getAdapterPosition();
Picture picture = (Picture) galleryList.get(position);
if(GalleryBrowserActivity.mActionMode!=null)
{
Log.d("Visiblilty","visible");
Picture model=(Picture) galleryList.get(getAdapterPosition());
if(model.getSelected()){
this.overlayView.setVisibility(View.GONE);
model.setSelected(false);
list.remove(model.getPath());
}else {
mItemClickListener.onItemClick(position, v, picture.getPath());
Toast.makeText(context, "visible" + picture.getPath(), Toast.LENGTH_LONG).show();
this.overlayView.setVisibility(View.VISIBLE);
model.setSelected(true);
list.add(model.getPath());
Log.d("Path2", model.getPath());
}
notifyDataSetChanged();
}
if (GalleryBrowserActivity.mActionMode==null) {
Log.d("Visible","invisible");
Toast.makeText(context,"invisible",Toast.LENGTH_LONG).show();
mItemClickListener.onItemClick(position, v, picture.getPath());
}
}
}
public interface OnItemClickListener
{
void onItemClick(int position, View v, String picturePath);
void onItemLongClick(int position);
}
}
I would suggest you to make below changes:
In GalleryAdapter :
From:
public static List<String> list;
To:
public static List< GalleryItem > list;
And add a function in your GalleryAdapter to remove items from your galleryList:
public void removeItem(GalleryItem item){
this.galleryList.remove(item);
notifyDataSetChanged();
}
And In PictureHolder:
#Override
public boolean onLongClick(View view) {
list=new ArrayList<>();
if (mItemClickListener != null) {
mItemClickListener.onItemLongClick(getAdapterPosition());
this.overlayView.setVisibility(View.VISIBLE);
GalleryItem model=(GalleryItem) galleryList.get(getAdapterPosition());
//galleryList.get(getAdapterPosition());
((Picture)model).setSelected(true);
list.add(model);
Log.d("Path1", ((Picture)model).getPath());
final int len = GalleryBrowserActivity.countgridsize;
int count = 0;
return true;
}
Log.d("hi","hello Image");
notifyDataSetChanged();
return false;
}
#Override
public void onClick(View v)
{
int position = getAdapterPosition();
GalleryItem picture = (GalleryItem) galleryList.get(position);
if(GalleryBrowserActivity.mActionMode!=null)
{
Log.d("Visiblilty","visible");
GalleryItem model=(GalleryItem) galleryList.get(getAdapterPosition());
if(model.getSelected()){
this.overlayView.setVisibility(View.GONE);
((Picture)model).setSelected(false);
list.remove(model);
}else {
mItemClickListener.onItemClick(position, v, picture.getPath());
Toast.makeText(context, "visible" + picture.getPath(), Toast.LENGTH_LONG).show();
this.overlayView.setVisibility(View.VISIBLE);
((Picture)model).setSelected(true);
list.add(model);
Log.d("Path2", model.getPath());
}
notifyDataSetChanged();
}
if (GalleryBrowserActivity.mActionMode==null) {
Log.d("Visible","invisible");
Toast.makeText(context,"invisible",Toast.LENGTH_LONG).show();
mItemClickListener.onItemClick(position, v, picture.getPath());
}
}
In the above code I am trying to update the list with selected GallryItem objects.
And While deleting item after the DialogInterface.BUTTON_POSITIVE is clicked, update the code like below:
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Toast.makeText(GalleryBrowserActivity.this, "Delete Successfully..", Toast.LENGTH_SHORT).show();
for (GalleryItem item : list) {
this.adapter.removeItem(item);
String fileNameStr = ((Picture)item).getPath();
String[] parts = fileNameStr.split("/");
String part1 = parts[5]; // 004
String part2 = parts[6]; // 034556
storage.deleteFile(".AliRehman/" + part1, part2);
}
break;
The above code will also update the galleryList inside adapter and notify the dataset change. Please let me know if you face any issue while implementing it.
you have to notify your adapter after you delete your image. like below.
arrayAdapter.notifyDataSetChanged();
in your example you have to write above line after you click Yes in your AlertDialog.
All you need to do is call notifyDataSetChanged() which will notify the RecyclerView to re-bin the views again, thereby deleting any item as necessary.
Just add a method in your adapter class,
mAdapter.notifyDataSetChanged();
If you know the position of the particular item which is getting deleted, then it is RECOMMENDED to use,
mAdapter.notifyItemChanged(position);
This will give you a nice animation effect while deleting the item.

App widget listview design gets change when loading dynamic image using url android

Hi I'm using widget listview. I want to load image on each widget listview item so I have used below code to load image using url
public class ListProvider implements RemoteViewsService.RemoteViewsFactory {
private String TAG = ListProvider.class.getSimpleName();
private Context context = null;
private UserPreference userPreference;
private int appWidgetId;
private String feedsData, mLaneName, mLaneId;
private Tooteet.Collection collection;
private ArrayList<Item> mItems;
public ListProvider(Context context, Intent intent) {
this.context = context;
userPreference = new UserPreference(context);
appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
feedsData = intent.getStringExtra(LargeWidgetProvider.LARGE_WIDGET_LIST_DATA);
mLaneId = intent.getStringExtra(LargeWidgetProvider.WIDGET_LANE_ID);
mLaneName = intent.getStringExtra(LargeWidgetProvider.WIDGET_LANE_NAME);
if(mLaneId != null && mLaneName != null) {
collection = new Tooteet.Collection(feedsData, mLaneId, mLaneName);
}
mItems = getItems(collection);
}
public ArrayList<Item> getItems(Tooteet.Collection collection) {
ArrayList<Item> items = new ArrayList<>();
if (collection == null) {
return items;
}
int sectionFirstPosition = 0;
int i = 0;
for (Tooteet tooteet : collection.getItems()) {
int type = tooteet.getTweetType();
int viewType = VIEW_TYPE_TEXT;
switch (type) {
case TooteetType.TEXT:
case TooteetType.NOTE:
viewType = VIEW_TYPE_TEXT;
// add text;
break;
case TooteetType.PICTURE:
case TooteetType.DRAWING:
case TooteetType.VIDEO:
viewType = VIEW_TYPE_MEDIA;
// add media
break;
case TooteetType.AUDIO:
case TooteetType.DOCUMENT:
//case TooteetType.EXPENSE:
viewType = VIEW_TYPE_FILE;
// add file
break;
case TooteetType.MEASURE:
viewType = VIEW_TYPE_MEASURE;
break;
case TooteetType.EXPENSE:
viewType = VIEW_TYPE_EXPENSE;
break;
}
Log.d(TAG, "getItems -- tooteet: "+tooteet);
items.add(new Item("", false, tooteet, viewType, sectionFirstPosition, i));
i++;
}
return items;
}
#Override
public int getCount() {
Log.d(TAG, " getCount() -- mItems.size(): "+mItems.size());
return mItems.size();
}
#Override
public long getItemId(int position) {
return position;
}
/*
*Similar to getView of Adapter where instead of View
*we return RemoteViews
*
*/
#Override
public RemoteViews getViewAt(final int position) {
Log.d(TAG,"=============getViewAt position=========="+position);
RemoteViews remoteView = null;
final Item item = mItems.get(position);
if (item.mTooteet.getTweetType() == TooteetType.TEXT || item.mTooteet.getTweetType() == TooteetType.NOTE) {
remoteView = new RemoteViews(context.getPackageName(), R.layout.widget_feed_list_text);
remoteView.setImageViewResource(R.id.feed_type,R.drawable.feed_list_note);
} else if (item.mTooteet.getTweetType() == TooteetType.PICTURE || item.mTooteet.getTweetType() == TooteetType.DRAWING || item.mTooteet.getTweetType() == TooteetType.VIDEO) {
remoteView = new RemoteViews(context.getPackageName(), R.layout.widget_feed_list_image);
int drawable = R.drawable.feed_list_attachment;
if (item.mTooteet.getTweetType() == TooteetType.PICTURE) {
drawable = R.drawable.feed_list_picture;
} else if (item.mTooteet.getTweetType() == TooteetType.VIDEO) {
drawable = R.drawable.feed_list_video;
}else if(item.mTooteet.getTweetType() == TooteetType.DRAWING){
drawable = R.drawable.feed_list_drawing;
}
remoteView.setImageViewResource(R.id.feed_type,drawable);
try {
} catch (Exception e) {
e.printStackTrace();
}
Handler uiHandler = new Handler(Looper.getMainLooper());
final RemoteViews finalRemoteView1 = remoteView;
uiHandler.post(new Runnable(){
#Override
public void run() {
Picasso.with(context).load(item.mTooteet.getThumbUrl1()).into(
finalRemoteView1, R.id.feed_image,
new int[]{appWidgetId});
}
});
} else if (item.mTooteet.getTweetType() == TooteetType.AUDIO || item.mTooteet.getTweetType() == TooteetType.DOCUMENT) {
remoteView = new RemoteViews(context.getPackageName(), R.layout.widget_feed_list_audio);
int drawable;
if (item.mTooteet.getTweetType() == TooteetType.AUDIO) {
drawable = R.drawable.feed_list_audio;
} else {
drawable = FeedDocResourceHandler.getIconResForListDoc(item.mTooteet.getUniqueFileName());
}
remoteView.setImageViewResource(R.id.feed_type,drawable);
} else if (item.mTooteet.getTweetType() == TooteetType.MEASURE) {
remoteView = new RemoteViews(context.getPackageName(), R.layout.widget_feed_list_measure);
}else if (item.mTooteet.getTweetType() == TooteetType.EXPENSE) {
remoteView = new RemoteViews(context.getPackageName(), R.layout.widget_feed_list_expense);
}
remoteView.setTextViewText(R.id.feed_keywords, item.mTooteet.getKeywords());
if(!TextUtils.isEmpty(item.mTooteet.getTooteetText())){
remoteView.setViewVisibility(R.id.feed_text, View.VISIBLE);
remoteView.setTextViewText(R.id.feed_text, item.mTooteet.getTooteetText());
}else{
remoteView.setViewVisibility(R.id.feed_text, View.GONE);
}
if (!item.mTooteet.isLocationEmpty()) {
if (!TextUtils.isEmpty(item.mTooteet.getLocationString())) {
remoteView.setViewVisibility(R.id.feed_location, View.VISIBLE);
remoteView.setTextViewText(R.id.feed_location, item.mTooteet.getLocationString());
} else {
final RemoteViews finalRemoteView = remoteView;
ReverseGeocoder.with(Constants.getLanesApp()).load(item.mTooteet, new com.kwypesoft.lanes.location.GeocodeApi.OnLocationListener() {
#Override
public void onReceive(String location) {
if (!TextUtils.isEmpty(location)) {
finalRemoteView.setViewVisibility(R.id.feed_location, View.VISIBLE);
finalRemoteView.setTextViewText(R.id.feed_location, item.mTooteet.getLocationString());
item.mTooteet.setLocationString(location);
}else{
finalRemoteView.setViewVisibility(R.id.feed_location, View.GONE);
}
}
});
}
}else{
remoteView.setViewVisibility(R.id.feed_location, View.GONE);
}
final Intent fillInIntent = new Intent();
fillInIntent.setAction(LargeWidgetProvider.ACTION_TOAST);
final Bundle bundle = new Bundle();
bundle.putString(LargeWidgetProvider.WIDGET_LANE_ID, mLaneId);
bundle.putSerializable(DetailBase.FEED_DETAILS, item.mTooteet);
fillInIntent.putExtras(bundle);
remoteView.setOnClickFillInIntent(R.id.root, fillInIntent);
return remoteView;
}
#Override
public RemoteViews getLoadingView() {
return null;
}
#Override
public int getViewTypeCount() {
return 5;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public void onCreate() {
}
#Override
public void onDataSetChanged() {
}
#Override
public void onDestroy() {
}
private static class Item{
boolean isHeader;
String header;
public Tooteet mTooteet;
int viewType;
int firstPosition;
int itemPosition;
public Item(String header, boolean isHeader, Tooteet tooteet, int type, int firstPosition, int itemPosition) {
this.header = header;
this.isHeader = isHeader;
mTooteet = tooteet;
this.viewType = type;
this.firstPosition = firstPosition;
this.itemPosition = itemPosition;
}
}
}
But this will change my widget UI design and it shows only one listview item at a time.
where i have only one appWidgetId in listview provider class which extends RemoteViewsService.RemoteViewsFactory. I do not know. What's went wrong. Could you please suggest me a idea to fix it?
Picasso offers much more than just downloading image. It can resize the image, transform before it is displayed in ImageView. So you can resize or transform your image as follow.
Picasso.with(this)
.load("YOUR IMAGE URL HERE")
.error(R.drawable.ic_error_fallback) // optional
.resize(250, 200) // optional
.rotate(90) // optional
.into(imageView);
thank you.
I have fix my issue using Universal image loader like below,
public class YourViewsFactory implements RemoteViewsService.RemoteViewsFactory
{
Map<Integer, Boolean> flags = Collections.synchronizedMap(new HashMap<Integer, Boolean>());
Bitmap mBitmap;
Handler handler = new Handler(Looper.getMainLooper());
#Override
public RemoteViews getViewAt(final int position)
{
final RemoteViews row = new RemoteViews(ctxt.getPackageName(), R.layout.row);
flags.put(position, false);
handler.post(new Runnable()
{
#Override
public void run()
{
m_imgLoader.loadImage(YOUR_IMAGE_URL, new SimpleImageLoadingListener()
{
#Override
public void onLoadingStarted(String imageUri, View view)
{
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason)
{
flags.put(position, true);
}
#Override
public void onLoadingCancelled(String imageUri, View view)
{
flags.put(position, true);
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap bitmap)
{
mBitmap = bitmap;
flags.put(position, true);
}
});
}
});
while (!flags.get(position))
{
try
{
Thread.sleep(100);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
flags.put(position, false);
if (mBitmap != null)
{
row.setImageViewBitmap(R.id.ivPoster, mBitmap);
} else
{
row.setImageViewResource(R.id.ivPoster, R.drawable.cw);
}
mBitmap = null;
} // End of getViewAt override
} // End of class
Please make use of it.

Android Universal Image Loader and GridView "Out of memory" on second launch

I have checked all the related posts so far, but did not managed to fix this "Out of memory on a 1843216-byte allocation" error my GridView activity generates.
Basically this activity displays the images from the phone's gallery in a GridView (as a multiple image picker), at first it loads everything just fine, at the second try I get the memory error and the GridView skips loading some of the image thumbnails.
I have disabled the memory caching by: ".cacheInMemory(false)", and using only disk caching with fixed ImageView width and height, but still got the memory error.
Could someone help me out? Thanks!
The CustomGalleryActivity, showing all pictures on the phone:
public class CustomGalleryActivity extends Activity {
GridView gridGallery;
Handler handler;
GalleryAdapter adapter;
ImageView imgNoMedia;
Button btnGalleryOk;
String action;
private ImageLoader imageLoader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
action = getIntent().getAction();
if (action == null) {
finish();
}
initImageLoader();
init();
}
private void initImageLoader() {
try {
String CACHE_DIR = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/.temp_tmp";
new File(CACHE_DIR).mkdirs();
File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(),
CACHE_DIR);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.cacheInMemory(false)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(getBaseContext())
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.defaultDisplayImageOptions(defaultOptions)
.discCache(new UnlimitedDiscCache(cacheDir))
.tasksProcessingOrder(QueueProcessingType.LIFO);
//.memoryCache(new WeakMemoryCache());
L.writeLogs(false);
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.destroy();
imageLoader.init(config);
} catch (Exception e) {
}
}
private void init() {
handler = new Handler();
gridGallery = (GridView) findViewById(R.id.gridGallery);
gridGallery.setFastScrollEnabled(true);
adapter = new GalleryAdapter(getApplicationContext(), imageLoader);
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader,
true, true);
gridGallery.setOnScrollListener(listener);
if (action.equalsIgnoreCase(Action.ACTION_MULTIPLE_PICK)) {
findViewById(R.id.llBottomContainer).setVisibility(View.VISIBLE);
gridGallery.setOnItemClickListener(mItemMulClickListener);
adapter.setMultiplePick(true);
} else if (action.equalsIgnoreCase(Action.ACTION_PICK)) {
findViewById(R.id.llBottomContainer).setVisibility(View.GONE);
gridGallery.setOnItemClickListener(mItemSingleClickListener);
adapter.setMultiplePick(false);
}
gridGallery.setAdapter(adapter);
imgNoMedia = (ImageView) findViewById(R.id.imgNoMedia);
btnGalleryOk = (Button) findViewById(R.id.btnGalleryOk);
btnGalleryOk.setOnClickListener(mOkClickListener);
new Thread() {
#Override
public void run() {
Looper.prepare();
handler.post(new Runnable() {
#Override
public void run() {
adapter.addAll(getGalleryPhotos());
checkImageStatus();
}
});
Looper.loop();
};
}.start();
}
private void checkImageStatus() {
if (adapter.isEmpty()) {
imgNoMedia.setVisibility(View.VISIBLE);
} else {
imgNoMedia.setVisibility(View.GONE);
}
}
View.OnClickListener mOkClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<CustomGallery> selected = adapter.getSelected();
String[] allPath = new String[selected.size()];
for (int i = 0; i < allPath.length; i++) {
allPath[i] = selected.get(i).sdcardPath;
}
Intent data = new Intent().putExtra("all_path", allPath);
setResult(RESULT_OK, data);
finish();
}
};
AdapterView.OnItemClickListener mItemMulClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
//adapter.changeSelection(v, position);
if (adapter.getSelected().size() >= 15) {
Toast.makeText(getApplicationContext(), "Max. 15 de poze pot fi selectate o data!", Toast.LENGTH_LONG).show();
} else {
adapter.changeSelection(v, position);
}
}
};
AdapterView.OnItemClickListener mItemSingleClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
CustomGallery item = adapter.getItem(position);
Intent data = new Intent().putExtra("single_path", item.sdcardPath);
setResult(RESULT_OK, data);
finish();
}
};
private ArrayList<CustomGallery> getGalleryPhotos() {
ArrayList<CustomGallery> galleryList = new ArrayList<CustomGallery>();
try {
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
#SuppressWarnings("deprecation")
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
null, null, orderBy);
if (imagecursor != null && imagecursor.getCount() > 0) {
while (imagecursor.moveToNext()) {
CustomGallery item = new CustomGallery();
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
item.sdcardPath = imagecursor.getString(dataColumnIndex);
galleryList.add(item);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// show newest photo at beginning of the list
Collections.reverse(galleryList);
return galleryList;
}
}
And its CustomAdapter:
public class GalleryAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater infalter;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public GalleryAdapter(Context c, ImageLoader imageLoader) {
infalter = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = c;
this.imageLoader = imageLoader;
// clearCache();
}
#Override
public int getCount() {
return data.size();
}
#Override
public CustomGallery getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void setMultiplePick(boolean isMultiplePick) {
this.isActionMultiplePick = isMultiplePick;
}
public void selectAll(boolean selection) {
for (int i = 0; i < data.size(); i++) {
data.get(i).isSeleted = selection;
}
notifyDataSetChanged();
}
public boolean isAllSelected() {
boolean isAllSelected = true;
for (int i = 0; i < data.size(); i++) {
if (!data.get(i).isSeleted) {
isAllSelected = false;
break;
}
}
return isAllSelected;
}
public boolean isAnySelected() {
boolean isAnySelected = false;
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
isAnySelected = true;
break;
}
}
return isAnySelected;
}
public ArrayList<CustomGallery> getSelected() {
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
dataT.add(data.get(i));
}
}
return dataT;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
} else {
data.get(position).isSeleted = true;
}
((ViewHolder) v.getTag()).imgQueueMultiSelected.setSelected(data
.get(position).isSeleted);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = infalter.inflate(R.layout.gallery_item, null);
holder = new ViewHolder();
holder.imgQueue = (ImageView) convertView
.findViewById(R.id.imgQueue);
holder.imgQueueMultiSelected = (ImageView) convertView
.findViewById(R.id.imgQueueMultiSelected);
if (isActionMultiplePick) {
holder.imgQueueMultiSelected.setVisibility(View.VISIBLE);
} else {
holder.imgQueueMultiSelected.setVisibility(View.GONE);
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imgQueue.setTag(position);
try {
imageLoader.displayImage("file://" + data.get(position).sdcardPath,
holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgQueueMultiSelected
.setSelected(data.get(position).isSeleted);
}
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgQueueMultiSelected;
}
public void clearCache() {
imageLoader.clearDiscCache();
imageLoader.clearMemoryCache();
}
public void clear() {
data.clear();
notifyDataSetChanged();
}
}
Try to do this with Picasso library instead of using image loader library. Hope this may helpful for you.
https://github.com/square/picasso

Categories

Resources