Saving image to gallery from imageview in viewpager - java

I managed to save the image from imageview to gallery with the onlongclicklistner() with the help of code given below. But the problem is that it always save the last image dosent matters which image i try to save.
public class CapturePhotoUtils {
public final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, title);
values.put(MediaStore.Images.Media.DISPLAY_NAME, title);
values.put(MediaStore.Images.Media.DESCRIPTION, description);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F, MediaStore.Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
private final Bitmap storeThumbnail(
ContentResolver cr,
Bitmap source,
long id,
float width,
float height,
int kind) {
// create the matrix to scale it
Matrix matrix = new Matrix();
float scaleX = width / source.getWidth();
float scaleY = height / source.getHeight();
matrix.setScale(scaleX, scaleY);
Bitmap thumb = Bitmap.createBitmap(source, 0, 0,
source.getWidth(),
source.getHeight(), matrix,
true
);
ContentValues values = new ContentValues(4);
values.put(MediaStore.Images.Thumbnails.KIND,kind);
values.put(MediaStore.Images.Thumbnails.IMAGE_ID,(int)id);
values.put(MediaStore.Images.Thumbnails.HEIGHT,thumb.getHeight());
values.put(MediaStore.Images.Thumbnails.WIDTH,thumb.getWidth());
Uri url = cr.insert(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, values);
try {
OutputStream thumbOut = cr.openOutputStream(url);
thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut);
thumbOut.close();
return thumb;
} catch (FileNotFoundException ex) {
return null;
} catch (IOException ex) {
return null;
}
}
}
I am putting images from the viewpager getting images from array of drawables
class CustomPagerAdapter extends PagerAdapter {
Context mContext;
LayoutInflater mLayoutInflater;
public CustomPagerAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mResources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.image_slider_item, container, false);
imageView = (TouchImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
imageView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
CapturePhotoUtils photoUtils = new CapturePhotoUtils();
imageView.setDrawingCacheEnabled(true);
Bitmap b = imageView.getDrawingCache();
photoUtils.insertImage(Full_Screen_Slider.this.getContentResolver(),
b, "1image", "this is downloaded image sample");
Toast.makeText(mContext, "longpress ", Toast.LENGTH_SHORT).show();
return true;
}
});
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}

Replace this
#Override
public Object instantiateItem(ViewGroup container,final int position) {
final View itemView = mLayoutInflater.inflate(R.layout.image_slider_item, container, false);
final TouchImageView imageView = (TouchImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
imageView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
CapturePhotoUtils photoUtils = new CapturePhotoUtils();
imageView.setDrawingCacheEnabled(true);
Bitmap b = imageView.getDrawingCache();
photoUtils.insertImage(Full_Screen_Slider.this.getContentResolver(),
b, "1image", "this is downloaded image sample");
Toast.makeText(mContext, "longpress ", Toast.LENGTH_SHORT).show();
return true;
}
});
container.addView(itemView);
return itemView;
}
it is replacing your view each time it calls instantiateItem so make it final which will help.

Related

Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent to activity

