Deleted image appears again in ListView - android

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

Related

How to set captured image in ListView?

I have an ArrayList which is bound to the listview, the custom row has a textview and an imageview, now when I click on any row I have given two functionality
1. Toast message to display position: which is displaying properly.
2. Open camera to capture an image and set that particular image to the row which was clicked.
Now the problem which I am facing is :
The image gets set but always to the last row and not to the row where it was clicked and when I click on the last row to capture image while setting the image it says IndexOutofBoundException
The code I have tried :
public class DocumentsKYCAdapter extends BaseAdapter{
private Context mContext;
private ArrayList<DocumentItem> gridName;
ArrayList<Integer> selectedDocumentId = new ArrayList<Integer>();
ArrayList<String> selectedDocumentNames = new ArrayList<String>();
ArrayList<Bitmap> selectedImages = new ArrayList<Bitmap>();
private Bitmap[] gridImage;
Documents_KYC activity;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Imageview";
private Uri fileUri;
ImageView imageView;
public static byte[] b;
public static String encodedImageStr1;
int imageCapturedPosition;
public DocumentsKYCAdapter(Documents_KYC activity,
ArrayList<DocumentItem> gridName,ArrayList<Integer>
selectedDocumentId,ArrayList<String> selectedDocumentNames) {
this.activity = activity;
this.gridImage = gridImage;
this.gridName = gridName;
this.selectedDocumentNames = selectedDocumentNames;
this.selectedDocumentId = selectedDocumentId;
}
#Override
public int getCount() {
return selectedDocumentNames.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup
parent) {
View grid;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.documents_kyc_row, null);
} else {
grid = (View) convertView;
}
final String documentItemName =
selectedDocumentNames.get(position);
final int documentItemId = selectedDocumentId.get(position);
TextView textView = (TextView) grid.findViewById(R.id.gridName);
imageView = (ImageView) grid.findViewById(R.id.gridImage);
imageView.setTag(position);
textView.setText(documentItemName);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageCapturedPosition = position;
Toast.makeText(activity,"Id"+documentItemId+"
,Position"+imageCapturedPosition,Toast.LENGTH_LONG).
show();
imageView.getTag(position);
captureImage();
}
});
return grid;
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
activity.startActivityForResult(intent, MEDIA_TYPE_IMAGE);
}
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
try {
if (requestCode == MEDIA_TYPE_IMAGE && resultCode ==
activity.RESULT_OK) {
BitmapFactory.Options options = new
BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap bitmap = Utility.decodeFile(fileUri.getPath(),
options);
FileOutputStream out = null;
try {
out = new FileOutputStream(fileUri.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
ByteArrayOutputStream baos = new
ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80,
baos);
b = baos.toByteArray();
encodedImageStr1 = Base64.encodeToString(b,
Base64.DEFAULT);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
selectedImages.add(bitmap);
imageView.setImageBitmap(selectedImages.
get(imageCapturedPosition));
} else if (resultCode == activity.RESULT_CANCELED) {
Toast.makeText(activity,
"User cancelled image capture",
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(activity,
"Sorry! Failed to capture image",
Toast.LENGTH_SHORT)
.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Custom Class :
public class BitmapModel {
Bitmap imageId;
ArrayList<String> documentNamesList;
public ArrayList<String> getDocumentNamesList() {
return documentNamesList;
}
public void setDocumentNamesList(ArrayList<String> documentNamesList) {
this.documentNamesList = documentNamesList;
}
public Bitmap getImageId() {
return imageId;
}
public void setImageId(Bitmap imageId) {
this.imageId = imageId;
}
}
Your issue is in the line -
selectedImages.add(bitmap);
Here whenever you add an image to your arrayList it always adds at the last position and then when you do imageView.setImageBitmap(selectedImages.get(imageCapturedPosition)); It tries to get the value for the position you selected which is not necessarily the last position.
The better way for you to do is create a Custom Class with Bitmap and selectedDocumentNames as part of the class then each object of the class would represent a name and an image associated with it.
Now when you capture the image, assign the image to the class Bitmap and then populate your listview with that Bitmap.
The workaround for your present code code be to either add the image into a particular position in array denoted by imageCapturedPosition or create a hashmap of type position,bitmap and then store it with the selected position. though i would not recommend any of these workarounds as they would cause other problems in future like memory leaks and positional movements in arrays etc and you would have to take care of these things

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

Prevent Dupliate image Strings from ListView in 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.

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"));

customized listview comes from database i want click listview means it prints particular itemname

I have fetched images and text as listview from database.now on clicking the particular text or image i should print same text.
Eg: if i click the listview of food menu then it should print food menu.if i click list view of catalogue it should print the catalogue .
enter code here
JSONArray json = jArray.getJSONArray("mainmenu");
list=(ListView)findViewById(R.id.mainmenulist);
adapter=new MainMenulist(this, json);
list.setAdapter(adapter);
Main menu listview
public class MainMenulist extends BaseAdapter {
protected static Context Context = null;
int i;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname;
public String[] itemnames;
HashMap<String, String> map = new HashMap<String, String>();
public MainMenulist(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
try {
for (i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("menuimage");
itemname = image.getString("menuname");
itemnames[i] = itemname;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(itemnames[i]);
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
vi = inflater.inflate(R.layout.mainmenulistview, null);
TextView text = (TextView) vi.findViewById(R.id.menutext);
ImageView image = (ImageView) vi.findViewById(R.id.menuimage);
image.setImageBitmap(bmps[position]);
text.setText(itemnames[position]);
text.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (itemnames[position].equals("Food Menu")) {
Intent intent = new Intent(Context, FoodMenu.class);
System.out.println("prakash");
Context.startActivity(intent);
}
}
});
return vi;
}
}
i can fetch all items in menulistview.java please tell me how to get particular list view click means particular item prints
Check below code
text.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (itemnames[position].equals("Food Menu")) {
Intent intent = new Intent(Context, FoodMenu.class);
System.out.println("prakash");
System.out.println(v.getText().toString());
Context.startActivity(intent);
}
}
});
Think you want to print name as you suggested at the place of your
System.out.println statement
Use the below link which shows a sample app and also how to use custom adapter.including the click events
http://www.codeproject.com/Articles/183608/Android-Lists-ListActivity-and-ListView-II-Custom
try below::
text.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Context, FoodMenu.class);
System.out.println(itemnames[position]);
System.out.println(text.getText().toString());
Context.startActivity(intent);
}
}
});

Categories

Resources