Bitmap resulting null even for particular path - android

I'm working on getting image from the camera and gallery. I'm trying to get the bitmap of the image to reduce the size of the image. But the bitmapfactory is null when I tried debugging the process. I'm not understanding why it is so even for absolute uri. I'm implementing inside adapter.
#SuppressLint("ResourceAsColor")
public class PSAdapter extends BaseAdapter{
private Context mContext;
private ArrayList<Message> mMessages;
public PSAdapter(Context context, ArrayList<Message> messages) {
super();
this.mContext = context;
this.mMessages = messages;
}
#Override
public int getCount() {
return mMessages.size();
}
#Override
public Object getItem(int position) {
return mMessages.get(position);
}
#SuppressWarnings("deprecation")
#SuppressLint("ResourceAsColor")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Message message = (Message) this.getItem(position);
ViewHolder holder;
if(convertView == null)
{
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.sms, parent, false);
holder.message = (TextView) convertView.findViewById(R.id.message_text);
holder.picture = (ImageView) convertView.findViewById(R.id.chat_image);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
if(message.message==null){
holder.message.setVisibility(View.GONE);
holder.picture.setVisibility(View.VISIBLE);
Bitmap attachment = getScaledBitmap("content://media/external/images/media/4391", 800, 800);
holder.picture.setImageBitmap(attachment);
}else{
holder.message.setVisibility(View.VISIBLE);
holder.picture.setVisibility(View.GONE);
holder.message.setText(message.getMessage());
}
LayoutParams lp = (LayoutParams) holder.message.getLayoutParams();
if(message.isStatusMessage())
{
holder.message.setBackgroundDrawable(null);
lp.gravity = Gravity.LEFT;
holder.message.setTextColor(R.color.textFieldColor);
}
else
{
if(message.isMine())
{
holder.message.setBackgroundResource(R.drawable.speech_bubble_green);
lp.gravity = Gravity.RIGHT;
}
else
{
holder.message.setBackgroundResource(R.drawable.speech_bubble_orange);
lp.gravity = Gravity.LEFT;
}
holder.message.setLayoutParams(lp);
holder.message.setTextColor(R.color.textColor);
}
return convertView;
}
public static class ViewHolder
{
TextView message;
ImageView picture;
}
#Override
public long getItemId(int position) {
return 0;
}
private Bitmap getScaledBitmap(String picPath, int width, int height){
BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
sizeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picPath,sizeOptions);
int inSampleSize = imageSize(sizeOptions, width, height);
sizeOptions.inJustDecodeBounds = false;
sizeOptions.inSampleSize = inSampleSize;
return BitmapFactory.decodeFile(picPath, sizeOptions);
}
private int imageSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
final int height = options.outHeight;
final int width = options.outWidth;
int size = 1;
if(height>reqHeight || width>reqWidth){
final int heightRatio = Math.round((float)height/(float)reqHeight);
final int widthRatio = Math.round((float)width/(float)reqWidth);
size = heightRatio<widthRatio? heightRatio:widthRatio;
}
return size;
}
}

Related

how to show all photos using AsyncTask

