Prevent Dupliate image Strings from ListView in Android - android

In my code i want to take a image from camera and store its string in encodedimagestring variable. But my code stores same image string two times. what logical check should i set here to prevent duplicate string. Please help me.
public View getView(final int position, View convertView, ViewGroup parent) {
final Bitmap image=(Bitmap)(images.get(position));
final ViewHolder holder;
if (convertView == null) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
byte[] b = bytes.toByteArray();
encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
StringImages.add(encodedImageString);
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.imageview2, null);
holder.image = (ImageView) convertView.findViewById(R.id.imageView2);
holder.Delete=(Button)convertView.findViewById(R.id.buttonClose);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
int imageWidth = factoryOptions.inDensity=70;
int imageHeight = factoryOptions.inDensity=65;
Bitmap Scaled =Bitmap.createScaledBitmap(images.get(position), imageWidth,
imageHeight, true);
holder.image.setImageBitmap(Scaled);
holder.image.setTag(position);
holder.Delete.setTag(position);
holder.image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
final Dialog imgDialog = new Dialog(view.getContext(),
android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
imgDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
imgDialog.setCancelable(false);
// layout imageview2 is used because when i use simple imageview layout
// dialogue with imageview and closebutton,
// every taken image at instance will not be shown in dialogue.
imgDialog.setContentView(R.layout.imageview);
Button btnClose = (Button)imgDialog.findViewById(R.id.btnIvClose);
ImageView ivPreview = (ImageView)imgDialog.findViewById(R.id.image1);
ivPreview.setImageBitmap(images.get(position));
btnClose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
imgDialog.dismiss();
}
});
imgDialog.show();
myAdapter.notifyDataSetChanged();
listviewattachment.setSelection(myAdapter.getCount()+1 );
}
});
holder.Delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
int tag = (Integer) view.getTag();
if ((position) != (images.size() )) {
images.remove(images.get(tag));
images.remove(image);
StringImages.remove(position);
myAdapter.notifyDataSetChanged();
}
}
});
return convertView ;
}
}

if (!StringImages.contains(encodedImageString)) {
StringImages.add(encodedImageString);
}
Should do the trick.

Related

Android click listView to expand ImageView

