Dynamically refresh gridview when image replaced. notifyDataSetChanged() not working - android

I have a GridView that loads images from SD card (if present) otherwise some default images. Once images are loaded, the user can select any image cell and take a new picture. When default pictures are loaded in GridView and user takes a picture, the GridView updates and shows the image - but if user clicks the cell again and takes a new picture, then GridView is not updated. Only when I kill the app and restart it, then the new picture appears.
I have tried notifyDataSetChanged() but it doesn't work when image is refreshed.
Here is the code:
public class Fragment1 extends SherlockFragment {
...
private Integer[] mThumbIds = { R.drawable.fr, R.drawable.siderelaxed3,
R.drawable.br, R.drawable.fdbth, R.drawable.bdb, R.drawable.bls,
R.drawable.fls, R.drawable.mm };
private ImageAdapter imageAdapter;
ArrayList<String> f = new ArrayList<String>();// list of file paths
File[] listFile;
ImageLoader imageLoader;
Context context;
boolean needToRefresh = true;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
date = util.getCurrentDate();
Bundle bundle = this.getArguments();
date = bundle.getString(MyCommons.SELECTED_DATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.picturerecord, container,
false);
getFromSdcard();
Grid = (GridView) mainView
.findViewById(R.id.pictureRecordGrid);
imageAdapter = new ImageAdapter();
Grid.setAdapter(imageAdapter);
imageLoader = new ImageLoader(context, 4);
try {
ourClass = Class
.forName("cameraOpen");
ourIntent = new Intent(context, ourClass);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
poseGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
startActivityForResult(ourIntent, CAMERA_REQUEST);
poseSelected = position;
}
});
return mainView;
}
public void getFromSdcard() {
f.clear();
for (int i = 0; i < MyCommons.POSES_TO_LOAD.length; i++) {
String pose = MyCommons.pose_names[i];
String path = MyCommons.rootPath + File.separator + pose
+ File.separator + date;
File imgFile = new File(path);
if (imgFile.exists()) {
f.add(path);
Log.d(TAG, "image is present at:" + path);
} else {
f.add("loaddefault");
}
}
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return f.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 (needToRefresh == true) {
convertView = null;
Log.d(TAG, "NEEDED REFRESH");
needToRefresh = false;
}
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.picturerecorddata,
null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.pictureRecordImage);
holder.textview = (TextView) convertView.findViewById(R.id.pictureRecordText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (f.get(position).equals("loaddefault")) {
DefaultImageLoader defaultImages = new DefaultImageLoader(holder.imageview);
defaultImages.execute(position);
} else {
imageLoader.DisplayImage(f.get(position), holder.imageview, mThumbIds[position], position);
}
holder.textview.setText(MyCommons.pose_names[position]);
return convertView;
}
}
class ViewHolder {
ImageView imageview;
TextView textview;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
Bitmap photo = BitmapFactory.decodeByteArray(
data.getByteArrayExtra("BitmapImage"), 0,
data.getByteArrayExtra("BitmapImage").length);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File root = new File(MyCommons.rootPath);
if (!root.exists()) {
root.mkdirs();
Log.d(TAG, "Created Progress pics directory.");
}
String poseName = MyCommons.pose_names[poseSelected];
File pose_dir = new File(root + File.separator + poseName);
if (!pose_dir.exists()) {
pose_dir.mkdirs();
Log.d(TAG, "Created" + pose_dir + " pics directory.");
}
String tempFileName = root + File.separator + poseName + File.separator + date;
File tempFile = new File(tempFileName);
if (tempFile.exists()) {
Log.d(TAG, "File already exist. deleteing it and will write new file:" + tempFileName);
tempFile.delete();
}
util.saveImage(bytes, pose_dir, date);
Log.d(TAG, "image saved. Reloading adapter:\n" + tempFileName);
f.remove(tempFileName);
getFromSdcard();
f.add(poseSelected, tempFileName);
//f.clear();
//f.addAll(f);
imageAdapter.notifyDataSetChanged();
Grid.invalidateViews();
Grid.setAdapter(imageAdapter);
}
}
}
...
}

you need to replace an image in list f with new picture and then call notify, adapter using only items in f for diplaying

Related

Expandable Listview slow performance in Android

