Listview click event not working - android

I am displaying images and file names in my list view. With the below code images and file names are populated but I am unable to click items in the listview.The activity just crashes on the click of item in the listview. Please help in figuring out.Thanks
public class ListviewActivity extends Activity
{
public class Data_Adapter extends ArrayAdapter<Data_Class>
{
Context context;
int ResourceLayoutId;
ArrayList<Data_Class> data = null;
public Data_Adapter(Context c, int r, ArrayList<Data_Class> dc)
{
super(c, r, dc);
this.ResourceLayoutId = r;
this.context = c;
this.data = dc;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
DataHolder holder = null;
if (row == null)
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(ResourceLayoutId, parent, false);
holder = new DataHolder();
holder.image = (ImageView) row.findViewById(R.id.image1);
holder.txt = (TextView) row.findViewById(R.id.textlist);
row.setTag(holder);
} else
{
holder = (DataHolder) row.getTag();
}
Data_Class dc = data.get(position);
holder.txt.setText(dc.data);
Bitmap bm = decodeSampledBitmapFromUri(data.get(position).get_path(), 100, 100);
holder.image.setImageBitmap(bm);
return row;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight)
{
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public 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)
{
if (width > height)
{
inSampleSize = Math.round((float) height / (float) reqHeight);
} else
{
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
public class DataHolder
{
ImageView image;
TextView txt;
}
}
private ListView listview1;
private int check_view;
private File targetDirectory;
private File[] files;
protected static ArrayList<Data_Class> dataclass = new ArrayList<Data_Class>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
check_view = 0;
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_layout);
listview1 = (ListView) findViewById(R.id.List1);
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
String targetPath = path + "/MyApp/";
targetDirectory = new File(targetPath);
files = targetDirectory.listFiles();
for (int i = 0; i < files.length; i++)
{
dataclass.add(new Data_Class(files[i].getName(), files[i].getAbsolutePath()));
}
Data_Adapter adapter = new Data_Adapter(this, R.layout.img, dataclass);
listview1.setAdapter(adapter);
listview1.setClickable(true);
// activity crashes when trying clicking item in listview
listview1.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
// TODO Auto-generated method stub
String path = (String) parent.getItemAtPosition(position);
Toast.makeText(ListviewActivity.this, path, Toast.LENGTH_LONG).show();
if(path.contains(".pdf")){
String path2 = path.substring(path.lastIndexOf("/") + 1);
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/" + path2);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent2 = Intent.createChooser(intent, "Open File");
try {
startActivity(intent2);
} catch (ActivityNotFoundException e) {
Toast.makeText(ListviewActivity.this, "No pdf viewer found. Install one. ", Toast.LENGTH_LONG).show();
}
}
}
}
});
}
}
// image.xml which contains imageview and textview
<ImageView
android:id="#+id/image1"
android:layout_width="50dip"
android:layout_height="50dip"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
/>
<TextView
android:id="#+id/textlist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="15dp"
android:textStyle="bold" />
// and main activity.xml
<ListView
android:id="#+id/List1"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>

Your listview contains list of Data_Class not String,which causes crash,So Change
String path = (String) parent.getItemAtPosition(position);
to
Data_Class mData_Class = (Data_Class) parent.getItemAtPosition(position);
String path = mData_Class.Name;
Change Name variable with your Data_Class file name variable.

Related

Loading image in onCreate doesn't fill adapter correctly