I have a listview with a textview and imageview in each row, and am trying to figure out how to enlarge my images when clicking on them. The user takes an image from their gallery and stores them in a database with a name. They are maps of resorts/hotels for the purpose of delivering.
This is how everything is laid out:
I'm trying to get my app to where I can click on an ImageView, or simply just the listview itself, and have the image enlarged in the center of the screen. If not enlarged in the center of the screen, I wouldn't even mind opening the enlarged image in a new activity. Either way is fine, I would just like to be able to read the maps, so doing something with pinch-to-zoom would be great! I get the images from the user's gallery and store them in a list, and ask them for a name for the hotel/resort. Then I save the information to a database and display it in a listview. I crop the images down to fit them in the listview as thumbnails, but I would like to expand them back out upon being clicked for easy readability. Any help would be greatly appreciated! My goal is to have it look like the answer to this question, but couldn't figure out how to optimize it into my code.
My adapter class is as follows:
public class dataAdapter extends ArrayAdapter<Hotel> {
Context context;
ArrayList<Hotel> mHotel;
public dataAdapter(Context context, ArrayList<Hotel> hotel)
{
super(context, R.layout.listhotels, hotel);
this.context = context;
this.mHotel = hotel;
}
public class Holder
{
TextView nameFV;
ImageView pic;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Hotel data = getItem(position);
Holder viewHolder;
if (convertView == null)
{
viewHolder = new Holder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listhotels, parent, false);
viewHolder.nameFV = (TextView) convertView.findViewById(R.id.txtViewer);
viewHolder.pic = (ImageView) convertView.findViewById(R.id.imgView);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (Holder) convertView.getTag();
}
viewHolder.nameFV.setText(data.getFName());
viewHolder.pic.setImageBitmap(convertToBitmap(data.getImage()));
return convertView;
}
private Bitmap convertToBitmap(byte[] b)
{
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
}
My code to display the list of hotels:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.display_hotels);
lv = (ListView) findViewById(R.id.list1);
db = new DatabaseHandler(this);
pic = (ImageView) findViewById(R.id.pic);
fname = (EditText) findViewById(R.id.txt1);
final ArrayList<Hotel> hotels = new ArrayList<>(db.getAllHotels());
data = new dataAdapter(this, hotels);
data.sort(new Comparator<Hotel>()
{
#Override
public int compare(Hotel arg0, Hotel arg1)
{
return arg0.getFName().compareTo(arg1.getFName());
}
});
data.notifyDataSetChanged();
lv.setAdapter(data);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Intent i = new Intent(getApplicationContext(), display_full_image.class);
startActivity(i);
}
});
}
And my main activity:
public class MapsMainActivity extends AppCompatActivity {
private EditText fname;
private ImageView pic;
private DatabaseHandler db;
private String f_name;
private ListView lv;
private dataAdapter data;
private Hotel dataModel;
private Bitmap bp;
private byte[] photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_main);
db = new DatabaseHandler(this);
lv = (ListView) findViewById(R.id.list1);
pic = (ImageView) findViewById(R.id.pic);
fname = (EditText) findViewById(R.id.txt1);
}
public void buttonClicked(View v)
{
int id = v.getId();
switch(id)
{
case R.id.save:
if (fname.getText().toString().trim().equals(""))
{
Toast.makeText(getApplicationContext(), "Name edit text is empty, Enter name", Toast.LENGTH_LONG).show();
}
else
{
addHotel();
}
break;
case R.id.display:
showRecords();
Intent intent = new Intent(getApplicationContext(), display_hotels.class);
startActivity(intent);
break;
case R.id.pic:
selectImage();
break;
}
}
public void selectImage()
{
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode)
{
case 2:
if(resultCode == RESULT_OK)
{
Uri chosenImage = data.getData();
if(chosenImage != null)
{
bp = decodeUri(chosenImage, 400);
pic.setImageBitmap(bp);
}
}
}
}
protected Bitmap decodeUri(Uri selectedImage, int REQUIRED_SIZE)
{
try
{
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
{
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private byte[] profileImage(Bitmap b)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 0, bos);
return bos.toByteArray();
}
private void getValues()
{
f_name = fname.getText().toString();
photo = profileImage(bp);
}
private void addHotel()
{
getValues();
db.addHotels(new Hotel(f_name, photo));
Toast.makeText(getApplicationContext(), "Saved successfully", Toast.LENGTH_SHORT).show();
}
private void showRecords()
{
final ArrayList<Hotel> hotels = new ArrayList<>(db.getAllHotels());
data = new dataAdapter(this, hotels);
data.notifyDataSetChanged();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
dataModel = hotels.get(position);
Toast.makeText(getApplicationContext(), String.valueOf(dataModel.getID()), Toast.LENGTH_SHORT).show();
}
});
}
}
Thank you in advance to anyone who can help me. I would greatly appreciate it. This is for a final project for my Mobile App Development class that is due in 2 days, and I'm really close to finishing it. Thank you for your time.
use this getView()
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Hotel data = getItem(position);
Holder viewHolder;
if (convertView == null)
{
viewHolder = new Holder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listhotels, parent, false);
viewHolder.nameFV = (TextView) convertView.findViewById(R.id.txtViewer);
viewHolder.pic = (ImageView) convertView.findViewById(R.id.imgView);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (Holder) convertView.getTag();
}
viewHolder.nameFV.setText(data.getFName());
viewHolder.pic.setImageBitmap(convertToBitmap(data.getImage()));
viewHolder.pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog settingsDialog = new Dialog(context);
settingsDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(500, 500);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
ImageView iv = new ImageView(context);
iv.setLayoutParams(lp);
iv.setImageResource(R.drawable.img3);
//use in your case iv.setImageBitmap(convertToBitmap(data.getImage()));
settingsDialog.addContentView(iv,lp);
settingsDialog.show();
}
});
return convertView;
}
just pass the imgeData as extra in intent when you start new Activity to display full image. and in FullImageActivit getIntent extra to get the image data and display it in an imageView.
and if you want to enable pinch zoom there a librabry to handle it
check this

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

Deleted image appears again in ListView