I want to make my expandable list smooth.
After looking a lot in the internet,
I added a viewHolder and changed my method where I load the data to be asynchronously. But my list is still slow!!!.
Can you take a look? I added the activity where I load asynchronously the data with my DataProvider and then I init my adapter. This help me to see my activity and a spinner until the data is loaded and then updated on my view.
But I dont have a fluid list when I scroll or when I try to expand a category. Can you help and tell me what to change ? I think that it can be the images but I save them locally to make it faster (I added my methods) and it can be something else....
MyActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set layout for this activity
setContentView(R.layout.expandable_list);
// Set actionbar title
getActionBar().show();
getActionBar().setTitle(Html.fromHtml("<font color='#fffffff'>Groups</font>"));
if (loggedUserId != null)
Log.d("TAG", "My Groups for user ID: " + loggedUserId);
// Connect between buttons to layout id
expandableListView = (ExpandableListView) findViewById(R.id.exp_list);
spinner = (ProgressBar) findViewById(R.id.spinner);
createCategoryButton = (ImageButton) findViewById(R.id.createCategory);
textLoading = (TextView) findViewById(R.id.textLoading);
// Loading data to expandable group list asynchronously
AsyncTask<String, String, HashMap<String, List<Group>>> task = new AsyncTask<String, String, HashMap<String, List<Group>>>() {
#Override
protected HashMap<String, List<Group>> doInBackground(String... params) {
return DataProvider.getInfo();
}
#Override
protected void onPostExecute(HashMap<String, List<Group>> listHashMap) {
super.onPostExecute(listHashMap);
// Setting adapter and creating group list
groupCategories = listHashMap;
groupsList = new ArrayList<String>(groupCategories.keySet());
adapter = new Adapter(GroupsListActivity.this, groupCategories, groupsList, GroupsListActivity.this);
expandableListView.setAdapter(adapter);
// Hide spinner after loading
spinner.setVisibility(View.GONE);
textLoading.setVisibility(View.GONE);
}
};
task.execute();
My adapter:
#Override
public View getGroupView(final int parent, boolean isExpanded, View convertView, ViewGroup parentView) {
final String categoryName = (String) getGroup(parent);
ParentViewHolder pHolder = null;
if (convertView == null) {
// Creates a ViewHolder and store references to layouts we want to bind data to.
pHolder = new ParentViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.expandable_list_parent, parentView, false);
// Connect between buttons to layout id
pHolder.categoryNameTextView = (TextView) convertView.findViewById(R.id.categoryName);
pHolder.editCategory = (ImageButton) convertView.findViewById(R.id.editCategory);
pHolder.deleteCategory = (ImageButton) convertView.findViewById(R.id.deleteCategory);
//Save holder
convertView.setTag(pHolder);
} else {
// Get the ViewHolder back
pHolder = (ParentViewHolder) convertView.getTag();
}
// Hide edit and delete button for category name Others
if (categoriesList.get(parent).equals("Others")) {
pHolder.editCategory.setVisibility(View.GONE);
pHolder.deleteCategory.setVisibility(View.GONE);
} else {
pHolder.editCategory.setVisibility(View.VISIBLE);
pHolder.deleteCategory.setVisibility(View.VISIBLE);
}
// Set category name on row
pHolder.categoryNameTextView.setTypeface(null, Typeface.BOLD);
pHolder.categoryNameTextView.setText(categoryName + ": " + getChildrenCount(parent));
// Set edit category button listener
final ParentViewHolder finalPHolder = pHolder;
pHolder.editCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalPHolder.editCategory.setEnabled(false);
editCategoryName(activity, finalPHolder.categoryNameTextView.getText().toString().toString().split(": ")[0], finalPHolder.editCategory, parent);
}
});
// Set delete category button listener
pHolder.deleteCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalPHolder.deleteCategory.setEnabled(false);
deleteCategory(activity, categoryName, finalPHolder.deleteCategory);
}
});
return convertView;
}
#Override
public View getChildView(final int parent, final int child, boolean lastChild, View convertView, ViewGroup parentView) {
final Group group = (Group) getChild(parent, child);
ChildViewHolder cHolder = null;
if (convertView == null) {
// Creates a ViewHolder and store references to layouts we want to bind data to.
cHolder = new ChildViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.expandable_list_child, parentView, false);
// Connect between buttons to layout id
cHolder.groupImage = (ImageView) convertView.findViewById(R.id.groupImage);
cHolder.groupName = (TextView) convertView.findViewById(R.id.groupName);
cHolder.moveCategory = (ImageButton) convertView.findViewById(R.id.moveCategory);
cHolder.groupFavoritesButton = (ImageButton) convertView.findViewById(R.id.groupFavorites);
cHolder.groupLeaveGroupButton = (Button) convertView.findViewById(R.id.groupLeave);
cHolder.groupImageProgressbar = (ProgressBar) convertView.findViewById(R.id.groupImageProgressBar);
//Save holder
convertView.setTag(cHolder);
} else {
// Get the ViewHolder back
cHolder = (ChildViewHolder) convertView.getTag();
}
// Set group name on row
cHolder.groupName.setText(group.getName());
// Load group image
cHolder.groupImageProgressbar.setVisibility(View.VISIBLE);
final ChildViewHolder finalHolder = cHolder;
Model.getInstance().getGroupImage(group.getImageName(), new Model.LoadImageListener() {
#Override
public void onResult(Bitmap imageBmp) {
if (imageBmp != null) {
finalHolder.groupImage.setImageBitmap(imageBmp);
finalHolder.groupImageProgressbar.setVisibility(View.GONE);
finalHolder.groupImage.setVisibility(View.VISIBLE);
}
}
});
// Set move category button listener
cHolder.moveCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.moveCategory.setEnabled(false);
showDialogMoveCategory(activity, group.getGroupID(), finalHolder.moveCategory);
}
});
// After click on group image - open profile for this group
cHolder.groupImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onGroupSelected(group.getGroupID());
}
});
// Setting favorite Button Image
boolean isFavorite = Model.getInstance().groupIsFavorite(loggedUserId, group.getGroupID());
if (isFavorite)
cHolder.groupFavoritesButton.setBackgroundResource(R.mipmap.favorites_on);
else
cHolder.groupFavoritesButton.setBackgroundResource(R.mipmap.favorites_off);
// Setting favorite Button Action
cHolder.groupFavoritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add group to favorites
if (!Model.getInstance().groupIsFavorite(loggedUserId, group.getGroupID())) {
finalHolder.groupFavoritesButton.setBackgroundResource(R.mipmap.favorites_on);
Toast.makeText(activity,
"The group " + group.getName() + " was added to favorites", Toast.LENGTH_SHORT).show();
Model.getInstance().changeFavoriteStatus(loggedUserId, group.getGroupID(), "true");
} else {
// Delete group from favorites
finalHolder.groupFavoritesButton.setBackgroundResource(R.mipmap.favorites_off);
Toast.makeText(activity,
"The group " + group.getName() + " was removed from favorites", Toast.LENGTH_SHORT).show();
Model.getInstance().changeFavoriteStatus(loggedUserId, group.getGroupID(), "false");
}
}
});
// After click on group action - leave group
cHolder.groupLeaveGroupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.groupLeaveGroupButton.setEnabled(false);
showDialogLeaveGroup(activity, "Are you sure ?", "This action will remove yourself from the group " + group.getName(), group.getGroupID(), parent, child);
finalHolder.groupLeaveGroupButton.setEnabled(true);
}
});
return convertView;
}
Images methods:
public void getGroupImage(final String imageName, final LoadImageListener listener) {
AsyncTask<String, String, Bitmap> task = new AsyncTask<String, String, Bitmap>() {
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bmp = loadImageFromFile(imageName); //first try to find the image on the device
// Bitmap bmp = null;
if (bmp == null) { //if image not found - try downloading it from parse
bmp = modelParse.getGroupImage(imageName);
if (bmp != null)
saveImageToFile(bmp, imageName); //save the image locally for next time *****
}
Bitmap scaledBitmap = scaleDown(bmp, 200, true);
return scaledBitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
listener.onResult(result);
}
};
task.execute();
}
private void saveImageToFile(Bitmap imageBitmap, String imageFileName) {
FileOutputStream fos;
OutputStream out = null;
try {
File dir = context.getExternalFilesDir(null);
out = new FileOutputStream(new File(dir, imageFileName + ".jpg"));
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Bitmap loadImageFromFile(String fileName) {
Bitmap bitmap = null;
try {
File dir = context.getExternalFilesDir(null);
InputStream inputStream = new FileInputStream(new File(dir, fileName + ".jpg"));
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap;
}

FileNotFoundException using Universal Image Loader

This is my first app on Android and I am using the Universal Image Loader Library to load images into a GridView.
The problem I am having is
FileNotFoundException: No entry for content://media/external/images/thumbnails/...(all thumbnails )
The thumbnails are not loaded in the GridView, but when I tap on a gridItem, the Intent is started and an imageId is passed to the next activity.
Here is the code I am using (based on the Sample example at UIL( github)
public class ImageGridFragment extends AbsListViewBaseFragment {
Cursor mCursor;
int[]imageIDs;
String bucket;
ArrayList<String> imageUrls;
int firstImageIndex;
int lastImageIndex;
int columnIndex;
String sender;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getActivity().getIntent();
sender = intent.getExtras().getString("sender");
bucket = intent.getExtras().getString("albumName");
imageIDs = getImagesFromBucket();
imageUrls = new ArrayList<>();
for(int i = 0; i < imageIDs.length; i++){
int imageID = imageIDs[i];
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
imageUrls.add(imageURI.toString());
}
BitmapFactory.Options resizeOptions = new BitmapFactory.Options();
resizeOptions.inSampleSize = 3; // decrease size 3 times
resizeOptions.inScaled = true;
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.decodingOptions(resizeOptions)
.postProcessor(new BitmapProcessor() {
#Override
public Bitmap process(Bitmap bmp) {
return Bitmap.createScaledBitmap(bmp, 120, 120, false);
}
})
.build();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_gallery_grid_view, container, false);
listView = (GridView) rootView.findViewById(R.id.gridView);
listView.setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent returnToSender;
if (sender.equals("First")) {
returnToSender = new Intent(ImageGridFragment.this.getActivity(), FirstImageActivity.class);
firstImageIndex = 0;
returnToSender.putExtra("firstImageIndex", firstImageIndex);
// Move cursor to current position
mCursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = mCursor.getInt(columnIndex);
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageID);
returnToSender.putExtra("imageURI", imageURI);
String comingFrom = "gridView";
returnToSender.putExtra("comingFrom", comingFrom);
mCursor.close();
returnToSender.putExtra("albumName", bucket);
} else {
returnToSender = new Intent(ImageGridFragment.this.getActivity(), LastImageActivity.class);
lastImageIndex = 0;
returnToSender.putExtra("lastImageIndex", lastImageIndex);
}
startActivity(returnToSender);
}
});
return rootView;
}
private int[] getImagesFromBucket()
{
int[] ids = null;
ArrayList<Integer> lstIds = new ArrayList<>();
String searchParams;
if(bucket != null)
{
searchParams = "bucket_display_name = \""+bucket+"\"";
}
else
{
return ids;
}
String[] projection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_TAKEN};
String orderBy = MediaStore.Images.Media.DATE_TAKEN + " DESC";
mCursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
searchParams,
null,orderBy);
if(mCursor.moveToFirst())
{
do
{
int id = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media._ID));
lstIds.add(id);
}
while(mCursor.moveToNext());
}
ids = new int[lstIds.size()];
for(int i=0;i<ids.length;i++)
{
ids[i] = lstIds.get(i);
}
return ids;
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater inflater;
ImageAdapter() {
inflater = LayoutInflater.from(getActivity());
}
#Override
public int getCount() {
return imageUrls.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.item_grid_image, parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (ImageView) view.findViewById(R.id.gridImageView);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
ImageLoader.getInstance()
.displayImage(imageUrls.get(position), holder.imageView, options, new SimpleImageLoadingListener() {
});
return view;
}
}
static class ViewHolder {
ImageView imageView;
}
}
Any help with understanding what I am doing wrong and how to fix it would be greatly appreciated.
SOLVED!
I changed this line
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
to
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageID);
If your path having filename with extension like .png, .jpg or any than it is file path, in such case you have to add string as
"file://"+ filename.
And if your path not having any extension and not web url, so it is content uri, here you have to add
"content://"+filename.
For more click here.