I m getting this error in my code.
Please help me.
My code is as follows. I don't know how to solve this. When I click on the add button I want to add all data to the model class and that class should be filled with the list array in main activity.
public class MainActivity extends Activity implements DataTransferInterfase{
private Button btnSelect,btnShow;
public int REQUEST_CAMERA=1;
public int SELECT_IMAGE=0;
private GridView gridview;
private CustomAdapter gridAdaptor;
public TextView tvcounter;
public ImageItemBin imageItemBin;
private Uri mCapturedImageUri;
public static ArrayList<ImageItemBin> publicSelectedImage=new ArrayList<ImageItemBin>();
public ArrayList<ImageItemBin> showImagelist=new ArrayList<ImageItemBin>();
public Uri ImageUri;
private int count=publicSelectedImage.size();
private int coloumn=3;
private int row=count/coloumn;
public String imgPath="";
private Uri fileUri; // file url to store image
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSelect=(Button)findViewById(R.id.btnselect);
btnShow=(Button)findViewById(R.id.btnShow);
tvcounter=(TextView)findViewById(R.id.tvcounter);
publicSelectedImage=new ArrayList<ImageItemBin>();
//showImagelist=new ArrayList<ImageItemBin>();
showImagelist=new ArrayList<ImageItemBin>();
gridview=(GridView) findViewById(R.id.gridLayout_main);
// gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage);
// gridview.setAdapter(gridAdaptor);
//gridAdaptor(R.layout.custom_grid_item_layout,getView());
//gridLayout.addView(gridAdaptor.getView());
//gridLayout.addView(inflater.inflate(R.layout.custom_grid_item_layout,null));
//gridLayout.addView(img);
//tvcounter.setText(CountRecord(imageItemBin));
//tvcounter.setText(CustomAdapter.result+"");
showImagelist.add(CustomAdapter.showBin);
tvcounter.setText(showImagelist.size());
//showImagelist.add(CustomAdapter.result);
//tvcounter.setText(counter);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//custom dialogBox
final Dialog dialog=new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog_layout);
dialog.setTitle("Select from..");
//set the custom dialog components
TextView txtmsg=(TextView)dialog.findViewById(R.id.txtmsg);
Button btnGallaery=(Button)dialog.findViewById(R.id.btngallery);
Button btnCamara=(Button)dialog.findViewById(R.id.btncamara);
btnGallaery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent image=new Intent();
image.setType("image/*");
image.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(image,"select file"),SELECT_IMAGE);
dialog.dismiss();
}
});
btnCamara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cam=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/*if(cam.resolveActivity(getPackageManager())!=null){
String filename="temp.jpg";
ContentValues values=new ContentValues();
values.put(MediaStore.Images.Media.TITLE,filename);
mCapturedImageUri=getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);*/
//cam.putExtra(MediaStore.EXTRA_OUTPUT,setImageUri());
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cam.putExtra("Image", fileUri);
startActivityForResult(cam,REQUEST_CAMERA);
dialog.dismiss();
// }
}
});
dialog.show();
}
});
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==SELECT_IMAGE){
if(resultCode==RESULT_OK && null!=data){
for (int i=0,c=0,r=0;i<count;i++,c++){
if(c==coloumn){
c=0;
r++;
}
}
ImageUri=data.getData();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(ImageUri.toString());
publicSelectedImage.add(imageItemBin);
gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage,this);
gridview.setAdapter(gridAdaptor);
}
}
if(requestCode==REQUEST_CAMERA)
{
if(resultCode==RESULT_OK && data!=null){
/*String[] projection={MediaStore.Images.Media.DATA};
Cursor cursor=managedQuery(mCapturedImageUri,projection,null,null,null);
int coloumn_index_data=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath=cursor.getString(coloumn_index_data);
Uri selectedImage=data.getData();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(selectedImage.toString());
publicSelectedImage.add(imageItemBin);*/
// gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage);
// gridview.setAdapter(gridAdaptor);
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
String stringImage=BitMapToString(mphoto);
// String getimage=getImagePath();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(stringImage);
//imageItemBin.setImage(picturePth.toString());
publicSelectedImage.add(imageItemBin);
gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage,this);
gridview.setAdapter(gridAdaptor);
//gridAdaptor.notifyDataSetChanged();
// tvcounter.setText(counter);
//publicSelectedImage=selectedImage;
}
}
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
/*private List<ImageItemBin> DisplayImage(){
ImageItemBin itembin=new ImageItemBin();
itembin.getImage();
}*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
/*File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
*/
//File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
// Create the storage directory if it does not exist
/*if (!file.exists()) {
if (!file.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}*/
// Create a media file name
//String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
// Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
} /*else if (type == MEDIA_TYPE_VIDEO) {
//mediaFile = new File(file.getPath() + File.separator
// + "VID_" + timeStamp + ".mp4");
}*/ else {
return null;
}
return mediaFile;
//return file;
}
private Bitmap previewCapturedImage(Uri file)
{
Bitmap bitmap=null;
try {
// hide video preview
//videoPreview.setVisibility(View.GONE);
//imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(file.getPath(),
options);
return bitmap;
//imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
return bitmap;
}
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;
}
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;
}
}
public static int totalAmt=0;
#Override
public int CountRecord(ImageItemBin bin) {
//for (int i=0;i<count;i++){
totalAmt=totalAmt+1;
// }
return totalAmt;
}
}
I just got it.
here is the way for getting the perfect result.in adapter just add the data.get(position)to countRecord method.
public int CountRecord(ImageItemBin bin)
{
showImagelist.add(showBin);
int size=showImagelist.size();
tvcounter.setText(Integer.toString(size));
btnShow.setText(Integer.toString(size));
return 0;
}
CustomAdaptor.java
public class CustomAdapter extends BaseAdapter {
public static String counter="";
public static int result=0;
Context context;
private int layoutResourceId;
private ArrayList<ImageItemBin> data=new ArrayList<ImageItemBin>();
public static ImageItemBin showBin=new ImageItemBin();
DataTransferInterfase dataTransferInterfase;
String qty,title;
public MainActivity mainActivity;
ImageLoader imageLoader;
DisplayImageOptions options;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity,ArrayList<ImageItemBin> data,DataTransferInterfase dataTransferInterfase){
this.data=data;
this.context=mainActivity;
this.dataTransferInterfase=dataTransferInterfase;
this.mainActivity=mainActivity;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
Holder holder=null;
View rootview=convertView;
if(rootview==null) {
rootview = inflater.inflate(R.layout.custom_grid_item_layout, null);
holder = new Holder();
holder.edttitle = (EditText) rootview.findViewById(R.id.edtTitle);
holder.edtqty = (EditText) rootview.findViewById(R.id.edtQty);
holder.image = (ImageView) rootview.findViewById(R.id.MyimageView);
holder.tvcounter=(TextView)rootview.findViewById(R.id.tvcounter);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
rootview.setTag(holder);
qty=holder.edtqty.getText().toString();
title=holder.edttitle.getText().toString();
data.get(position).setTitle(title);
data.get(position).setQty(qty);
}
else
{
holder=(Holder)convertView.getTag();
holder.image.setTag(position);
holder.edttitle.setTag(position);
holder.edtqty.setTag(position);
qty=holder.edtqty.getText().toString();
title=holder.edttitle.getText().toString();
data.get(position).setTitle(title);
data.get(position).setQty(qty);
}
String img=data.get(position).getImage();
final String title=data.get(position).getTitle();
final String qty=data.get(position).getQty();
options = getDisplayImageOptions(context, R.mipmap.ic_launcher);
imageLoader.displayImage(img, holder.image, options);
holder.btnadd=(Button)rootview.findViewById(R.id.btnAdd);
final Holder finalHolder = holder;
//public static final ImageItemBin showBin=new ImageItemBin();
holder.btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(position).setQty(qty);
data.get(position).setTitle(title);
showBin.setImage(data.get(position).getImage());
showBin.setTitle(title);
showBin.setQty(qty);
mainActivity.CountRecord(data.get(position));
}
});
return rootview;
}
static class Holder{
ImageView image;
EditText edtqty;
EditText edttitle;
Button btnadd;
TextView tvcounter;
}
public static DisplayImageOptions getDisplayImageOptions(Context context, int defaultImg) {
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(defaultImg)
.resetViewBeforeLoading(true).showImageForEmptyUri(defaultImg).showImageOnFail(defaultImg)
.cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true).build();
return options;
}
}

