Assign the Intended bitmap value to an imageView - android

I'm using an adapter to load the items to a grid. then when the user select an item from the grid then it opens up the customizing screen. In that process I'm sending some data in the intent and later I can load the these in the customizing screen. Successfully I have loaded the other items other than the isVeg item. Response I'mgetting for isVeg , [false, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true] .
My problem is the way I have intented is correct or not. If it is correct how can I assign it to a ImageView.
adapter im using to send the data to next acitivty
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.pasta_single_item, parent, false);
holder.ivImage = (ImageView) convertView
.findViewById(R.id.grid_image);
holder.tvImageIcon = (ImageView) convertView
.findViewById(R.id.icon);
holder.tvHeader = (TextView) convertView
.findViewById(R.id.grid_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvHeader.setText(descriptions.get(position));
Picasso.with(this.context).load(imageUrls.get(position))
.into(holder.ivImage);
final String strIsVag=isVeg.get(position);
final Bitmap mBitmap;
if (strIsVag.contains("true")) {
mBitmap = BitmapFactory.decodeResource(
this.context.getResources(), R.drawable.veg);
} else {
mBitmap = BitmapFactory.decodeResource(
this.context.getResources(), R.drawable.nonveg);
}
holder.tvImageIcon.setImageBitmap(mBitmap);
Button customizePasta = (Button) convertView
.findViewById(R.id.bt_direct_customize);
customizePasta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent next = new Intent(context, ActivityPastaCustomize.class);
next.putExtra("description", descriptions.get(position));
next.putExtra("imageUrl", imageUrls.get(position));
next.putExtra("price", price.get(position));
next.putExtra("isVeg", mBitmap); //intent the image for selected item
context.startActivity(next);
((Activity) context).overridePendingTransition(
R.anim.slide_in_right, R.anim.slide_out_left);
}
});
return convertView;
}
private class ViewHolder {
private TextView tvHeader;
private ImageView ivImage;
private ImageView tvImageIcon;
}
}
receiving the data in activity
final String description = getIntent().getStringExtra("description");
String imageUrl = getIntent().getStringExtra("imageUrl");
final String Strprice = getIntent().getStringExtra("price");
String mBitmap = getIntent().getStringExtra("isVeg"); // recives the item
setting the recivied data
final TextView descriptionTV = (TextView) findViewById(R.id.grid_text);
descriptionTV.setText(description);
final TextView priceTV = (TextView) findViewById(R.id.pasta_price);
priceTV.setText("PRICE RS " + Strprice);
ImageView imageView = (ImageView) findViewById(R.id.grid_image);
Picasso.with(this).load(imageUrl).into(imageView);

Instead of sending Bitmap with intent send drawable id.make following changes in getView method:
1. Get selected String from isVeg List:
#Override
public void onClick(View view) {
...
next.putExtra("isVeg", isVeg.get(position));
context.startActivity(next);
....
}
2. Receive data in activity isVeg as String:
String strIsVag = getIntent().getStringExtra("isVeg");
3. Set Image to ImageView according to strIsVag :
Bitmap mBitmap;
if (strIsVag.contains("true")) {
mBitmap = BitmapFactory.decodeResource(
this.getResources(), R.drawable.veg);
} else {
mBitmap = BitmapFactory.decodeResource(
this.getResources(), R.drawable.nonveg);
}
ImageView imageView = (ImageView) findViewById(R.id.grid_image);
imageView.setImageBitmap(mBitmap);

I would suggest to convert Bitmap object to string and send to your desired activity like this:-
next.putExtra("isVeg", BitMapToString(mBitmap));
These this function write below ViewHolder class like this
private class ViewHolder {
private TextView tvHeader;
private ImageView ivImage;
private ImageView tvImageIcon;
}
public String BitMapToString(Bitmap bitmap){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
String temp=Base64.encodeToString(b, Base64.DEFAULT);
return temp;
}
then in the receiving activity convert the string back to bitmap to use it to the imageview like this:-
String mBitmapString = getIntent().getStringExtra("isVeg");
Bitmap mBitmap=StringToBitMap(mBitmapString);
Assign where you want
image.setImageBitmap(mBitmap);
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}