Highlighted items in multi-selection file-chooser are dynamically changed while scrolling listview

I have selected set of items from my sdcard folder using multi-selection file-chooser.It returns exactly selected values but the selection highlighted items (using colors) are dynamically changed while scrolling list-view..can anybody tell me how to fix it?
Here i have added my file-chooser class and adapter class..
public class FileChooser extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
private Bundle selectedfiles;
String selectedFileAbspath;
ArrayList<String> images_arr = new ArrayList<String>();
boolean is_multiple;
Button file_upload;
Integer val;
Pattern fileExtnPtrn;;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
is_multiple = this.getIntent().getExtras()
.getBoolean("is_multiple", false);
val = this.getIntent().getExtras()
.getInt("value");
if (is_multiple)
{
setContentView(R.layout.file_chooser_list);
file_upload = (Button) findViewById(R.id.file_upload);
file_upload.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(selectedfiles.size()!=0)
{
Intent i = new Intent();
i.putExtra("selected_files", selectedfiles);
setResult(RESULT_OK, i);
finish();
}
else
{
showDialog("Please Choose Atleast one File");
}
}
});
}
currentDir = new File("/sdcard/");
selectedfiles = new Bundle();
fill(currentDir);
}
private void fill(File f)
{
File[]dirs = f.listFiles();
this.setTitle("Current Dir: "+f.getName());
List<Item>dir = new ArrayList<Item>();
List<Item>fls = new ArrayList<Item>();
try
{
for(File ff: dirs)
{
Date lastModDate = new Date(ff.lastModified());
DateFormat formater = DateFormat.getDateTimeInstance();
String date_modify = formater.format(lastModDate);
if(ff.isDirectory())
{
File[] fbuf = ff.listFiles();
int buf = 0;
if(fbuf != null)
{
buf = fbuf.length;
}
else buf = 0;
String num_item = String.valueOf(buf);
if(buf == 0)
num_item = num_item + " item";
else
num_item = num_item + " items";
//String formated = lastModDate.toString();
dir.add(new Item(ff.getName(),num_item,date_modify,ff.getAbsolutePath(),"directory_icon"));
}
else
{
fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"file_icon"));
}
}
}
catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if(!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0,new Item("..","Parent Directory","",f.getParent(),"directory_up"));
adapter = new FileArrayAdapter(FileChooser.this,R.layout.file_view,dir);
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Item o = adapter.getItem(position);
if(o.getImage().equalsIgnoreCase("directory_icon")||o.getImage().equalsIgnoreCase("directory_up")){
currentDir = new File(o.getPath());
fill(currentDir);
}
else
{
onFileClick(o,v);
}
}
private void onFileClick(Item o,View v)
{
selectedFileAbspath = currentDir.toString() + "/" + o.getName();
RelativeLayout list_item=(RelativeLayout) v;
if(is_multiple)
{
if(validateFileExt(selectedFileAbspath))
{
if (selectedfiles.containsKey(selectedFileAbspath))
{
selectedfiles.remove(selectedFileAbspath);
list_item.setBackgroundColor(getResources().getColor(R.color.white));
}
else
{
selectedfiles.putString(selectedFileAbspath, "1");
list_item.setBackgroundColor(getResources().getColor(R.color.red));
}
}
else
{
showDialog("please select valid image file");
}
}
else
{
if(validateFileExt(selectedFileAbspath))
{
Intent intent = new Intent();
intent.putExtra("GetPath", currentDir.toString());
intent.putExtra("GetFileName", o.getName());
setResult(RESULT_OK, intent);
finish();
}
else
{
Intent intent = new Intent();
setResult(RESULT_CANCELED, intent);
finish();
}
}
}
private boolean validateFileExt(String fileName)
{
fileExtnPtrn = Pattern.compile("([^\\s]+(\\.(?i)(jpg|png))$)");
Matcher mtch = fileExtnPtrn.matcher(fileName);
return mtch.matches();
}
private void showDialog(String string)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(string);
alertDialog.setPositiveButton("Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alertDialog.show();
}
}
Adapter class
public class FileArrayAdapter extends ArrayAdapter{
private Context c;
private int id;
private List<Item>items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Item> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Item getItem(int i)
{
return items.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
/* create a new view of my layout and inflate it in the row */
//convertView = ( RelativeLayout ) inflater.inflate( resource, null );
final Item o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);
String uri = "drawable/" + o.getImage();
int imageResource = c.getResources().getIdentifier(uri, null, c.getPackageName());
Drawable image = c.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
if(t1!=null)
t1.setText(o.getName());
if(t2!=null)
t2.setText(o.getData());
if(t3!=null)
t3.setText(o.getDate());
}
return v;
}
}
your problem in getItem method in ListAdapter of List
try this adapter) you must determine all elements of each item in your case)
public class FileArrayAdapter extends ArrayAdapter{
private Context c;
private int id;
private List<Item>items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Item> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Item getItem(int i)
{
return items.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
/* create a new view of my layout and inflate it in the row */
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);
String uri = "drawable/" + o.getImage();
int imageResource = c.getResources().getIdentifier(uri, null, c.getPackageName());
Drawable image = c.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
if(t1!=null)
t1.setText(o.getName());
if(t2!=null)
t2.setText(o.getData());
if(t3!=null)
t3.setText(o.getDate());
return v;
}
}