Mutiple Contact Picker not working in Android api level less than 17

I have a code to read the contacts from the inbuilt phone contacts and it displays all the contacts in a list view in my app.The user can select multiple contacts and display them in another activity.
This code works fine in Android API level 18 and above,but gives an error in the versions below API 18.
I'm attaching the code of the contact picker activity and its adapter.
Error Logcat
private void getSelectedContacts() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
for (ContactObject bean : ContactsListClass.phoneList) {
if (bean.isSelected()) {
sb.append(bean.getName());
sb.append(bean.getNumber());
sb.append("1");
values.put(DbHelper.KEY_FNAME,bean.getName());
values.put(DbHelper.KEY_LNAME,bean.getNumber() );
values.put(DbHelper.KEY_INVITE,"1" );
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
}
dataBase.close();
String s = sb.toString().trim();
if (TextUtils.isEmpty(s)) {
Toast.makeText(context, "Select atleast one Contact",
Toast.LENGTH_SHORT).show();
} else {
s = s.substring(0, s.length() - 1);
/**
Toast.makeText(context, "Selected Contacts : " + s,
Toast.LENGTH_SHORT).show();
**/
Intent i = new Intent(Contacts_main.this, MainActivity.class);
i.putExtra("NAME", name);
i.putExtra("EVT_Name", event_name);
i.putExtra("EVT_Date", event_date);
startActivity(i);
}
}
private void addContactsInList() {
// TODO Auto-generated method stub
Thread thread = new Thread() {
#Override
public void run() {
showPB();
try {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
try {
ContactsListClass.phoneList.clear();
} catch (Exception e) {
}
while (phones.moveToNext()) {
String phoneName = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneImage = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
//String pImage =
ContactObject cp = new ContactObject();
cp.setName(phoneName);
cp.setNumber(phoneNumber);
cp.setImage(phoneImage);
//cp.setImage(getResources(R.drawable.prof_active));
ContactsListClass.phoneList.add(cp);
}
phones.close();
lv = new ListView(context);
lv.setDividerHeight(0);
lv.setDivider(null);
lv.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
llContainer.addView(lv);
}
});
Collections.sort(ContactsListClass.phoneList,
new Comparator<ContactObject>() {
#Override
public int compare(ContactObject lhs,
ContactObject rhs) {
return lhs.getName().compareTo(
rhs.getName());
}
});
objAdapter = new ContactsAdapter(Contacts_main.this,
ContactsListClass.phoneList);
lv.setAdapter(objAdapter); //ERROR SHOWING HERE
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
CheckBox chk = (CheckBox) view
.findViewById(R.id.contactcheck);
ContactObject bean = ContactsListClass.phoneList
.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
} catch (Exception e) {
// e.printStackTrace();
//Toast.makeText(context, "Crash",Toast.LENGTH_SHORT).show();
}
hidePB();
}
};
thread.start();
}
Adapter Class:
Context mContext;
LayoutInflater inflater;
private List<ContactObject> mainDataList = null;
private List<ContactObject> mainInviteesList = null;
private ArrayList<ContactObject> arraylist;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
public ContactsAdapter(Context context, List<ContactObject> mainDataList) {
mContext = context;
this.mainDataList = mainDataList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ContactObject>();
this.arraylist.addAll(mainDataList);
mHelper=new DbHelper(context);
}
static class ViewHolder {
protected TextView name;
protected TextView number;
protected CheckBox check;
protected ImageView image;
protected EditText invitees;
}
#Override
public int getCount() {
return mainDataList.size();
}
#Override
public ContactObject getItem(int position) {
return mainDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_row, null);
holder.name = (TextView) view.findViewById(R.id.contactname);
holder.number = (TextView) view.findViewById(R.id.contactno);
holder.check = (CheckBox) view.findViewById(R.id.contactcheck);
holder.image = (ImageView) view.findViewById(R.id.contactimage);
holder.invitees = (EditText) view.findViewById(R.id.editInvites);
view.setTag(holder);
view.setTag(R.id.contactname, holder.name);
view.setTag(R.id.contactno, holder.number);
view.setTag(R.id.contactcheck, holder.check);
view.setTag(R.id.editInvites, holder.invitees);
holder.check
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton vw,
boolean isChecked) {
int getPosition = (Integer) vw.getTag();
mainDataList.get(getPosition).setSelected(
vw.isChecked());
/**
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,mainDataList.get(getPosition).getName());
values.put(DbHelper.KEY_LNAME,mainDataList.get(getPosition).getNumber());
values.put(DbHelper.KEY_INVITE,"1" );
dataBase.insert(DbHelper.TABLE_NAME, null, values);
dataBase.close();
**/
}
});
// holder.invitees.addTextChangedListener(watcher);
} else {
holder = (ViewHolder) view.getTag();
}
holder.check.setTag(position);
//holder.invitees.setTag(position);
holder.name.setText(mainDataList.get(position).getName());
holder.number.setText(mainDataList.get(position).getNumber());
if(getByteContactPhoto(mainDataList.get(position).getImage())==null){
holder.image.setImageResource(R.drawable.prof_active);
}else{
holder.image.setImageBitmap(getByteContactPhoto(mainDataList.get(position).getImage()));
}
holder.check.setChecked(mainDataList.get(position).isSelected());
return view;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
mainDataList.clear();
if (charText.length() == 0) {
mainDataList.addAll(arraylist);
} else {
for (ContactObject wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
mainDataList.add(wp);
}
}
}
notifyDataSetChanged();
}
public Bitmap getByteContactPhoto(String contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, Long.parseLong(contactId));
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = mContext.getContentResolver().query(photoUri,
new String[] {Contacts.Photo.DATA15}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream( new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
}

Using AsyncTask to load images into a adapter for ListView

Hello So I Was Having Problems With My List View That Contains Songs And There AlbumArt and I Want To make an AsyncTask To Get The Album Art In background.
Put Its either giving Me A NullPointer Or The Album Art is Blank Please Help
ImageLoader.java
public class ImageLoader extends AsyncTask<Object, String, Bitmap> {
private View view;
private Bitmap bitmap = null;
public static BitmapDrawable drawable = null;
Context context;
Cursor cursor;
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
#Override
protected Bitmap doInBackground(Object... parameters) {
// Get the passed arguments here
final Uri ART_CONTENT_URI = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(ART_CONTENT_URI, albumId);
ContentResolver res = context.getContentResolver();
InputStream in;
try {
if(bitmap != null)
{
bitmap = null;
if(drawable != null)
{
drawable = null;
}
}
in = res.openInputStream(albumArtUri);
bitmap = BitmapFactory.decodeStream(in);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 1280, 720, false);
// bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), albumArtUri);
drawable = new BitmapDrawable(context.getResources(), resizedBitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
drawable = (BitmapDrawable) context.getResources().getDrawable(R.drawable.default_artwork);
};
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null && view != null) {
ImageView albumArt = (ImageView) view.getTag(R.id.iconlist);
albumArt.setImageBitmap(bitmap);
}
}
}
SongAdapter.java
public class SongAdapter extends CursorAdapter implements SectionIndexer{
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private final LayoutInflater mInflater;
public SongAdapter(Context context, Cursor c, int textViewResourceId,
List<String> objects) {
super(context, c,textViewResourceId);
new ImageLoader().execute();
mInflater=LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title1 = (TextView) view.findViewById(R.id.titlelist);
TextView artist1 = (TextView) view.findViewById(R.id.artistlist);
ImageView album1 = (ImageView) view.findViewById(R.id.iconlist);
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
StringBuilder titleBuild = new StringBuilder();
titleBuild.append(title);
if(titleBuild.length() > 35)
{
titleBuild.setLength(32);
title = titleBuild.toString()+"...";
}
else
{
title = titleBuild.toString();
}
StringBuilder artistBuild = new StringBuilder();
artistBuild.append(artist);
if(artistBuild.length() > 35)
{
artistBuild.setLength(32);
artist = artistBuild.toString()+"...";
}
else
{
artist = artistBuild.toString();
}
album1.setImageDrawable(ImageLoader.drawable);
title1.setText(title);
artist1.setText(artist);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.rowlayout, parent, false);
}#Override
public int getPositionForSection(int section) {
// If there is no item for current section, previous section will be selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
if (StringMatcher.match(String.valueOf(( getItem(j))), String.valueOf(k)))
return j;
}
} else {
if (StringMatcher.match(String.valueOf(getItem(j)), String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
Now This Code Gives Me A Null Pointer So Any Help Would Be Great
Your view object in the Async task is never initialized, atleast I don't see that code. What I think you could do is launch a new AsyncTask for every "new" view you're creating in your adapter. You would need to make the async task have a reference to the imageview you want to populate though. One way to do this is like this.
public class ImageLoader extends AsyncTask<Object, String, Bitmap> {
private WeakReference<ImageView> mReference;
private View view;
private Bitmap bitmap = null;
public static BitmapDrawable drawable = null;
Context context;
Cursor cursor;
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
public ImageLoader(ImageView imageView) {
mReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(Object... parameters) { ... your code }
#Override
protected Void onPostExecute(Bitmap bitmap) {
if(mReference != null) {
if(bitmap != null) {
ImageView view = mReference.get();
// note that this could still return null if the view or the reference has been
// garbage collected which it could be since it is a weak reference, so you should
// always check the status in this case.
//do what you want with the image view.
}
}
}
then in your adapter do something like this.
public class SongAdapter extends CursorAdapter implements SectionIndexer{
...other code...
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title1 = (TextView) view.findViewById(R.id.titlelist);
TextView artist1 = (TextView) view.findViewById(R.id.artistlist);
ImageView album1 = (ImageView) view.findViewById(R.id.iconlist);
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
StringBuilder titleBuild = new StringBuilder();
titleBuild.append(title);
if(titleBuild.length() > 35)
{
titleBuild.setLength(32);
title = titleBuild.toString()+"...";
}
else
{
title = titleBuild.toString();
}
StringBuilder artistBuild = new StringBuilder();
artistBuild.append(artist);
if(artistBuild.length() > 35)
{
artistBuild.setLength(32);
artist = artistBuild.toString()+"...";
}
else
{
artist = artistBuild.toString();
}
<---->
// new code
new ImageLoader(album1).execute();
// old code album1.setImageDrawable(ImageLoader.drawable);
title1.setText(title);
artist1.setText(artist);
}
}
I've used a similar technique in a grid view and it's cool because you can actually see each image view being populated.
Hope that helps!

ListView and Images: I'm going crazy

i have a big problem that is driving me crazy. I have a ListView with all apps installed but the scroll is very slow, so i want to improve it. I tried to put a Thread but it doesn't solv the problem. This is the code
ApplicationAdapter
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
Holder holder;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
final Holder holder;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.snippet_list_row, null);
holder = new Holder();
holder.appName = (TextView) view.findViewById(R.id.app_name);
holder.packageName = (TextView) view.findViewById(R.id.app_paackage);
holder.iconview = (ImageView) view.findViewById(R.id.app_icon);
view.setTag(holder);
}
else
{
holder = (Holder)view.getTag();
}
final ApplicationInfo data = appsList.get(position);
if (null != data) {
holder.appName.setText(data.loadLabel(packageManager));
holder.packageName.setText(data.packageName);
holder.iconview.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
static class Holder
{
TextView appName, packageName;
ImageView iconview;
}
}
Activity
public class Activity_Eclair extends ListActivity {
public PackageManager packageManager = null;
public List<ApplicationInfo> applist = null;
public ApplicationAdapter listadaptor = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eclair);
ListView lv = getListView();
lv.setFastScrollEnabled(true);
lv.setScrollingCacheEnabled(false);
registerForContextMenu(lv);
packageManager = getPackageManager();
new LoadApplications().execute();
Button bottone1 = (Button)findViewById(R.id.button1);
bottone1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new LoadApplications().execute();
}
});};
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
Uri packageUri = Uri.parse("package:"+app.packageName);
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageUri);
startActivity(uninstallIntent);
}
public List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
public ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(Activity_Eclair.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
protected void onDestroy() {
if(progress!=null)
if(progress.isShowing()){
progress.dismiss();
}
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(Activity_Eclair.this, null,
"Loading...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
private final static int UPDATE_MENU_OPTION = 1;
private final static int DELETE_MENU_OPTION = 2;
private final static int TRUNCATE_MENU_OPTION = 3;
private final static int DELETE = 4;
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
final long examId = info.id;
ApplicationInfo app = applist.get((int) info.id);
switch (item.getItemId()) {
case UPDATE_MENU_OPTION:
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(Activity_Eclair.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(Activity_Eclair.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
return true;
case DELETE_MENU_OPTION:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id="+app.packageName));
startActivity(browserIntent);
return true;
case TRUNCATE_MENU_OPTION:
try {
//Open the specific App Info page:
Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + app.packageName));
startActivity(intent);
} catch ( ActivityNotFoundException e ) {
//e.printStackTrace();
//Open the generic Apps page:
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
startActivity(intent);
}
return true;
case DELETE:
{
Uri packageUri = Uri.parse("package:"+app.packageName);
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageUri);
startActivity(uninstallIntent);
}
return true;
default:
return super.onContextItemSelected(item);
}
}
I state that I have already tried numerous snippets present on StackOverflow and on the Web but do not work.
}
1 - edit Manifest file add to activity
android:hardwareAccelerated="true"
2- Cache and draw icons to ImageView oneByOne we need 4 classes witch is :
Utils.class
public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}
MemoryCache.class
public class MemoryCache {
private static final String TAG = "MemoryCache";
private Map<String, Bitmap> cache=Collections.synchronizedMap(
new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
private long size=0;//current allocated size
private long limit=1000000;//max memory in bytes
public MemoryCache(){
//use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory()/4);
}
public void setLimit(long new_limit){
limit=new_limit;
Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
}
public Bitmap get(String id){
try{
if(!cache.containsKey(id))
return null;
return cache.get(id);
}catch(NullPointerException ex){
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap){
try{
if(cache.containsKey(id))
size-=getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size+=getSizeInBytes(bitmap);
checkSize();
}catch(Throwable th){
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size="+size+" length="+cache.size());
if(size>limit){
Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();
while(iter.hasNext()){
Entry<String, Bitmap> entry=iter.next();
size-=getSizeInBytes(entry.getValue());
iter.remove();
if(size<=limit)
break;
}
Log.i(TAG, "Clean cache. New size "+cache.size());
}
}
public void clear() {
try{
cache.clear();
size=0;
}catch(NullPointerException ex){
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if(bitmap==null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
FileCache.class
public class FileCache {
private File cacheDir;
String cacheFile = "cachefolder";
public FileCache(Context context, String subfolder ){
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),cacheFile+"/"+subfolder);
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
public FileCache(Context context){
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),cacheFile);
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url){
//I identify images by hashcode. Not a perfect solution, good for the demo.
String filename = String.valueOf(url.hashCode());
//Another possible solution (thanks to grantland)
//String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear(){
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
ImageLoader.class :
public class ImageLoader {
public static int REQUIRED_SIZE=100;
public MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
int stub_id = R.drawable.drawing_image;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
}
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put( imageView, url );
Bitmap bitmap = memoryCache.get(url);
if( bitmap != null )
{
imageView.setImageBitmap(bitmap);
}
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
/* private Bitmap bitmap_to_circel( Bitmap bitmap)
{
return bitmap;
Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader (bitmap, TileMode.CLAMP, TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);
return circleBitmap;
}*/
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
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;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
#Override
public void run() {
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
3 - Add ImageLoader to your ApplicationAdapter and Start display images
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
Holder holder;
//added imageloader here <<------------------
ImageLoader imgLoader;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
//Register image loader class <<---------------------
imgLoader = new ImageLoader(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
final Holder holder;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.snippet_list_row, null);
holder = new Holder();
holder.appName = (TextView) view.findViewById(R.id.app_name);
holder.packageName = (TextView) view.findViewById(R.id.app_paackage);
holder.iconview = (ImageView) view.findViewById(R.id.app_icon);
view.setTag(holder);
}
else
{
holder = (Holder)view.getTag();
}
final ApplicationInfo data = appsList.get(position);
if (null != data) {
holder.appName.setText(data.loadLabel(packageManager));
holder.packageName.setText(data.packageName);
//now load icon provide Url and ImageView only and keep the rest to the class
//provide fill link url to the icon the class will download it , cache it , display it
//next time when scroll again to this position the icon will be displayed from cache file
imgLoader.DisplayImage(data.icon_link_url_with_http, holder.iconview);
}
return view;
}
static class Holder
{
TextView appName, packageName;
ImageView iconview;
}
}
now your list view will scroll quickly even if its has 1k ImageView
holder.iconview.setImageDrawable(data.loadIcon(packageManager));
You do that everytime you set an image, which is very very slow, hitting the disk and loading the image in full scale. Some apps have very big launcher icons, this can kill your ram quickly. Load all images into ram or the cache folder before creating the listview and it will run a lot quicker.

out of memory exception

I am new to android. I am doing image listing form sd-card.Following code give me error "Out of memory on a 614416-byte allocation."
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.ll_sponsor_list_item,
parent, false);
final ImageView img = (ImageView) convertView
.findViewById(R.id.imggrid_item_image);
String imgurl = ImageName.get(position);
AsyncImageLoaderv asyncImageLoaderv = new AsyncImageLoaderv();
Bitmap cachedImage = asyncImageLoaderv.loadDrawable(imgurl,
new AsyncImageLoaderv.ImageCallback() {
public void imageLoaded(Bitmap imageDrawable,
String imageUrl) {
img.setImageBitmap(imageDrawable);
}
});
img.setImageBitmap(cachedImage);
cachedImage.recycle();
return convertView;
}
Class:
class AsyncImageLoaderv {
int width;
int height;
float aspectRatio;
int newWidth;
int newHeight;
public Bitmap loadDrawable(final String imageUrl,
final ImageCallback imageCallback) {
final Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
imageCallback.imageLoaded((Bitmap) message.obj, imageUrl);
}
};
new Thread() {
#Override
public void run() {
try {
Log.d("ur", imageUrl);
Bitmap drawable = BitmapFactory.decodeFile(imageUrl);
width = drawable.getWidth();
height = drawable.getWidth();
aspectRatio = (float) width / (float) height;
newWidth = 98;
newHeight = (int) (98 / aspectRatio);
Bitmap.createScaledBitmap(drawable, newWidth, newHeight,
true);
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
//this.sleep(1000);
} catch (Exception e) {
Log.e("thread stellent", e.toString());
}
}
}.start();
return null;
}
public interface ImageCallback {
public void imageLoaded(Bitmap imageBitmap, String imageUrl);
}
}
As I answered in that question:
Android - Outofmemory error by decodefile or decodeStream to convert the Uri selected to bitmap
Bitmaps can not hold heavyweight pictures. Read this post, it is possible to reduce size of images.

Categories