After you download a image from url below is your code-
Picasso.with(this.context).load(imageUrls.get(position))
.into(holder.ivImage);
final String strIsVag=isVeg.get(position);
final Bitmap mBitmap;
if (strIsVag.contains("true")) {
mBitmap = BitmapFactory.decodeResource(
this.context.getResources(), R.drawable.veg);
} else {
mBitmap = BitmapFactory.decodeResource(
this.context.getResources(), R.drawable.nonveg);
}
after that store that bitmap in local storage.
and pass path of that storage dir by intent and display it in other activity a you want.
below is code for store image in local storage-
FileOutputStream out = new FileOutputStream(file);
mBitmap .compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
hope it will help you.
EDITED
create a file like -
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/app_name");
myDir.mkdirs();
String fname = "image.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();

Related

share listview item (url image and text ) on facebook

I am fetching data from server and set it into listview. Each Listview item have photo ( url image ) and a text + share button . I have implemented all the code and working perfect.. But can any one help me.. How to implement facebook share intent when click on button of particular listview item.I want to share image and text
i ask from a way to the this
and thank you in advance
this is my code "MediaAdapter.java" :
public class MediaAdapter extends ArrayAdapter<Media> {
ArrayList<Media> mediaList;
Context context;
int Resource;
LayoutInflater vi;
ViewHolder holder;
ImageLoader imageLoader;
public MediaAdapter(Context context, int resource, ArrayList<Media> objects) {
super(context, resource, objects);
imageLoader = new ImageLoader(context);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
mediaList = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
v = vi.inflate(Resource, null);
holder = new ViewHolder();
int loader = R.drawable.ic_launcher;
//l url d image
holder.imageview = (ImageView) v.findViewById(R.id.urlImage);
// load image
imageLoader.DisplayImage(mediaList.get(position).getUrl(), loader, holder.imageview );
holder.titre = (TextView) v.findViewById(R.id.titre);
holder.titre.setText(mediaList.get(position).getTitre());
v.setTag(holder);
holder.button = (Button) v.findViewById(R.id.btnOne);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), "test",Toast.LENGTH_SHORT).show();
}
});
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView titre;
public Button button;
}
}
Change this in the code ....
First remove this line from the constructor
imageLoader = new ImageLoader(context);
Change it to
ImageLoader imageLoader = ImageLoader.getInstance();
Secondly remove this line from the code :
imageLoader.DisplayImage(mediaList.get(position).getUrl(), loader, holder.imageview );
Change it to
imageLoader.loadImage(mediaList.get(position).getUrl(), new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,mediaList.get(position).getTitre());
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, getImageUri(context,loadedImage));
try {
context.startActivity(shareIntent);
} catch (Exception ex) {
Toast.makeText(context, ex.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
});
Use this method to transform bitmap to uri:
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(),inImage, "Title", null);
return Uri.parse(path);
}
This will open the the share option for sharing to all the other apps including facebook. If facebook is selected by the user,then the image will be opened in the facebook app (if installed).Let me know if it working for you or not.
this is my new coode
it work like a charm
but i have a problem : but i have a problem when i click on share button of the item Number 2 ===== the content of the item number 3 is shared and note the Number 2 and vice-versa ????????????????
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri pictureUri = getLocalBitmapUri(holder.imageview);
if (pictureUri != null) {
// Construct a ShareIntent with link to image
String text = "image : "+mediaList.get(position).getTitre();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.putExtra(Intent.EXTRA_STREAM, pictureUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(shareIntent);
} else {
// ...sharing failed, handle error
}
///////////////////////////////////////////////////////////
private Uri getLocalBitmapUri(ImageView imageview) {
// TODO Auto-generated method stub
// Extract Bitmap from ImageView drawable
Drawable drawable =holder.imageview.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) holder.imageview.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}

How to share external image in custom listview?

I have created a custom listview that is handled by a custom adapter. Each item in this list displays an image and a share button. The images are loaded from external sources with ion. This works fine.
Now I want to share the image when the user clicks on the button. While I'm able to share text, etc. I'm not able to share these external images, even after implementing this code: Sharing Remote Images
Two things:
I'm new to android so I might be using the setTag/getTag completely wrong
if (drawable instanceof BitmapDrawable) is false, but I don't know why or how to fix this
Any help or suggestion is greatly appreciated!
This is the code from my adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
//brand new
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.contentImageView = (ImageView) convertView.findViewById(R.id.contentImageView);
holder.contentLabel = (TextView) convertView.findViewById(R.id.contentLabel);
holder.contentShareButton = (Button) convertView.findViewById(R.id.contentShareButton);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Content content = mContents[position];
Ion.with(mContext)
.load(content.getSrc()) //the external image url
.intoImageView(holder.contentImageView);
holder.contentLabel.setText(content.getTitle());
holder.contentShareButton.setTag(holder.contentImageView);
holder.contentShareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageView ivImage = (ImageView) v.getTag();
//ImageView ivImage = (ImageView) findViewById(R.id.ivResult);
// Get access to the URI for the bitmap
Uri bmpUri = getLocalBitmapUri(ivImage);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
mContext.startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
Log.i("test", "Sharing failed, handler error.");
}
}
});
return convertView;
}
// Returns the URI path to the Bitmap displayed in specified ImageView
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
Log.i("test", "is null");
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
Adding these four lines to the getLocalBitmapUri-function got it working for me:
bmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
And here is the complete function with the updated code:
// Returns the URI path to the Bitmap displayed in specified ImageView
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
bmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}