android put icons to list (filebrowser)

hi m making a filebrowser in android and this is the code for it :
public class FileBrowser extends ListActivity {
private IAppManager imService;
private File currentDir;
private FileArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Editable usrr = Login.usernameText.getText();
currentDir = new File("/sdcard/");
fill(currentDir);
}
private void fill(File f)
{
File[]dirs = f.listFiles();
this.setTitle(f.getName()+ "'s Chats" );
List<Option>dir = new ArrayList<Option>();
List<Option>fls = new ArrayList<Option>();
try{
for(File ff: dirs)
{
if(ff.isDirectory())
dir.add(new Option(ff.getName(),"Folder",ff.getAbsolutePath()));
else
{
fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath()));
}
}
}catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if(!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0,new Option("..","Parent Directory",f.getParent()));
adapter = new FileArrayAdapter(FileBrowser.this,R.layout.filebrowser,dir);
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Option o = adapter.getItem(position);
if(o.getData().equalsIgnoreCase("folder")||o.getData().equalsIgnoreCase("parent directory")){
//v.setBackgroundResource(R.drawable.foler);
currentDir = new File(o.getPath());
fill(currentDir);
}
else
{
onFileClick(o);
}
}
now what i want is to display an icon for the files and the folders.(no other icons, just these 2) i have put an image view in the xml layout but i dont know how to dynamicaly check which list item is file so that it displays a file icon next to it and which one is a folder to display the folder icon.
please help!
You have to customize the FileArrayAdapter.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
final Option o = items.get(position);
if (o != null) {
TextView fileName = (TextView) v.findViewById(R.id.FileName);
ImageView fileIcon = (ImageView) v.findViewById(R.id.FileIcon);
if(fileName!=null) {
fileName.setText(o.getName());
if(fileIcon!=null) {
if(o.getData().equalsIgnoreCase("folder")||o.getData().equalsIgnoreCase("parent directory")){
fileIcon.setImageRessource(<FolderIcon>)
} else {
fileIcon.setImageResouce(<FileIcon>)
}
}
}
return v;
}