My application is able to take pictures and to save and to show them in a list. They also can be deleted and the list is correctly updated.
However, if I close the application and then launch it again, the list is no more correct. In detail:
These are the list elements in the adapter after I take two pictures:
List[0] 20150603_042556
List[1] 20150603_042601
These pictures are correctly saved. However, if I close and open again the application, this is what happens:
Loaded selfie:﹕ 20150603_042556
List[0] 20150603_042556
Loaded selfie: 20150603_042601
List[0] 20150603_042601
List[1] 20150603_042601
This is the add function:
public void add(SelfieRecord listItem) {
list.add(listItem);
for(int k=0;k<list.size();k++)
Log.i("List: ", String.valueOf(k) + " " + list.get(k).getPicName());
notifyDataSetChanged();
}
This is how I load the saved pictures:
for (int ii = 0; ii < dirFiles.length; ii++) {
File file = dirFiles[ii];
String path = file.getAbsolutePath();
selfie.setPic(path);
selfie.setPicName(path.substring(path.indexOf("_") + 1, path.lastIndexOf("_")));
Log.i(TAG+" Loaded selfie: ",path);
mAdapter.add(selfie);
}
Can't figure out what happens.
EDIT: More code follows.
In the main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setup notifications
setNotifications();
mListView = (ListView)findViewById(R.id.selfieList);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, ViewActivity.class);
SelfieRecord record = (SelfieRecord) mAdapter.getItem(position);
intent.putExtra(SELFIE_KEY, record.getPic());
startActivity(intent);
}
});
mAdapter = new SelfieAdapter(getApplicationContext());
mListView.setAdapter(mAdapter);
// load selfies
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && mAdapter.getCount()==0) {
// gets the files in the directory
File fileDirectory = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath());
if (!fileDirectory.exists()) {
fileDirectory.mkdirs();
}
// lists all the files into an array
File[] dirFiles = fileDirectory.listFiles();
if (dirFiles.length != 0) {
SelfieRecord selfie = new SelfieRecord();
// loops through the array of files, outputing the name to console
for (int ii = 0; ii < dirFiles.length; ii++) {
File file = dirFiles[ii];
String path = file.getAbsolutePath();
selfie.setPic(path);
selfie.setPicName(path.substring(path.indexOf("_") + 1, path.lastIndexOf("_")));
Log.i(TAG+" Loaded selfie: ",path);
mAdapter.add(selfie);
}
}
}
registerForContextMenu(mListView);
}
In the Adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View newView = convertView;
ViewHolder holder;
SelfieRecord curr = list.get(position);
Log.i("List: ", String.valueOf(position)+" "+list.get(position).getPicName());
if (null == convertView) {
holder = new ViewHolder();
newView = inflater.inflate(R.layout.list_record, parent, false);
holder.pic = (ImageView) newView.findViewById(R.id.pic);
holder.name = (TextView) newView.findViewById(R.id.pic_name);
newView.setTag(holder);
} else {
holder = (ViewHolder) newView.getTag();
}
//setPic(holder.pic, curr.getPic());
holder.name.setText(curr.getPicName());
mImageView = holder.pic;
new BitmapLoader().execute(curr.getPic());
Log.i("Loader: ", String.valueOf(position) + " " + curr.getPicName());
return newView;
}
static class ViewHolder {
ImageView pic;
TextView name;
}
public void add(SelfieRecord listItem) {
list.add(listItem);
for(int k=0;k<list.size();k++)
Log.i("List: ", String.valueOf(k) + " " + list.get(k).getPicName());
notifyDataSetChanged();
}
public void remove(int position) {
list.remove(position);
notifyDataSetChanged();
}
Bitmap Loader:
public class BitmapLoader extends AsyncTask<String,Integer,Bitmap> {
#Override
protected Bitmap doInBackground(String... resId) {
// Get the dimensions of the View
int targetW = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 160, mContext.getResources().getDisplayMetrics()));
int targetH = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 120, mContext.getResources().getDisplayMetrics()));
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(resId[0], bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int 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(resId[0], bmOptions);
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
I believe the problem is when I put the elements in the adapter after recovered them from storage:
Loaded selfie:﹕ 20150603_042556
List[0] 20150603_042556
Loaded selfie: 20150603_042601
List[0] 20150603_042601
List[1] 20150603_042601
The second call to the adapter's add method overwrite the first element. Why?
Solved by changing the for loop in on Create:
if (dirFiles.length != 0) {
// loops through the array of files, outputing the name to console
for (int ii = 0; ii < dirFiles.length; ii++) {
File file = dirFiles[ii];
String path = file.getAbsolutePath();
SelfieRecord selfie = new SelfieRecord();
selfie.setPic(path);
selfie.setPicName(path.substring(path.indexOf("_") + 1, path.lastIndexOf("_")));
Log.i(TAG+" Loaded selfie: ",path);
mAdapter.add(selfie);
}
}
Must pass a different SelfieRecord Object to the add method.

Using Picasso to solve OutOfMemoryError

I have seen many answers on this issue which has not worked so far for me, the best option I got was using a Picasso to solve this, I have imported the .jar but am getting an error on the code I was told to use, I get an error on this(context) in the following line of code, say (context) cannot be resolved to a variable
Picasso.with(context).load(myBitmap).into(imageView);
This is the lines of code that generates the error, which I intend solving using Picasso
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
This is my full code below
public class WidgetActivity extends Activity {
GridView grid;
Matrix matrix = new Matrix();
Bitmap rotateimage;
ArrayList<HashMap<String, String>> maplist = new ArrayList<HashMap<String,String>>();
LocalStorageHandler notedb;
ImageView iv_notes;
EditText content;
LinearLayout grid_layout;
AppWidgetManager appWidgetManager;
int n;
Intent i;
int s;
String[] tcolor;
public String path = "", name = "", color = "";
public void onCreate(Bundle os) {
super.onCreate(os);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_shownotes);
notedb = new LocalStorageHandler(WidgetActivity.this);
grid = (GridView) findViewById(R.id.grid);
iv_notes = (ImageView) findViewById(R.id.iv_note);
content = (EditText) findViewById(R.id.content);
grid_layout = (LinearLayout) findViewById(R.id.grid_layout);
i = getIntent();
n = i.getIntExtra("currentWidgetId", 1);
new getlist().execute();
}
class getlist extends AsyncTask<String, String, String> {
ArrayList<HashMap<String, String>> maplist = new ArrayList<HashMap<String, String>>();
#Override
public void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg) {
ArrayList<String> filepaths = new ArrayList<String>();
ArrayList<String> filenames = new ArrayList<String>();
Cursor dbCursor = notedb.get();
if (dbCursor.getCount() > 0) {
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())
&& noOfScorer < dbCursor.getCount()) {
noOfScorer++;
try {
HashMap<String, String> items = new HashMap<String, String>();
filepaths.add(Environment.getExternalStorageDirectory()
+ "/360notes/" + dbCursor.getString(2));
filenames.add(dbCursor.getString(3));
items.put("path",
Environment.getExternalStorageDirectory()
+ "/360notes/" + dbCursor.getString(2));
items.put("name", dbCursor.getString(3));
items.put("time", dbCursor.getString(1));
items.put("id", dbCursor.getString(0));
items.put("color", dbCursor.getString(4));
maplist.add(items);
} catch (Exception e) {
e.printStackTrace();
}
dbCursor.moveToNext();
}
}
return null;
}
#Override
protected void onPostExecute(String unused) {
if (maplist.size() > 0) {
grid.setAdapter(new GridViewImageAdapter(WidgetActivity.this,
maplist));
}
}
}
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
ArrayList<String> _filenames = new ArrayList<String>();
private ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
public GridViewImageAdapter(Activity activity,
ArrayList<HashMap<String, String>> items) {
this._activity = activity;
data = items;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater inflate = (LayoutInflater) _activity
.getSystemService(_activity.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.show_image, null);
ImageView imageView = (ImageView) convertView
.findViewById(R.id.imgScreen);
TextView title = (TextView) convertView.findViewById(R.id.title);
try {
String[] tcolor = data.get(position).get("name").split(" / ");
title.setText(tcolor[0].trim());
title.setTextColor(Color.parseColor(tcolor[1].trim()));
if (tcolor[2].trim().equals("0")) {
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("3")) {
// title.setTypeface(null, Typeface.BOLD);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("4")) {
// title.setTypeface(null, Typeface.ITALIC);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("1")) {
// title.setTypeface(null, Typeface.BOLD);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else if (tcolor[2].trim().equals("2")) {
// title.setTypeface(null, Typeface.ITALIC);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else {
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
}
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
// TODO: handle exception
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
/*if (myBitmap != null && !myBitmap.isRecycled()) {
myBitmap.recycle();
myBitmap = null;
}*/
//myBitmap.recycle();
//myBitmap = null;
Picasso.with(context).load(myBitmap).into(imageView);
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
grid.setVisibility(View.GONE);
// grid_layout.setVisibility(View.VISIBLE);
s = position;
path = data.get(position).get("path");
try {
tcolor = data.get(position).get("name").split(" / ");
name = tcolor[0].trim();
color = tcolor[1].trim();
} catch (IndexOutOfBoundsException e) {
name = "";
color = "#000000";
}
appWidgetManager = AppWidgetManager
.getInstance(WidgetActivity.this);
UnreadWidgetProvider.updateWidget(WidgetActivity.this,
appWidgetManager, n, path,
data.get(position).get("name"), color, s);
finish();
}
});
return convertView;
}
}
public void images(String path, String name, String color) {
try {
Bitmap bm;
try {
bm = decodeSampledBitmapFromResource(path);
ExifInterface exifReader = new ExifInterface(path);
int orientation = exifReader.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation == ExifInterface.ORIENTATION_NORMAL) {
matrix.postRotate(360);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
// matrix.postRotate(90);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
// matrix.postRotate(180);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
// matrix.postRotate(270);
} else if (orientation == ExifInterface.ORIENTATION_UNDEFINED) {
// matrix.postRotate(90);
} else {
}
rotateimage = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), matrix, true);
iv_notes.setImageBitmap(rotateimage);
content.setText(name);
content.setFocusable(false);
try {
String[] tcolor = name.split(" / ");
content.setText(tcolor[0].trim());
content.setTextColor(Color.parseColor(tcolor[1].trim()));
if (tcolor[2].trim().equals("0")) {
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("3")) {
// content.setTypeface(null, Typeface.BOLD);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("4")) {
// content.setTypeface(null, Typeface.ITALIC);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("1")) {
// content.setTypeface(null, Typeface.BOLD);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else if (tcolor[2].trim().equals("2")) {
// content.setTypeface(null, Typeface.ITALIC);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else {
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
}
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
grid_layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int i = grid.getCount();
Intent intentAlarm = new Intent(WidgetActivity.this,
WriteNotesActivity.class);
intentAlarm.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
intentAlarm.putExtra("max", s);
startActivity(intentAlarm);
finish();
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
// finish();
}
}
public static Bitmap decodeSampledBitmapFromResource(String resId) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 400, 300);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(resId, options);
}
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;
}
}
This might help someone out there after several hours without an answer to this. I found a way of solving this without using Picasso in handling the outOfMemoryError. I added this line of code in my Manifest file.
android:largeHeap="true"
I added this to the entire application here as below:-
<application
android:icon="#drawable/ic_launcher"
android:largeHeap="true"
android:label="#string/app_name" >
android:largeHeap is the instrument for increasing your allocated memory to app.
EDIT:
well, you are using too much memory. remove those 3 lines of code :
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
simply, you are assigning too much space to these instances and your phone runs out of memory. Just use my response and consider logging the file path so you can possibly use that without creating another file.
i think you used wrong implementation. Probably the context is not adressing correctly and therefore, i would personally use "this" instead. And for loading resources, their guide provides us with three implementations, see below:
pass drawable
Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
pass uri
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
pass file
Picasso.with(context).load(new File(...)).into(imageView3);
so therefore i would decode the image using this code:
Picasso.with(this).load(new File(data.get(position).get("path"))).into(imageView);