GridView Image (from URL) to Second Activity by using Intent

First of all im giving the codes what i'm using currently
MainActivity
static final String URL = "http://my .com/images/rss.xml";
static final String KEY_TITLE = "item";
static final String KEY_THUMB_URL = "thumb_url";
// Click event for single list row
gridView.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map2 = (HashMap<String, String>) parent.getItemAtPosition(position);
Intent in = new Intent(getApplicationContext(), FullSize.class);
Bitmap b; // your bitmap
in.putExtra(KEY_TITLE, map2.get(KEY_TITLE));
in.putExtra(KEY_THUMB_URL, KEY_THUMB_URL);
startActivity(in);
}
});
2nd Activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullsize);
ImageView image = (ImageView) findViewById(R.id.fullsizeimg2);
TextView txtName = (TextView) findViewById(R.id.txt1);
Intent in = getIntent();
// Receiving the Data
String name = in.getStringExtra("item");
Bitmap bitmap =(Bitmap) in.getParcelableExtra("thumb_url");
// Displaying Received data
txtName.setText(name);
image.setImageBitmap(bitmap);
}
}
in this case, if i use the codes as above , the title works , i can see the text in txt but i cannot get img. i think i need to convert it to bitmap but also it didnt work for me. for converting bitmap i used this
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),"Image ID");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
////////for intent /////
intent.putExtra("imagepass", bytes.toByteArray());
/////////2nd activity//////////
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("imagepass");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView iv=(ImageView) findViewById(R.id.fullsizeimg);
iv.setImageBitmap(bmp);
but in main activity after decoderesource line, it was giving this error :
The method decodeResource(Resources, int) in the type BitmapFactory is not applicable for the arguments (Resources, String)
I will be very happy if you can help.
You are using String as the second parameter in BitmapFactory.decodeResource()
But according to your code the Bitmap creation should be like this
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.yourImageId);

Android custom adapter list view images showing randomly while scroll