I want to collect all photos in pictures directory to show them in GridView, so tried with two ways.
1_ without using AsyncTask: this way worked very well but it has a problem which is that the app freezes for seconds to get all photos in specified directory and it's sub directories.
2_using AsyncTask: this way doesn't get any images and the list of images is always empty, I know that I should use Asynctask for processes that take mush time to processed and I don't know what I missed when using AsyncTask.
what I want is to find a way to collect all photos using AsyncTask with app freezing and thanks in advance.
public static class ImagesFragment extends Fragment {
static List<Image> imagesList = new ArrayList<>();
GridViewRecyclerAdapter gridViewRecyclerAdapter;
GridView gridView;
Spinner spinner;
public static File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// imagesList = loadImageData(file);
gridViewRecyclerAdapter = new GridViewRecyclerAdapter(imagesList, getContext());
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_images, container, false);
spinner = view.findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.spinner, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
break;
case 1:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
gridView = view.findViewById(R.id.grid_view);
gridView.setAdapter(gridViewRecyclerAdapter);
return view;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static List<Image> loadImageData(File file) {
String fileType;
String extension;
if(file.isDirectory()){
File[] files = file.listFiles();
for(File file1: files){
if(file1.isDirectory())
loadImageData(file1);
else{
extension = MimeTypeMap.getFileExtensionFromUrl(file1.getPath());
if (extension != null) {
fileType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if(fileType != null)
if(fileType.contains("image")){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calculateInSampleSize(options, 500, 500);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(file1.getAbsolutePath(), options);
// bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight())
imagesList.add(new Image(bitmap, file1.getName(), file1.getPath()));
}
}
}
}
}
else {
extension = MimeTypeMap.getFileExtensionFromUrl(file.getPath());
if (extension != null) {
fileType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if(fileType != null)
if(fileType.contains("image")){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calculateInSampleSize(options, 500, 500);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
imagesList.add(new Image(bitmap, file.getName(), file.getPath()));
}
}
}
return imagesList;
}
}
public static class GridViewRecyclerAdapter extends BaseAdapter {
List<Image> imageList;
Context context;
static int position;
public GridViewRecyclerAdapter(List<Image> imageList, Context context){
this.imageList = imageList;
this.context = context;
}
#Override
public int getCount() {
return imageList.size();
}
#Override
public Object getItem(int position) {
return imageList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.images_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.imageView = convertView.findViewById(R.id.image_view);
viewHolder.imageView.setTag(imageList.get(position).path);
viewHolder.textView = convertView.findViewById(R.id.text_view);
convertView.setTag(viewHolder);
}
else
viewHolder = (ViewHolder) convertView.getTag();
new LoadImageAsyncTask().execute(ImagesFragment.file.getAbsolutePath());
viewHolder.imageView.setImageBitmap(imageList.get(position).bitmap);
viewHolder.textView.setText(imageList.get(position).title);
GridViewRecyclerAdapter.position = position;
return convertView;
}
public static class ViewHolder{
ImageView imageView;
TextView textView;
}
static class LoadImageAsyncTask extends AsyncTask<String, Void, List<Image>> {
#Override
protected List<Image> doInBackground(String... objects) {
ImagesFragment.imagesList = ImagesFragment.loadImageData(new File(objects[0]));
return ImagesFragment.imagesList;
}
}
}

PagerAdapter OOM Error using ImageView

I Have problem with sliding pictures in my activity. When I slide 5-10 times I get an OutOfMemoryError. This is nothing extraordinary. My problem is related with using BitmapFactory and calculating size of image like in this page: https://android.jlelse.eu/loading-large-bitmaps-efficiently-in-android-66826cd4ad53. I don't know how it works when I'm using SlidingAdapter/PagerAdapter and my images are numbered.
This is my code:
public class SliderAdapter extends PagerAdapter {
static Resources res = null;
Context context;
LayoutInflater layoutInflater;
public SliderAdapter(Context context)
{
this.context = context;
slide_headings = context.getResources().getStringArray(R.array.p06_naglowek);
slide_descs = context.getResources().getStringArray(R.array.p06_opis);
}
public int [] slide_images = {
R.drawable.komputer_startowe,
R.drawable.ecu_version,
R.drawable.potrzebne_elementy,
R.drawable.co_gdzie,
R.drawable.rm11,
R.drawable.p06_finish
};
String[] slide_headings;
String[] slide_descs;
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
#Override
public int getCount() {
return slide_headings.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (RelativeLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout, container, false);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = calculateInSampleSize(options, 500,500);
Bitmap startImage = BitmapFactory.decodeResource(context.getResources(),R.drawable.komputer_startowe,options);
ImageView slideImageView = (ImageView) view.findViewById(R.id.slide_image);
TextView slideHeading = (TextView) view.findViewById(R.id.slide_heading);
TextView slideDescription = (TextView) view.findViewById(R.id.slide_desc);
slideImageView.setImageResource(slide_images[position]);
slideHeading.setText(slide_headings[position]);
slideDescription.setText(slide_descs[position]);
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((RelativeLayout)object);
}
}
Okay, I've got solution. Maybe it'll be usable for someone.
Here is the activity:
public class SliderAdapter extends PagerAdapter {
static Resources res = null;
Context context;
LayoutInflater layoutInflater;
static Bitmap bitmap;
public SliderAdapter(Context context)
{
this.context = context;
slide_headings = context.getResources().getStringArray(R.array.p06_naglowek);
slide_descs = context.getResources().getStringArray(R.array.p06_opis);
}
public int [] slide_images = {
R.drawable.komputer_startowe,
R.drawable.ecu_version,
R.drawable.potrzebne_elementy,
R.drawable.co_gdzie,
R.drawable.rm11,
R.drawable.p06_finish
};
String[] slide_headings;
String[] slide_descs;
#Override
public int getCount() {
return slide_headings.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (RelativeLayout) object;
}
#NonNull
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 1;
// o.inDither = false;
o.inScaled = true;
o.inDensity = srcWidth;
o.inTargetDensity = dstWidth*o.inSampleSize;
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), slide_images[position], o);
ImageView slideImageView = (ImageView) view.findViewById(R.id.slide_image);
TextView slideHeading = (TextView) view.findViewById(R.id.slide_heading);
TextView slideDescription = (TextView) view.findViewById(R.id.slide_desc);
slideImageView.setImageResource(slide_images[position]);
slideHeading.setText(slide_headings[position]);
slideDescription.setText(slide_descs[position]);
slideImageView.setImageBitmap(bitmap);
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((RelativeLayout)object);
}
}