In my application i add images to listview and transfer those images to servelet after conversion into string. But deleted image from listview also transfer. It removes from listview, but string is transfering to servelet. This is annoying . I am not getting where to add these lines in BaseAdapter.
Bitmap image=(Bitmap)getItem(position);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//encode image
byte[] b = bytes.toByteArray();
encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
//encodedImageString is sent to servlet, it's showing deleted image string also
Here is a complete code of BaseAdapter
public class MyAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> imageHashMap=new ArrayList<HashMap<String,String>>();
private LayoutInflater mInflater;
public MyAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// return myItems.size();
return images.size();
}
public Bitmap getItem(int position) {
return images.get(position);
//return myItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
final Bitmap image=(Bitmap)getItem(position);
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.imageview2, null);
holder.image = (ImageView) convertView
.findViewById(R.id.imageView2);
holder.Delete=(Button)convertView.findViewById(R.id.buttonClose);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
int imageWidth = factoryOptions.inDensity=70;
int imageHeight = factoryOptions.inDensity=65;
Bitmap Scaled = Bitmap.createScaledBitmap(images.get(position), imageWidth, imageHeight, true);
holder.image.setImageBitmap(Scaled);
holder.image.setTag(position);
String me= holder.image.getTag().toString();
holder.Delete.setTag(position);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//encode image
final ArrayList<HashMap<String, String>> imageHashMap=new ArrayList<HashMap<String,String>>();
byte[] b = bytes.toByteArray();
encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
// StringImages.add(encodedImageString);
imageHashMap.putString(String.valueOf(image.getTag()), encodedImageString);
holder.image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
final Dialog imgDialog = new Dialog(view.getContext(),android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
imgDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
imgDialog.setCancelable(false);
// layout imageview2 is used because when i use simple imageview layout dialogue with imageview and closebutton,
// every taken image at instance will not be shown in dialogue.
imgDialog.setContentView(R.layout.imageview);
Button btnClose = (Button)imgDialog.findViewById(R.id.btnIvClose);
ImageView ivPreview = (ImageView)imgDialog.findViewById(R.id.image1);
ivPreview.setImageBitmap(images.get(position));
btnClose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
imgDialog.dismiss();
}
});
imgDialog.show();
myAdapter.notifyDataSetChanged();
listviewattachment.setSelection(myAdapter.getCount()+1 );
}
});
holder.Delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
int tag = (Integer) view.getTag();
if (tag != (images.size() )) {
images.remove(tag);
Log.d("GCM", "Item removed from " + tag);
myAdapter.notifyDataSetChanged();
}
if(imageHashMap.contains(tag)) {
imageHashMap.remove(tag); }
}
});
return convertView;
}
}
For an example, using hashmap look at this:
Bitmap Scaled = Bitmap.createScaledBitmap(images.get(position), imageWidth,imageHeight,true);
holder.image.setImageBitmap(Scaled);
holder.image.setTag(position);
holder.Delete.setTag(position);
Bitmap image=(Bitmap)getItem(position);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//encode image
byte[] b = bytes.toByteArray();
encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
StringImages.add(encodedImageString) -----> Instead of this line, use a hashmap like this
imageHashMap.put(String.valueOf(image.getTag()), encodedImageString);
and in the delete.onclicklistener code as you are removing image from images, like images.remove(image),
add these lines
if(imageHashMap.contains(image.getTag())) {
imageHashMap.remove(image.getTag());
}
I hope this helps.
PS: declare the hashmap in the constructor before you use it, else you might get a null pointer exception

Android ListView the gallery shows in wrong places