Hi i am a noob to android, I am trying to load some data to a ListView using custom adapter. I am using the following code for loading data. First time, it working well. But while I am trying to load more, then data loads and image is showing random while scrolling. After showing some random images in that list finally shows the correct image. It is repeating on the next scroll also
Here is my getView code
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.review_list_m, null);
v.setMinimumHeight(height);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.name);
holder.image = (ImageView) v.findViewById(R.id.posterView);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
int colorPos = position % colors.length;
v.setBackgroundColor(Color.parseColor(colors[colorPos]));
final Custom custom = entries.get(position);
if (custom != null) {
holder.image.setBackgroundColor(Color.parseColor(colors[colorPos]));
holder.image.setLayoutParams(new LinearLayout.LayoutParams(height-10,width-10));
String imgUrl=custom.getImage();
AsyncHttpClient client = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
client.get(imgUrl, new BinaryHttpResponseHandler(allowedContentTypes) {
#Override
public void onSuccess(byte[] fileData) {
// Do something with the file
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileData);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
holder.image.setImageBitmap(bitmap);
}
});
holder.item1.setHeight(height/3);
Log.v("PATH",custom.getcustomBig());
holder.item1.setText(custom.getcustomBig());
}
return v;
}
Any idea ? Please help
UPDATE
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.review_list_m, null);
v.setMinimumHeight(height);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.name);
holder.image = (ImageView) v.findViewById(R.id.posterView);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
int colorPos = position % colors.length;
v.setBackgroundColor(Color.parseColor(colors[colorPos]));
final Custom custom = entries.get(position);
if (custom != null) {
holder.image.setBackgroundColor(Color.parseColor(colors[colorPos]));
holder.image.setLayoutParams(new LinearLayout.LayoutParams(height-10,width-10));
final String imgUrl=custom.getImage();
holder.image.setTag(imgUrl);
holder.image.setImageBitmap(null);
Bitmap cachedBitmap = cache.get(imgUrl);
if( cachedBitmap == null) {
Log.v("HERE","DOWNLOADING");
AsyncHttpClient client = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
client.get(imgUrl, new BinaryHttpResponseHandler(allowedContentTypes) {
#Override
public void onSuccess(byte[] fileData) {
// Do something with the file
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileData);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
holder.image.setImageBitmap(bitmap);
}
});
}
else
{
holder.image.setImageBitmap(cachedBitmap);
}
holder.item1.setHeight(height/3);
//Log.v("PATH",custom.getcustomBig());
holder.item1.setText(custom.getcustomBig());
}
Problably you should set null bitmap to holder.image if v != null. Otherwise Android can show bitmap from other cell until new image is downloaded via async http request.
Example code (for problem with redownload images), it wasn't testes, but should give you idea how should it looks:
HashMap<String, Bitmap> cache = new HashMap<String, Bitmap>();
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//....
final Custom custom = entries.get(position);
if (custom != null) {
holder.image.setBackgroundColor(Color.parseColor(colors[colorPos]));
holder.image.setLayoutParams(new LinearLayout.LayoutParams(height-10,width-10));
String imgUrl=custom.getImage();
Bitmap cachedBitmap = cache.get(imgUrl);
if( cachedBitmap == null) {
AsyncHttpClient client = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
client.get(imgUrl, new BinaryHttpResponseHandler(allowedContentTypes) {
#Override
public void onSuccess(byte[] fileData) {
// Do something with the file
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileData);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
holder.image.setImageBitmap(bitmap);
cache.add( imgUrl, bitmap );
}
});
}
else
{
holder.image.setImageBitmap(cachedBitmap);
}
holder.item1.setHeight(height/3);
Log.v("PATH",custom.getcustomBig());
holder.item1.setText(custom.getcustomBig());
}
EDITed answer
Validate your imageview's tag hasn't change before you set the Bitmap.
You could try:
/**
* Caches an image (or a group of them) async.
* #author
*
*/
public static class ImageCacher extends AsyncTask<String, String, Integer>{
Context context;
ImageView iv;
Bitmap b;
public ImageCacher(Context context, ImageView iv){
this.context = context;
this.iv = iv;
}
#Override
protected Integer doInBackground(String... params) {
for(final String param:params){
//check if already CACHED
String filename = String.format("%d", param.hashCode());
File file = new File(context.getFilesDir(), filename);
if(file.exists()){
try {
b = BitmapFactory.decodeFile(file.getAbsolutePath());
} catch (Exception e) {
}
if(b != null){
if(iv != null){
iv.post(new Runnable() {
public void run() {
String tag = (String) iv.getTag();
if(tag != null){
if(tag.matches(param))
iv.setImageBitmap(b);
}
}
});
}
return 0;
}else{
file.delete();
}
}
//download
file = new File(context.getFilesDir(), filename);
b = saveImageFromUrl(context, param);
if(b != null){
if(iv != null){
iv.post(new Runnable() {
public void run() {
String tag = (String) iv.getTag();
if(tag != null){
if(tag.matches(param))
iv.setImageBitmap(b);
}
}
});
}
}
}
return 0;
}
}
/**
* Gets an image given its url
* #param param
*/
public static Bitmap saveImageFromUrl(Context context, String fullUrl) {
Bitmap b = null;
try {
URL url = new URL(fullUrl);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.connect();
//save bitmap to file
InputStream is = conn.getInputStream();
String filename = String.format("%d", fullUrl.hashCode());
File file = new File(context.getFilesDir(), filename);
if(file.exists()){
//delete
file.delete();
file=null;
}
file = new File(context.getFilesDir(), filename);
FileOutputStream out = new FileOutputStream(file);
byte buffer[] = new byte[256];
while(true){
int cnt = is.read(buffer);
if(cnt <=0){
break;
}
out.write(buffer,0, cnt);
}
out.flush();
out.close();
is.close();
b = BitmapFactory.decodeFile(file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
/**
* Gets an already cached photo
*
* #param context
* #param fullUrl
* #return
*/
public static Bitmap getCachedPhoto(Context context, String fullUrl){
System.gc();
String filename = String.format("%d", fullUrl.hashCode());
File file = new File(context.getFilesDir(), filename);
if(file.exists()){
try {
Bitmap b = BitmapFactory.decodeFile(file.getAbsolutePath());
return b;
} catch (Exception e) {
}
}
return null;
}
And then, to set the image in the adapter, you can do like:
//set info
vh.iv.setTag("");
String foto = your_url_goes_here;
vh.iv.setImageResource(R.drawable.fotodefault_2x);
if(!TextUtils.isEmpty(foto)){
vh.iv.setTag(foto);
Bitmap b = getCachedPhoto(context, foto);
if(b != null){
vh.iv.setImageBitmap(b);
}else{
new ImageCacher(context, vh.iv).execute(foto);
}
}
Don't forget to correctly encapsulate the class and methods.
Hope it helps.
I had this random pictures problem with my arrayAdapter. Then I used Picasso which takes care of imageView reusing in listview: http://square.github.io/picasso/
Example of code:
Picasso.with(mContext)
.load(url)
.resize(size, size)
.centerCrop()
.placeholder(R.drawable.image_holder)
.into(holder.imgDefaultImage);

Check when onClick is checked only?

I have a checkbox, that when checked, makes a bitmap and then saves that bitmap to internal storage. Then, in a gridView adapter, I have it check for the bitmap from internal storage with FileInputstream.
The issue is that the checkbox's onClick method is also in a class that extends baseadapter.
With the way it is now, when I start my app, it automatically checks for the bitmap and then returns a FileNotFound exception and then the onClick of the checkbox doesn't do anything.
I thought about this and realized that the reason it checks for it is that it is creating the gridView when I first open my app (which it is supposed to). In other words, it checks for the file because it is in the getView() method of my gridView adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
try {
Bitmap bitmapA = null;
FileInputStream in = Context.openFileInput("bitmapA");
bitmapA = BitmapFactory.decodeStream(in);
in.close();
/*BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
*/view.setImageBitmap(bitmapA);
if (in != null) {
in.close();
}
/*if (buf != null) {
buf.close();
}*/
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
Is there a way that I can make it check internal storage ONLY IF the checkbox is checked?
Please note that the onClick method of the checkbox is in one class while I am getting the bitmap in another.
Here are my two full classes:
AppInfoAdapter (the one with the onClick method---I will only post the needed coding here):
package com.example.awesomefilebuilderwidget;
IMPORTS
public class AppInfoAdapter extends BaseAdapter {
private Context mContext;
private List<ResolveInfo> mListAppInfo;
private PackageManager mPackManager;
private List<ResolveInfo> originalListAppInfo;
private Filter filter;
private String fname;
public AppInfoAdapter(Context c, List<ResolveInfo> listApp,
PackageManager pm) {
mContext = c;
this.originalListAppInfo = this.mListAppInfo = listApp;
mPackManager = pm;
Log.d("AppInfoAdapter", "top");
}
#Override
public int getCount() {
Log.d("AppInfoAdapter", "getCount()");
return mListAppInfo.size();
}
#Override
public Object getItem(int position) {
Log.d("AppInfoAdapter", "getItem");
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position) {
Log.d("AppInfoAdapter", "getItemId");
return position;
}
public static Bitmap scaleDownBitmap(Bitmap default_b, int newHeight, Context c) {
final float densityMultiplier = c.getResources().getDisplayMetrics().density;
int h= (int) (100*densityMultiplier);
int w= (int) (h * default_b.getWidth()/((double) default_b.getHeight()));
default_b=Bitmap.createScaledBitmap(default_b, w, h, true);
// TO SOLVE LOOK AT HERE:http://stackoverflow.com/questions/15517176/passing-bitmap-to-other-activity-getting-message-on-logcat-failed-binder-transac
return default_b;
}
public void SaveImage(Bitmap default_b) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-" + n +".png";
File file = new File (myDir, fname);
Log.i("AppInfoAdapter", "" + file);
if (file.exists()) file.delete();
try {
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + "/" + fname + ".png");
FileOutputStream out = mContext.getApplicationContext().openFileOutput("bitmapA", Context.MODE_WORLD_WRITEABLE);
// FileOutputStream out = new FileOutputStream(file);
default_b.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// get the selected entry
final ResolveInfo entry = (ResolveInfo) mListAppInfo.get(position);
// reference to convertView
View v = convertView;
// inflate new layout if null
if (v == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
v = inflater.inflate(R.layout.layout_appinfo, null);
Log.d("AppInfoAdapter", "New layout inflated");
}
// load controls from layout resources
ImageView ivAppIcon = (ImageView) v.findViewById(R.id.ivIcon);
TextView tvAppName = (TextView) v.findViewById(R.id.tvName);
TextView tvPkgName = (TextView) v.findViewById(R.id.tvPack);
final CheckBox addCheckbox = (CheckBox) v
.findViewById(R.id.addCheckbox);
Log.d("AppInfoAdapter", "Controls from layout Resources Loaded");
// set data to display
ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
tvAppName.setText(entry.activityInfo.loadLabel(mPackManager));
tvPkgName.setText(entry.activityInfo.packageName);
Log.d("AppInfoAdapter", "Data Set To Display");
addCheckbox
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (addCheckbox.isChecked()) {
System.out.println("Checked");
PackageManager pm = mContext.getPackageManager();
Drawable icon = null;
try {
icon = pm
.getApplicationIcon(entry.activityInfo.packageName);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable default_icon = pm.getDefaultActivityIcon();
if (icon instanceof BitmapDrawable
&& default_icon instanceof BitmapDrawable) {
BitmapDrawable icon_bd = (BitmapDrawable) icon;
Bitmap icon_b = icon_bd.getBitmap();
BitmapDrawable default_bd = (BitmapDrawable) pm
.getDefaultActivityIcon();
Bitmap default_b = default_bd.getBitmap();
if (icon_b == default_b) {
// It's the default icon
scaleDownBitmap(default_b, 100, v.getContext());
Log.d("AppInfoAdapter", "Scale Bitmap Chosen");
SaveImage(default_b);
Log.d("AppInfoAdapter", "Scaled BM saved to External Storage");
Intent intent = new Intent(v.getContext(), GridViewAdapter.class);
// intent.hasExtra("bitmapA");
v.getContext().startActivity(intent);
Log.d("AppInfoAdapter", "Intent started to send Bitmap");
}
}
} else {
System.out.println("Un-Checked");
}
}
});
// return view
return v;
}
GridViewAdapter:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class GridViewAdapter extends BaseAdapter {
private Context Context;
// Keep all Images in array list
public ArrayList<Integer> drawables = new ArrayList<Integer>();
// Constructor
public GridViewAdapter(Context c){
Context = c;
Log.d("GridViewAdapter", "Constructor is set");
drawables.add(R.drawable.pattern1);
Log.d("GridViewAdapter", "pattern1 added");
drawables.add(R.drawable.pattern2);
Log.d("GridViewAdapter", "pattern2 added");
drawables.add(R.drawable.trashcan);
Log.d("GridViewAdapter", "trashcan added");
drawables.add(R.drawable.ic_launcher);
Log.d("GridViewAdapter", "ic_launcher added");
Bitmap default_b = BitmapFactory.decodeFile("picture");
}
#Override
// How many items are in the data set represented by this Adapter
public int getCount() {
return drawables.size();
}
#Override
// Get the data item associated with the specified position in the
// data set
public Object getItem(int position) {
return drawables.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
try {
Bitmap bitmapA = null;
FileInputStream in = Context.openFileInput("bitmapA");
bitmapA = BitmapFactory.decodeStream(in);
in.close();
/*BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
*/view.setImageBitmap(bitmapA);
if (in != null) {
in.close();
}
/*if (buf != null) {
buf.close();
}*/
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
}
FURTHER UPDATED CODING:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
if(checked = true){
try {
Bitmap bitmapA = null;
FileInputStream in = Context.openFileInput("bitmapA");
bitmapA = BitmapFactory.decodeStream(in);
in.close();
/*BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
*/view.setImageBitmap(bitmapA);
if (in != null) {
in.close();
}
/*if (buf != null) {
buf.close();
}*/
} catch (Exception e) {
e.printStackTrace();
}}
PLUS I ADDED THIS METHOD:
public void setCheckBox(CheckBox checkbox){
mCheckBox=checkbox;
}
AND THIS VARIABLE:
CheckBox mCheckBox=null;
You dont need to listen to the onClick event in the adapter.
Instead, you can read the checkbox status.
for this, in your adapter, you add a field and a setter:
CheckBox mCheckBox=null;
public void setCheckBox( CheckBox checkbox){
mCheckBox=checkbox;
}
and then, in the getView(), you add thiss line at the begining;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
UPDATE
then in your activity, i suppose you have something like
GridViewAdapter mGridViewAdapter= new GridViewAdapter(this);
so, below you have to add:
CheckBox mCheckBox = findViewById(R,id.YOURCHECKBOXID);
mGridViewAdapter.setCheckBox(mCheckBox);
And that's it!

Categories

Resources