How to set thumbnail picture for each row in list view with sd card as resource?

I would like to set a thumbnail picture for each corresponding row from the sd card.As of now I am getting the list view from the sd card.Here is the completed code of mine
public class SaveList extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private String root="/sdcard/Photos/";
private TextView myPath;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.savelist);
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if(file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.savelistrow, item);
setListAdapter(fileList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
else
{
final String path1= ("/sdcard/Photos/"+file.getName());
Intent intent = new Intent( getBaseContext(),FullView.class);
intent.putExtra("link",path1);
startActivity( intent);
}
}
}
Please tell me how to add right corresponding thumbnail from sd card as resource.I have tried it from static images but I am unable to do it for dynamic resource.Thanks a lot.
According to my understanding of your question, you want to load an image from sdCard, right? If this is the case you can do it like this:
ImageView image = (ImageView) findViewById(R.id.imageID);
if(image != null)
{
Bitmap myBitmap = BitmapFactory.decodeFile("/sdcard/MyImage.jpg");
if(myBitmap != null)
image.setImageBitmap(myBitmap);
}
Secondly, you can set the thumbnail of each row in ListView by making a custom Adapter by overriding the getView() e.g.
private class MyCustomAdapter extends ArrayAdapter<String>
{
public MyCustomAdapter(Context context, int resource, int textViewResourceId, List<String> item)
{
super(context, resource, textViewResourceId, item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.my_listview_row, null);
}
ImageView image = (ImageView) v.findViewById(R.id.imageID);
if(image != null)
{
Bitmap myBitmap = BitmapFactory.decodeFile("/sdcard/MyImage.jpg");
if(myBitmap != null)
image.setImageBitmap(myBitmap);
}
return v;
}
}

Categories

Resources