How can i add sdcard images to coverflow?

Here is my coverflow with drawables :(
This is my Image Adapter Code
/** The Constant IMAGE_RESOURCE_IDS. */
private static final List<Integer> IMAGE_RESOURCE_IDS = new ArrayList<Integer>(DEFAULT_LIST_SIZE);
/** The Constant DEFAULT_RESOURCE_LIST. */
private static final int[] DEFAULT_RESOURCE_LIST = {
R.drawable.promo_blue_bg_medium,
R.drawable.promo_green_bg_medium,
R.drawable.flow,
R.drawable.promo_yellow_bg_medium,
R.drawable.promo_black_bg_medium ,
};
/** The bitmap map. */
private final Map<Integer, WeakReference<Bitmap>> bitmapMap = new HashMap<Integer, WeakReference<Bitmap>>();
private final Context context;
/**
* Creates the adapter with default set of resource images.
*
* #param context
* context
*/
public ResourceImageAdapter(final Context context) {
super();
this.context = context;
setResources(DEFAULT_RESOURCE_LIST);
}
/**
* Replaces resources with those specified.
*
* #param resourceIds
* array of ids of resources.
*/
public final synchronized void setResources(final int[] resourceIds) {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/CamWay/";
File targetDirector = new File(targetPath);
IMAGE_RESOURCE_IDS.clear();
for (final int resourceId : resourceIds) {
IMAGE_RESOURCE_IDS.add(resourceId);
}
notifyDataSetChanged();
}
/*
* (non-Javadoc)
*
* #see android.widget.Adapter#getCount()
*/
#Override
public synchronized int getCount() {
return IMAGE_RESOURCE_IDS.size();
}
/*
* (non-Javadoc)
*
* #see pl.polidea.coverflow.AbstractCoverFlowImageAdapter#createBitmap(int)
*/
#Override
protected Bitmap createBitmap(final int position) {
Log.v(TAG, "creating item " + position);
final Bitmap bitmap = ((BitmapDrawable) context.getResources().getDrawable(IMAGE_RESOURCE_IDS.get(position)))
.getBitmap();
bitmapMap.put(position, new WeakReference<Bitmap>(bitmap));
return bitmap;
}
}
You see,5 drawable listed above.I wanna load 5 last added images from folder.How can i add sdcard images to that code.
I'm trying to showing 5 last taken photos with coverflow.
I hope somebody can help me.
EDIT(last code):
public class ResourceImageAdapter extends AbstractCoverFlowImageAdapter {
//Dosya alımı başlangıç
public class ImageAdapter extends BaseAdapter {
private Context mContext;
ArrayList<String> itemList = new ArrayList<String>();
public ImageAdapter(Context c) {
mContext = c;
}
void add(String path){
itemList.add(path);
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);
imageView.setImageBitmap(bm);
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public 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) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
}
ImageAdapter myImageAdapter;
//Burası Dosya alımı bitimi
/** The Constant TAG. */
private static final String TAG = ResourceImageAdapter.class.getSimpleName();
/** The Constant DEFAULT_LIST_SIZE. */
private static final int DEFAULT_LIST_SIZE = 20;
/** The Constant IMAGE_RESOURCE_IDS. */
private static final List<Integer> IMAGE_RESOURCE_IDS = new ArrayList<Integer>(DEFAULT_LIST_SIZE);
/** The Constant DEFAULT_RESOURCE_LIST. */
private static final int[] DEFAULT_RESOURCE_LIST = {
R.drawable.promo_blue_bg_medium,
R.drawable.promo_green_bg_medium,
R.drawable.flow,
R.drawable.promo_yellow_bg_medium,
R.drawable.promo_black_bg_medium ,
};
private String[] mFileStrings;
ArrayList<String> f = new ArrayList<String>();
public void getFromSdcard()
{
File file= new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() ,"CamWay");
if (file.isDirectory())
{
File[] listFile = file.listFiles();//get list of filess
mFileStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++)
{
mFileStrings[i] = listFile[i].getAbsolutePath();
f.add(listFile[i].getAbsolutePath());//add path of files to array list
System.out.println("...................................."+mFileStrings[i]);
}
}
}
/** The bitmap map. */
private final Map<Integer, WeakReference<Bitmap>> bitmapMap = new HashMap<Integer, WeakReference<Bitmap>>();
private final Context context;
/**
* Creates the adapter with default set of resource images.
*
* #param context
* context
*/
public ResourceImageAdapter(final Context context) {
super();
this.context = context;
setResources(DEFAULT_RESOURCE_LIST);
}
/**
* Replaces resources with those specified.
*
* #param resourceIds
* array of ids of resources.
*/
public final synchronized void setResources(final int[] resourceIds) {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/CamWay/";
File targetDirector = new File(targetPath);
IMAGE_RESOURCE_IDS.clear();
for (final int resourceId : resourceIds) {
IMAGE_RESOURCE_IDS.add(resourceId);
}
notifyDataSetChanged();
}
/*
* (non-Javadoc)
*
* #see android.widget.Adapter#getCount()
*/
#Override
public synchronized int getCount() {
return IMAGE_RESOURCE_IDS.size();
}
/*
* (non-Javadoc)
*
* #see pl.polidea.coverflow.AbstractCoverFlowImageAdapter#createBitmap(int)
*/
#Override
protected Bitmap createBitmap(final int position) {
Log.v(TAG, "creating item " + position);
final Bitmap bitmap = BitmapFactory.decodeFile(f.get(position));
bitmapMap.put(position, new WeakReference<Bitmap>(bitmap));
return bitmap;
}
}
EDIT 2 :
it starts and then shows 3 items from beginning .when i try look 4+ item ,it stops.
this is code -- getFromSdcard() ; int size= f.size()-5; //get the size of arraylist then decrease it by 5 //then loop from that point to your arraylist size //to get the last 5 items in the list for(int j=size;j<f.size();j++) { System.out.println("Position = "+j); System.out.println("Path of files"+f.get(j)); } final Bitmap bitmap = BitmapFactory.decodeFile(f.get(position)); bitmapMap.put(position, new WeakReference<Bitmap>(bitmap)); return bitmap;
04-06 21:41:05.013: E/AndroidRuntime(11217): at com.project.smyrna.camway.ResourceImageAdapter.createBitmap(ResourceImageAdapter‌​.java:152)
--line is final Bitmap bitmap = BitmapFactory.decodeFile(f.get(position));
private String[] mFileStrings;
ArrayList<String> f = new ArrayList<String>();
public void getFromSdcard()
{
File file= new File(android.os.Environment.getExternalStorageDirectory(),"Your Sdcard");
if (file.isDirectory())
{
listFile = file.listFiles();//get list of files
for (int i = listFile.length-5; i < listFile.length; i++)
{
//get the length decrease it 5 . loop to last
mFileStrings[i] = listFile[i].getAbsolutePath();
f.add(listFile[i].getAbsolutePath());//add path of files to array list
System.out.println("...................................."+mFileStrings[i]);
}
}
}
You can get the path of files under a folder in your sdcard. But make sure the sdcard folder does not have other file formats. Then pass the arraylist to your adapter to display the same in coverflow
To filter files that are .png you can use the below
File dir= new File(android.os.Environment.getExternalStorageDirectory());
Then call
walkdir(dir);
ArrayList<String> filepath= new ArrayList<String>();//contains list of all files ending with
public void walkdir(File dir) {
String Patternpng = ".png";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(Patternpng)){
//Do what ever u want
filepath.add( listFile[i].getAbsolutePath());
}
}
}
}
}
From the comment made i assume you need to display last 5 items from your sdcard folder
int size= f.size()-5;
//get the size of arraylist then decrease it by 5
//then loop from that point to your arraylist size
//to get the last 5 items in the list
for(int j=size;j<f.size();j++)
{
System.out.println("Position = "+j);
System.out.println("Path of files"+f.get(j));
}
Your adapter
public class MyAdapter extends AbstractCoverFlowImageAdapter {
#Override
public int getCount() {
// TODO Auto-generated method stub
return f.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
//inflate layout
//do something
//use the edit 2 to get last 5 items in the arraylist.
ImageView image=(ImageView)vi.findViewById(R.id.ivv);
Bitmap b = BitmapFactory.decodeFile(f.get(position));
image.setImageBitmap(b);
}
}
UPDATE:
Add only last 5 file paths to your arraylist f in getFromSdcard()
Your listview item count is f.size()
To get the paths you can use f.get(position) in getview().
In getFromSdcard()
for (int i = listFile.length-5; i < listFile.length; i++)
// add only last 5 file paths from your folder
In your adapter
#Override
public int getCount() {
// TODO Auto-generated method stub
return f.size();
}
In getView
ImageView image=(ImageView)vi.findViewById(R.id.ivv);
Bitmap b = BitmapFactory.decodeFile(f.get(position));
image.setImageBitmap(b);