When I use listview with adapter which add a gallery in the view and the gallery adapter loads the image loads the image with asynctask the gallery shows in different places.
public View getView(int position, View convertView, ViewGroup parent) {
final int myPosition = position;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
boolean isConverted = false;
switch(typeOfCell.get(position))
{
case 0:
if(convertView == null)
{
rowView = inflater.inflate(R.layout.newstextcelladapter, parent, false);
}
else
{
rowView = convertView;
}
break;
case 1:
if(convertView == null)
{
rowView = inflater.inflate(R.layout.newsimagecelladapter, parent, false);
}
else
{
rowView = convertView;
isConverted = true;
}
Gallery gallery = (Gallery) rowView.findViewById(R.id.newsImageGallery);
try{
gallery.setAdapter(this.adaptersForGallery.get(position));
Log.w("Adapter used", "" + this.adaptersForGallery.get(position));
Log.w("URL used", "" + this.adaptersForGallery.get(position).mImageIds.get(0));
gallery.setHorizontalFadingEdgeEnabled(false);
gallery.setVisibility(View.GONE);
gallery.setVisibility(View.VISIBLE);
}
catch(Exception e)
{
#SuppressWarnings("unused")
int a =1;
Log.w("FATAL","ERROR");
}
rowView.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
View view2 = new View(MainActivity.context);
DetailsImageNews.setView(MainActivity.dataBase.getCommentsForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.dataBase.getAuthorForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.dataBase.getDateForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.dataBase.getTimeForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.dataBase.getDetailedTextForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.dataBase.getTitleForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.detailImageNews,
adaptersForGallery.get(myPosition)
,view2);
while (MainActivity.currentViewPosition != 1) {
MainActivity.mContainer.showNext();
Log.w("position", "" + MainActivity.currentViewPosition);
if (MainActivity.currentViewPosition > 2) {
MainActivity.currentViewPosition = 0;
}
MainActivity.currentViewPosition += 1;
}
}
});
break;
case 2:
if(convertView == null)
{
rowView = inflater.inflate(R.layout.newsvideocelladapter, parent, false);
}
else
{
rowView = convertView;
}
Uri uri=Uri.parse(videoUrls.get(position));
VideoView video = (VideoView) rowView.findViewById(R.id.newsVideo);
video.setVideoURI(uri);
break;
default:
if(convertView == null)
{
rowView = inflater.inflate(R.layout.newstextcelladapter, parent, false);
}
else
{
rowView = convertView;
}
break;
}
TextView titleView = (TextView) rowView.findViewById(R.id.newsTitleView);
TextView dateView = (TextView) rowView.findViewById(R.id.newsDateView);
TextView timeView = (TextView) rowView.findViewById(R.id.newsTimeView);
TextView commentsView = (TextView) rowView.findViewById(R.id.newsCommentView);
titleView.setText(this.title.get(position));
dateView.setText(this.date.get(position));
timeView.setText(this.time.get(position));
commentsView.setText(Integer.toString(this.comments.get(position)));
return rowView;
}
public View getView(int position, View convertView, ViewGroup parent) {
View i ;
ImageView iv;
ProgressBar mProgressBar;
calledGetView+=1;
Log.i("Image View:URL", ""+mImageIds.get(position));
if(convertView == null)
{
i = MainActivity.factory.inflate(R.layout.imagespinner, null);
}
else
{
i = (ImageView) convertView;
}
mProgressBar =(ProgressBar) i.findViewById(R.id.imageProgress);
iv = (ImageView) i.findViewById(R.id.image);
try {
AsycTask task = new AsycTask();
task.url = new URL(mImageIds.get(position));
task.iv = iv;
task.execute(iv);
iv.setAdjustViewBounds(true);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setLayoutParams(new RelativeLayout.LayoutParams((int) (MainActivity.screenWidth*0.7), (int) ((MainActivity.screenWidth*0.7)*0.6)));
task.globalPosition = currentPosition;
task.mProgressBar = mProgressBar;
if(task.bm == null)
{
}
}
catch (IOException e) {
Log.i("Asyc task", "FATAL ERROR");
e.printStackTrace();
}
return i;
}
public class AsycTask extends AsyncTask<ImageView, Void, Bitmap> {
public Bitmap bm;
public Bitmap bm2;
public int globalPosition;
public ProgressBar mProgressBar;
public int imagePosition;
public ImageView iv;
public URL url;
public Canvas c;
#Override
protected Bitmap doInBackground(ImageView... arg0) {
iv = arg0[0];
//Log.w("Loading url:",""+ url.getPath());
try {
bm2 = BitmapFactory.decodeStream((InputStream) url.getContent());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OutOfMemoryError e) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 2;
o.inDither = false;
o.inPurgeable = true;
try {
bm2 = BitmapFactory.decodeStream(
(InputStream) url.getContent(), null, o);
} catch (IOException e1) {
e1.printStackTrace();
} catch (OutOfMemoryError e1) {
}
}
return bm2;
}
private void updateView(int index){
View v = MainActivity.newsListView.getChildAt(index -
MainActivity.newsListView.getFirstVisiblePosition());
}
#Override
protected void onPostExecute(Bitmap result) {
mProgressBar.setVisibility(View.GONE);
iv.setVisibility(View.GONE);
iv.setVisibility(View.VISIBLE);
BitmapDrawable dr = ((BitmapDrawable) iv.getDrawable());
if (dr != null) {
Bitmap bmForRecyl = dr.getBitmap();
if (bmForRecyl != null) {
bmForRecyl.recycle();
}
}
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setImageBitmap(result);
Log.i("Set", "setted");
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
mProgressBar.incrementProgressBy(5);
}
}
I know for this problem but I dont know how to resolve it for listview with gallery with asyctask.
I think this is because the gallery is not loaded with the new adapter.How to change the adapter?
You need to override getViewItemType.
getViewTypeCount() - this methods returns information how many types of rows do you have in your list
getItemViewType(int position) - returns information which layout type you should use based on position
Then you inflate layout only if it's null and determine type using getItemViewType.
Example :
private static final int TYPE_ITEM1 = 0;
private static final int TYPE_ITEM2 = 1;
private static final int TYPE_ITEM3 = 2;
#Override
public int getItemViewType(int position)
{
int type;
if (position== 0){ // your condition
type = TYPE_ITEM1; //type 0 for image
} else if(position == 1){
type = TYPE_ITEM2; //type 1 for text
}else {
type = TYPE_ITEM3; //type 2 for videos
}
return type;
}
#Override
public int getViewTypeCount() {
return 3; //three different layouts to be inflated
}
In getView
int type= getItemViewType(arg0);
switch (type) {
case TYPE_ITEM1:
// inflate layout for text
break;
case TYPE_ITEM2:
// inflate layout for image
break;
case TYPE_ITEM3:
// inflate layout for video
break;
....
You can check the tutorial below
http://android.amberfog.com/?p=296

Image from sd card to gallery

I want to get an image from sd card and place it in gallery view.For that i had converted that image to bitmap but it shows certain errors..
code for conversion of the image.. I am attaching the complete code it showing a null pointer exception
private Gallery gallery;
private ImageView imgView;
int position;
private byte[] data = { };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
System.out.println("Enter the activity");
try{
String filepath = "/sdcard/";
File imagefile = new File(filepath + "abcdoutput.jpg");
FileInputStream fis = new FileInputStream(imagefile);
Bitmap bi = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
System.out.println("cnvrtn");
}
catch(Exception e) {
e.printStackTrace();
}
Bitmap bitmapimage = BitmapFactory.decodeByteArray(data, 0, data.length);
position = 0;
imgView = (ImageView) findViewById(R.id.ImageView01);
imgView.setImageBitmap(bitmapimage);
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
imgView.setImageResource(data[position]);
DisplayImage.this.position = position;
}
});
System.out.println("Enter the activity//////////");
imgView.setOnLongClickListener(new View.OnLongClickListener() {
#SuppressWarnings("deprecation")
public boolean onLongClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(
DisplayImage.this).create();
alertDialog.setTitle("Confirmation");
alertDialog
.setMessage("Do you want to set this image as wallaper?");
alertDialog.setButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Bitmap bitmap = BitmapFactory.decodeResource(
getResources(), data[position]);
try {
DisplayImage.this.setWallpaper(bitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Gallery Example", "Image setted.");
}
});
alertDialog.show();
return true;
}
});
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = null;
GalItemBg = typArray.getResourceId(
0, 0);
typArray.recycle();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView = new ImageView(cont);
imgView.setImageResource(data[position]);
imgView.setLayoutParams(new Gallery.LayoutParams(100, 100));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
Use this to get the image back from the array and set it:
Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
imgView.setImageBitmap(bitmap);
try and simple with one line code
String imagePath=Environment.getExternalStorageDirectory().toString()+"/abcdoutput.jpg";
imgView.setImageDrawable(Drawable.createFromPath("imagePath"));

Categories

Resources