List View changes position of ImageView On scroll

I am using List View with custom array adapter the adapter sets data from Sqlite. But when the list items reach over 10 (or list becomes scroll able) the Image View changes position automatically if i scrolls continue. here is my custom adapter's code.Thanks
public class CustomeAdapter extends ArrayAdapter<String>{
public Context context;
public ArrayList<String> titleArrayList, descArrayList, timeArrayList, imgArrayList, IdArrayList;
List data;
int layoutResID;
private Bitmap myBitmap;
public CustomeAdapter(Context context, int layoutResourceId, ArrayList<String> titleArrayList, ArrayList<String> descArrayList, ArrayList<String> timeArrayList, ArrayList<String> imgArrayList, ArrayList<String> IdArrayList) {
super(context, layoutResourceId, titleArrayList);
this.context = context;
this.titleArrayList = titleArrayList;
this.descArrayList = descArrayList;
this.timeArrayList = timeArrayList;
this.imgArrayList = imgArrayList;
this.IdArrayList = IdArrayList;
this.data = data;
this.layoutResID = layoutResourceId;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
final StockQuoteView sqView;
if (rowView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
rowView = inflater.inflate(layoutResID, parent, false);
sqView = new StockQuoteView();
sqView.tag = (TextView) rowView.findViewById(R.id.tv_fullnote);
sqView.desc = (TextView) rowView.findViewById(R.id.tv_title);
sqView.time = (TextView) rowView.findViewById(R.id.tv_time);
sqView.id = (TextView) rowView.findViewById(R.id.id);
sqView.img = (ImageView) rowView.findViewById(R.id.imageView3);
sqView.button1 = (ImageView) rowView.findViewById(R.id.swipe_button1);
sqView.button2 = (ImageView) rowView.findViewById(R.id.swipe_button2);
sqView.button3 = (ImageView) rowView.findViewById(R.id.swipe_button3);
sqView.button4 = (ImageView) rowView.findViewById(R.id.swipe_button4);
rowView.setTag(sqView);
} else {
sqView = (StockQuoteView) rowView.getTag();
}
try {
sqView.tag.setText(titleArrayList.get(position));
sqView.desc.setText(descArrayList.get(position));
sqView.time.setText(timeArrayList.get(position));
sqView.id.setText(IdArrayList.get(position));
sqView.id.setTag(IdArrayList.get(position).toString());
if (imgArrayList.get(position).contains("null")) {
sqView.img.setImageBitmap(null);
sqView.img.setTag("null");
} else {
myBitmap = BitmapFactory.decodeFile(imgArrayList.get(position));
//sqView.img.setImageBitmap((position & 1) == 1 ? myBitmap : myBitmap);
String TAG = "tag";
String id = String.valueOf(position);
sqView.img.setTag(imgArrayList.get(position).toString());
int width = myBitmap.getWidth();
int height = myBitmap.getHeight();
int newWidth = (height > width) ? width : height;
int newHeight = (height > width) ? height - (height - width) : height;
int crop = (width - height) / 2;
crop = (crop < 0) ? 0 : crop;
Bitmap cropImg = Bitmap.createBitmap(myBitmap, crop, 0, newWidth, newHeight);
sqView.img.setImageBitmap(cropImg);
}
} catch (Exception e) {
System.out.print(e.toString());
}
return rowView;
}
protected static class StockQuoteView {
protected TextView tag;
protected TextView desc;
protected TextView time;
protected ImageView img;
protected ImageView button1;
protected ImageView button2;
protected ImageView button3;
protected ImageView button4;
public TextView id;
}
}
`
put this linesqView.img.setVisibility(View.INVISIBLE) after sqView.img.setTag("null"); and Make Visible back the imageView in the else statment like else {sqView.img.setVisibility(View.VISIBLE)
myBitmap = BitmapFactory.decodeFile(imgArrayList.get(position));
//sqView.img.setImageBitmap((position & 1) == 1 ? myBitmap : myBitmap);
String TAG = "tag";
String id = String.valueOf(position);............}
this is tricked only.

Listing photos captured Android

Im trying to make a list of photos after taking photo. After secont photo taken it appear as the second item in the list. I faced some problem. I've created Adapters and try using it. As i am taking photos the same photo is shown in the listview. I am using method i found in internet.
photo class :
public class Photo {
public Bitmap icon;
public String title;
public Photo(){
super();
}
public Photo(Bitmap bitmap, String title) {
super();
this.icon = bitmap;
this.title = title;
}
}
public class PhotoAdapter extends ArrayAdapter<Photo> {
Context context;
int layoutResourceId;
ArrayList<Photo> data = null;
public PhotoAdapter(Context context, int layoutResourceId, ArrayList<Photo> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
PhotoHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new PhotoHolder();
holder.imgIcon = (ImageView) row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView) row.findViewById(R.id.txtTitle);
holder.del_but = (ImageView) row.findViewById(R.id.imgDel);
row.setTag(holder);
} else {
holder = (PhotoHolder) row.getTag();
}
Photo photo = data.get(position) ;
holder.txtTitle.setText(photo.title);
holder.imgIcon.setImageBitmap(photo.icon);
return row;
}
}
Photo holder class:
static class PhotoHolder {
ImageView imgIcon;
TextView txtTitle;
ImageView del_but;
}
This code in onCrete method :
ArrayList<Photo> photo_data = new ArrayList<Photo>();
adapter = new PhotoAdapter(this, R.layout.photos_list_item, photo_data);
listView1 = (ListView) findViewById(R.id.listView1);
listView1.setAdapter(adapter);
method which starts after photo is taken;
private void setPic() {
int targetW = 220;
int targetH = 300;
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW / targetW, photoH / targetH);
}
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
System.out.println("bitmap " + bitmap);
Photo li = new Photo(bitmap, "haha");
adapter.addAll(li);
}
also i came up with a question. how may i get images from listview?
i dont really understand how getView is working

Grid view crashe the app on scrolling on too many images

in my project that uses custom adapter with grid view , when my grid view load many Items that contain images on scrolling my activity crashes and reloads again. it had some resource problem on loading image that i solved with help of #Raghunandan
my error is out of memmory. cause i think loadfull size images.
public class MyAdapter extends ArrayAdapter<StructureCase> {
private LayoutInflater mInflater = null;
public Context context;
public Class distinationActivity = null;
public MyAdapter(Context context, int textViewResourceId, List<StructureCase> objects) {
super(context, textViewResourceId, objects);
mInflater = LayoutInflater.from(context);
// mInflater = (LayoutInflater)G.currentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder {
public ImageView gem_img = null;
public TextView gem_name = null;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final View v;
final StructureCase item = getItem(position);
if (convertView == null) {
convertView = this.mInflater.inflate(R.layout.my_grid_list, null);
//mInflater = (LayoutInflater)G.currentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.my_grid_list, parent, false);
viewHolder = new ViewHolder();
convertView.setTag(viewHolder);
viewHolder.gem_img = (ImageView) convertView.findViewById(R.id.imageView_mygrid_list);
viewHolder.gem_name = (TextView) convertView.findViewById(R.id.textView_mygrid_list);
viewHolder.gem_name.setTypeface(G.typeFacePrs);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
int temp = 0;
viewHolder.gem_name.setText(item.g_name);
int id = G.currentActivity.getResources().getIdentifier(item.g_image, "drawable", G.currentActivity.getPackageName());
Drawable drawable = G.currentActivity.getResources().getDrawable(id);
if(drawable != null){
viewHolder.gem_img.setImageDrawable(drawable);
}else{
viewHolder.gem_img.setImageResource(R.drawable.almas);
}
//viewHolder.newsThumb.setImageResource(temp);
viewHolder.gem_img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
return convertView;
}
#Override
public long getItemId(int position) {
return position;
}
Use this code to in your getview method while setting bitmap in ImageView.
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException
{
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(
getContentResolver().openInputStream(selectedImage), null, o);
final int REQUIRED_SIZE = 800;
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;`enter code here`
return BitmapFactory.decodeStream(
getContentResolver().openInputStream(selectedImage), null, o2);
}

Categories

Resources