Get the LinearLayout inside a ListView from an Async Task onRetainNonConfigurationInstance()

I hope the title is not mis-leading. I am trying to implement onRetainNonConfigurationInstance() of an AsyncTask of loading images and am getting this error "Java.lang.RuntimeException:Unable to retain Activity". Here is my code for onRetainNonConfigurationInstance():
public Object onRetainNonConfigurationInstance(){
//final ListView listview = list;
final int count = list.getChildCount();
final LoadedImage[] mylist = new LoadedImage[count];
for(int i = 0; i < count; i++){
final ImageView v = (ImageView)list.getChildAt(i); // getting error here
mylist[i] = new LoadedImage(((BitmapDrawable) v.getDrawable()).getBitmap());
}
return mylist;
}
Here is the Logcat:
05-18 08:43:15.385: E/AndroidRuntime(28130): java.lang.RuntimeException: Unable to retain activity {com.MyApps.ImageGen/com.MyApps.ImageGen.Wallpapers}: java.lang.ClassCastException: android.widget.LinearLayout
05-18 08:43:15.385: E/AndroidRuntime(28130): at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:2989)
05-18 08:43:15.385: E/AndroidRuntime(28130): at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3100)
05-18 08:43:15.385: E/AndroidRuntime(28130): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3216)
05-18 08:43:15.385: E/AndroidRuntime(28130): at android.app.ActivityThread.access$1600(ActivityThread.java:132)
Here is my layout with the ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000"
android:listSelector="#android:color/transparent" >
</ListView>
</LinearLayout>
Here is how I setup the ListView:
private void setupViews() {
list = (ListView)findViewById(android.R.id.list);
list.setDivider(null);
list.setDividerHeight(0);
imageAdapter = new ImageAdapter(getApplicationContext());
list.setAdapter(imageAdapter);
list.setOnItemClickListener(this);
}
my async task and Item Adapter:
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... params) {
Bitmap bitmap = null;
Bitmap newbitmap = null;
Uri uri = null;
String [] img = {MediaStore.Images.Media._ID};
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, img, null, null, null);
} else {
// cursor = getContentResolver().query(MediaStore.Images.Media.INTERNAL_CONTENT_URI, img, null, null, null);
inInternalStorage = true;
}
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int size = cursor.getCount();
if(size == 0){
//Toast.makeText(getApplicationContext(), "There are no Images on the sdcard", Toast.LENGTH_SHORT).show();
//System.out.println("size equals zero");
Wallpaper.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "There are no Images on the sdcard", Toast.LENGTH_SHORT).show();
}
});
return params;
}else {
}
for(int i = 0; i < size; i++){
cursor.moveToPosition(i);
int ImageId = cursor.getInt(column_index);
if(inInternalStorage == true){
uri = Uri.withAppendedPath(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "" + ImageId);
}else {
uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + ImageId);
}
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
Log.i(TAG, "imageheight = " + imageHeight);
Log.i(TAG, "imagewidth = " + imageWidth);
Log.i(TAG, "imageType = " + imageType);
//options.inSampleSize=4;
options.inSampleSize = calculateInSampleSize(options, imageWidth, imageHeight);
options.inJustDecodeBounds = false;
//bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
if(bitmap != null){
newbitmap = Bitmap.createScaledBitmap(bitmap, 180, 180, true);
bitmap.recycle();
}
if(newbitmap != null){
publishProgress(new LoadedImage(newbitmap));
}
}catch(IOException e){
}
//cursor.close();
}
cursor.close();
return null;
}
#Override
public void onProgressUpdate(LoadedImage... value){
addImage(value);
}
#Override
protected void onPostExecute(Object result) {
setProgressBarIndeterminateVisibility(false);
}
}
private static class LoadedImage {
Bitmap mBitmap;
LoadedImage(Bitmap bitmap) {
mBitmap = bitmap;
}
public Bitmap getBitmap() {
return mBitmap;
}
}
/*Image Adapter to populate grid view of images*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();
public ImageAdapter(Context context){
this.mContext = context;
}
public void addPhotos(LoadedImage photo){
photos.add(photo);
}
#Override
public int getCount() {
return photos.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView image;
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//convertView = inflater.inflate(R.layout.image_list,null);
convertView = inflater.inflate(R.layout.media_view, null);
holder = new ViewHolder();
holder.image = (ImageView)convertView.findViewById(R.id.media_image_id);
//holder.item_name = (TextView)convertView.findViewById(R.id.media_image_id);
convertView.setTag(holder);
} else{
holder = (ViewHolder)convertView.getTag();
}
//holder.image.setLayoutParams(new GridView.LayoutParams(100, 100));
//String item_name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));
holder.image.setImageBitmap(photos.get(position).getBitmap());
//holder.item_name.setText(item_name);
return convertView;
}
}
static class ViewHolder {
ImageView image;
TextView item_name;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = null;
int image_column_index = 0;
String[] proj = {MediaStore.Images.Media.DATA};
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,proj,null, null,null);
}else{
cursor = managedQuery(MediaStore.Images.Media.INTERNAL_CONTENT_URI,proj,null, null,null);
}
cursor.moveToPosition(position);
image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String info = cursor.getString(image_column_index);
Intent imageviewer = new Intent(getApplicationContext(), ViewImage.class);
imageviewer.putExtra("pic_name", info);
startActivity(imageviewer);
cursor.close();
}
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 = 2;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
/*final int REQUIRED_SIZE = 180;
int scale = 1;
if(reqWidth > REQUIRED_SIZE || reqHeight > REQUIRED_SIZE){
scale = (int)Math.pow(2, (int)Math.round(Math.log(REQUIRED_SIZE/(double)Math.max(reqHeight, reqWidth)) / Math.log(0.5)));
}*/
return inSampleSize;
}
other Methods within Async Task:
private void loadImages() {
final Object data = getLastNonConfigurationInstance();
if(data == null){
new LoadImagesFromSDCard().execute();
}else {
final LoadedImage[] photos = (LoadedImage[])data;
if(photos.length == 0){
new LoadImagesFromSDCard().execute();
}
for(LoadedImage photo:photos){
addImage(photo);
}
}
}
private void addImage(LoadedImage... value) {
for(LoadedImage photo: value){
imageAdapter.addPhotos(photo);
imageAdapter.notifyDataSetChanged();
}
}
I am assuming I should first get the root element before I get the ListView from the logcat error, but I don't know how, I can't seem to find a suitable method from the documentation.
P.S: I am using an Activity and not a ListActivity.
The exception tells you that you try to do an invalid cast. My guess is that your row layout isn't a simple ImageView like you assume with the cast in the onRetainNonConfigurationInstance(), instead your row layout probably has a parent Linearlayout that wraps the ImageView(and other views?!). When you call the method getChildAt you get that parent Linearlayout which you try to cast to a ImageView. Instead you should do this:
//...
for(int i = 0; i < count; i++){
LinearLayout parent = (LinearLayout)list.getChildAt(i);
final ImageView v = (ImageView) parent.findViewById(R.id.the_id_of_the_imageview_from_theRow_layout);
mylist[i] = new LoadedImage(((BitmapDrawable) v.getDrawable()).getBitmap());
}
Note: The getChildAt method returns the rows views for the visible rows only so if you try to access the View for a row that isn't currently visible you'll most likely end up with a NullPointerException(you should get the drawables directly from the adapter and not from parsing all the rows Views).
Edit based on the comments:
If I understood your problem, the behavior you see it's normal. You didn't say how you ended up getting the bitmaps in the onRetainNonConfigurationInstance but my guess is that you just save the images from the ListView rows that are currently visible to the user. When it's time to restore the adapter with the images from getLastNonConfigurationInstance() you end up getting only those images which were previously visible. This will get worse if you rotate the phone again as, most likely, there are fewer images visible in landscape orientation then in the portrait orientation.
I don't know if this will work but you could try to modify the LoadedImage class to store the id of the image from MediaStore.Images.Media. When it's time to save the configuration, stop the LoadImagesFromSDCard task and nullify all the images(remove the Bitmap to which LoadedImage points)from the LoadedImages ArrayList(in the adapter) except the ones that are currently visible to the user. Send the photos ArrayList from your adapter through
onRetainNonConfigurationInstance.
When it's time to restore the adapter set the photos ArrayList of your new adapter to the one you got back and put the ListView to the position of the visible images(so the user sees the sent images). In the getView method of your adapter you'll put a default image(like loading...) when you have a null value for the Bitmap in the associated LoadedImage class. Start a new LoadImagesFromSDCard task to get the images and parse them again. When you get the id from MediaStore.Images.Media you'll check if a LoadedImage with this id exists in the adapter and if it has a Bitmap set to it. If it doesn't exist(or it doesn't have a Bitmap associated) then load the image and put it in the adapter, if not the image already exists and move to the next one.
I don't know if the solution above will work or if it's efficient. I would recommend you to modify the code and load images on demand instead of loading all up in a big task.

Show Image View from file path?

I need to show an image by using the file name only, not from the resource id.
ImageView imgView = new ImageView(this);
imgView.setBackgroundResource(R.drawable.img1);
I have the image img1 in the drawable folder. I wish to show that image from the file.
How can I do this?
Labeeb is right about why you need to set image using path if your resources are already laying inside the resource folder ,
This kind of path is needed only when your images are stored in SD-Card .
And try the below code to set Bitmap images from a file stored inside a SD-Card .
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
And include this permission in the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I think you can use this
Bitmap bmImg = BitmapFactory.decodeFile("path of your img1");
imageView.setImageBitmap(bmImg);
You can also use:
File imgFile = new File(“filepath”);
if(imgFile.exists())
{
ImageView myImage = new ImageView(this);
myImage.setImageURI(Uri.fromFile(imgFile));
}
This does the bitmap decoding implicit for you.
All the answers are outdated. It is best to use picasso for such purposes. It has a lot of features including background image processing.
Did I mention it is super easy to use:
Picasso.with(context).load(new File(...)).into(imageView);
String path = Environment.getExternalStorageDirectory()+ "/Images/test.jpg";
File imgFile = new File(path);
if(imgFile.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(myBitmap);
}
From the official site: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
ImageView image = (ImageView) findViewById(R.id.imagePreview);
try {
image.setImageBitmap(decodeSampledBitmap(picFilename));
} catch (Exception e) {
e.printStackTrace();
}
Here the methods:
private 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;
}
private Bitmap decodeSampledBitmap(String pathName,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(pathName, options);
}
//I added this to have a good approximation of the screen size:
private Bitmap decodeSampledBitmap(String pathName) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
return decodeSampledBitmap(pathName, width, height);
}
How To Show Images From Folder path in Android
Very First: Make Sure You Have Add Permissions into Mainfest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
:Make a Class MyGallery
public class MyGallery extends Activity {
private GridView gridView;
private String _location;
private String newFolder = "/IslamicGif/";
private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
private AdView mAdView;
private ArrayList<Bitmap> photo = new ArrayList<Bitmap>();
public static String[] imageFileList;
TextView gallerytxt;
public static ImageAdapter imageAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mygallery);
/*if (MenuClass.mInterstitialAd.isLoaded()) {
MenuClass.mInterstitialAd.show();
}*/
gallerytxt = (TextView) findViewById(R.id.gallerytxt);
/*gallerytxt.setTextSize(20);
int[] color = {Color.YELLOW,Color.WHITE};
float[] position = {0, 1};
Shader.TileMode tile_mode0= Shader.TileMode.REPEAT; // or TileMode.REPEAT;
LinearGradient lin_grad0 = new LinearGradient(0, 0, 0, 200,color,position, tile_mode0);
Shader shader_gradient0 = lin_grad0;
gallerytxt.getPaint().setShader(shader_gradient0);*/
ImageButton btn_back = (ImageButton) findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MyGallery.this.finish();
}
});
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
gridView = (GridView) findViewById(R.id.gridView);
new MyGalleryAsy().execute();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(MyGallery.this, ImageDetail.class);
intent.putExtra("ImgUrl", imageFileList[pos]);
//Toast.makeText(MyGallery.this,"image detail"+pos,Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
protected void onStart() {
super.onStart();
if (ImageDetail.deleted) {
photo = new ArrayList<Bitmap>();
new MyGalleryAsy().execute();
ImageDetail.deleted = false;
}
}
public class MyGalleryAsy extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
Bitmap mBitmap;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MyGallery.this, "", "Loading ...", true);
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
readImage();
return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
DisplayMetrics displayMatrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMatrics);
int screenWidth = displayMatrics.widthPixels / 3;
if (photo.size() > 0) {
imageAdapter = new ImageAdapter(MyGallery.this, screenWidth);
gridView.setAdapter(imageAdapter);
}
}
}
private void readImage() {
// TODO Auto-generated method stub
try {
if (isSdPresent()) {
_location = extStorageDirectory + newFolder;
} else
_location = getFilesDir() + newFolder;
File file1 = new File(_location);
if (file1.isDirectory()) { // sdCard == true
imageFileList = file1.list();
if (imageFileList != null) {
for (int i = 0; i < imageFileList.length; i++) {
try {
photo.add(BitmapFactory.decodeFile(_location + imageFileList[i].trim()));
} catch (Exception e) {
// TODO: handle exception
//Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
}
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean isSdPresent() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
private int width;
private int mGalleryItemBackground;
public ImageAdapter(Context c) {
context = c;
}
public ImageAdapter(Context c, int width) {
context = c;
this.width = width;
}
public int getCount() {
return photo.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflater.inflate(R.layout.galleryadapter, null);
RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.galleryLayout);
ImageView imageView = new ImageView(context);
layout.addView(imageView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.setLayoutParams(new GridView.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
imageView.setImageBitmap(photo.get(position));
return v;
}
public void updateItemList(ArrayList<Bitmap> newItemList) {
photo = newItemList;
notifyDataSetChanged();
}
}
}
Now create its Xml Class
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize">
<TextView
android:id="#+id/gallerytxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:fontFamily="#string/font_fontFamily_medium"
android:text="My Gallery"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/black"
android:textStyle="bold" />
<ImageButton
android:id="#+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/ic_arrow_back_black_24dp" />
</RelativeLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center|bottom"
android:visibility="gone"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_id" />
<GridView
android:id="#+id/gridView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/adView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/relativeLayout"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:smoothScrollbar="true"
android:verticalSpacing="5dp"></GridView>
## Also Make Adapter galleryadapter.xml ##
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="#+id/galleryLayout"
android:padding="2dp">
[![enter image description here][1]][1]
To see the Image in Detail create a new Class ImageDetail:##
public class ImageDetail extends Activity implements OnClickListener {
public static InterstitialAd mInterstitialAd;
private ImageView mainImageView;
private LinearLayout menuTop;
private TableLayout menuBottom;
private Boolean onOff = true;
private ImageView delButton, mailButton, shareButton;
private String imgUrl = null;
private AdView mAdView;
TextView titletxt;
private String newFolder = "/IslamicGif/";
private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
public static boolean deleted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.image_detail);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
mainImageView = (ImageView) findViewById(R.id.mainImageView);
menuTop = (LinearLayout) findViewById(R.id.menuTop);
menuBottom = (TableLayout) findViewById(R.id.menuBottom);
titletxt = (TextView) findViewById(R.id.titletxt);
titletxt.setTextSize(22);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.interstial_id));
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
delButton = (ImageView) findViewById(R.id.delButton);
mailButton = (ImageView) findViewById(R.id.mailButton);
shareButton = (ImageView) findViewById(R.id.shareButton);
Bundle exBundle = getIntent().getExtras();
if (exBundle != null) {
imgUrl = exBundle.getString("ImgUrl");
}
if (isSdPresent()) {
imgUrl = extStorageDirectory + newFolder + imgUrl;
} else
imgUrl = getFilesDir() + newFolder + imgUrl;
if (imgUrl != null) {
GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(mainImageView);
Glide.with(this).load(imgUrl).into(imageViewTarget);
}
delButton.setOnClickListener(this);
mailButton.setOnClickListener(this);
shareButton.setOnClickListener(this);
}
public static boolean isSdPresent() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.shareButton:
Image_Link();
break;
case R.id.delButton:
deleted();
break;
case R.id.mailButton:
sendemail();
break;
default:
break;
}
}
private void sendemail() {
try {
File photo = new File(imgUrl);
Uri imageuri = Uri.fromFile(photo);
String url = Constant.AppUrl;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Face Placer App Available here..Play Link");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
String[] recipients2 = new String[]{"mymail#email.com", "",};
emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
emailIntent2.setType("text/html");
emailIntent2.setType("image/JPEG");
startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
private void Image_Link() {
try {
File photo = new File(imgUrl);
Uri imageuri = Uri.fromFile(photo);
String url = Constant.AppUrl;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Face Placer App Available here..Play Link");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
String[] recipients2 = new String[]{"mymail#email.com", "",};
emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
emailIntent2.setType("text/html");
emailIntent2.putExtra(Intent.EXTRA_TEXT, "Face Placer App Available here..Play Link " + url);
emailIntent2.setType("image/JPEG");
startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
private void deleted() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
AlertDialog.Builder builder = new AlertDialog.Builder(ImageDetail.this);
builder.setTitle(getString(R.string.removeoption));
builder.setMessage(getString(R.string.deleteimage));
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
dialog.cancel();
File fileDel = new File(imgUrl);
boolean isCheck1 = fileDel.delete();
if (isCheck1) {
deleted = true;
finish();
MyGallery.imageAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
dialog.cancel();
}
});
Dialog dialog = builder.create();
dialog.show();
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
.build();
mInterstitialAd.loadAd(adRequest);
}
}
Create its xml image_detail.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg"
android:orientation="vertical">
<ImageView
android:id="#+id/mainImageView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:contentDescription="#string/app_name"
android:focusable="true"
android:focusableInTouchMode="true" />
<LinearLayout
android:id="#+id/adlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:orientation="horizontal"
android:visibility="gone"></LinearLayout>
<LinearLayout
android:id="#+id/menuTop"
android:layout_width="fill_parent"
android:layout_height="56dp"
android:layout_alignWithParentIfMissing="true"
android:layout_below="#+id/adlayout"
android:background="#color/colorPrimary"
android:orientation="vertical"
android:padding="10.0dip"
android:visibility="visible">
<TextView
android:id="#+id/titletxt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Islamic Gifs"
android:textColor="#000000"
android:textSize="22sp"
android:textStyle="bold" />
</LinearLayout>
<TableLayout
android:id="#+id/menuBottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"
android:padding="10.0dip"
android:stretchColumns="*"
android:visibility="visible">
<TableRow>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/mailButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="#drawable/selector_shareimage"
android:contentDescription="#string/app_name" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/shareButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="#drawable/selector_shareimage_small"
android:contentDescription="#string/app_name" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/delButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="#drawable/selector_delete"
android:contentDescription="#string/app_name" />
</LinearLayout>
</TableRow>
</TableLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/menuTop"
android:layout_centerHorizontal="true"
android:visibility="gone"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_id"></com.google.android.gms.ads.AdView>
Add your own Drawable to Selector class,and create it res>drawable>selector_shareimage.xml
<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="#drawable/result_bt_mail" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="#drawable/result_bt_mail" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="#drawable/result_bt_mail" android:state_enabled="true" android:state_selected="true"/>
<item android:drawable="#drawable/result_bt_mail_s"/>
Dont forget to add in application tag for sdk version 29 and 30 to add this line
android:requestLegacyExternalStorage="true"
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
You can use:
ImageView imgView = new ImageView(this);
InputStream is = getClass().getResourceAsStream("/drawable/" + fileName);
imgView.setImageDrawable(Drawable.createFromStream(is, ""));
You may use this to access a specific folder and get particular image
public void Retrieve(String path, String Name)
{
File imageFile = new File(path+Name);
if(imageFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(path+Name);
myImage = (ImageView) findViewById(R.id.savedImage);
myImage.setImageBitmap(myBitmap);
Toast.makeText(SaveImage.this, myBitmap.toString(), Toast.LENGTH_LONG).show();
}
}
And then you can call it by
Retrieve(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images/","Image2.PNG");
Toast.makeText(SaveImage.this, "Saved", Toast.LENGTH_LONG).show();
public static Bitmap decodeFile(String path) {
Bitmap b = null;
File f = new File(path);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int IMAGE_MAX_SIZE = 1024; // maximum dimension limit
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
public static Bitmap showBitmapFromFile(String file_path)
{
try {
File imgFile = new File(file_path);
if(imgFile.exists()){
Bitmap pic_Bitmap = decodeFile(file_path);
return pic_Bitmap;
}
} catch (Exception e) {
MyLog.e("Exception showBitmapFromFile");
return null;
}
return null;
}
if you are using image loading in List view then use Aquery concept .
https://github.com/AshishPsaini/AqueryExample
AQuery aq= new AQuery((Activity) activity, convertView);
//load image from file, down sample to target width of 250 pixels .gi
File file=new File("//pic/path/here/aaaa.jpg");
if(aq!=null)
aq.id(holder.pic_imageview).image(file, 250);
onLoadImage Full load
private void onLoadImage(final String imagePath) {
ImageSize targetSize = new ImageSize(imageView.getWidth(), imageView.getHeight()); // result Bitmap will be fit to this size
//ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleto
com.nostra13.universalimageloader.core.ImageLoader imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));
imageLoader.loadImage(imagePath, targetSize, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(final String imageUri, View view) {
super.onLoadingStarted(imageUri, view);
progress2.setVisibility(View.VISIBLE);
new Handler().post(new Runnable() {
public void run() {
progress2.setColorSchemeResources(android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);
// Picasso.with(getContext()).load(imagePath).into(imageView);
// Picasso.with(getContext()).load(imagePath) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(imageView);
Glide.with(getContext())
.load(imagePath)
.asBitmap()
.into(imageView);
}
});
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (view == null) {
progress2.setVisibility(View.INVISIBLE);
}
// else {
Log.e("onLoadImage", "onLoadingComplete");
// progress2.setVisibility(View.INVISIBLE);
// }
// setLoagingCompileImage();
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason);
if (view == null) {
progress2.setVisibility(View.INVISIBLE);
}
Log.e("onLoadingFailed", imageUri);
Log.e("onLoadingFailed", failReason.toString());
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
super.onLoadingCancelled(imageUri, view);
if (view == null) {
progress2.setVisibility(View.INVISIBLE);
}
Log.e("onLoadImage", "onLoadingCancelled");
}
});
}
private void showImage(ImageView img, String absolutePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmapPicture = BitmapFactory.decodeFile(absolutePath);
img.setImageBitmap(bitmapPicture);
}
Most of the answers are working but no one mentioned that the high resolution image will slow down the app , In my case i used images RecyclerView which was taking 0.9 GB of device memory In Just 30 Images.
I/Choreographer: Skipped 73 frames! The application may be doing too
much work on its main thread.
The solution is Sipmle you can degrade the quality like here : Reduce resolution of Bitmap
But I use Simple way , Glide handles the rest of work
fanContext?.let {
Glide.with(it)
.load(Uri.fromFile(File(item.filePath)))
.into(viewHolder.imagePreview)
}
You can easily do this using bitmap. You can find the code below :
ImageView imageView=findViewById(R.id.imageView);
Bitmap bitMapImage= BitmapFactory.decodeFile("write path of your image");
imageView.setImageBitmap(bitMapImage);
mageView.setImageResource(R.id.img);

Categories

Resources