I'm trying without success to add search functionality to my images listview.
Can you help me?
What i have to add to adapter and fragment in order to do it?
My code below:
public class Fragment2 extends SherlockFragment {
DatabaseConnector dbConnector;
private Cursor cursor;
private ListView listView;
private EditText inputSearch;
ImageCursorAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.fragment2, container, false);
dbConnector = new DatabaseConnector(view.getContext());
dbConnector.open();
cursor = dbConnector.getPlaces("");
listView = (ListView)view.findViewById(R.id.lv);
inputSearch = (EditText)view.findViewById(R.id.inputSearch);
adapter = new ImageCursorAdapter(view.getContext(), R.layout.listview_each_item, cursor, new String [] { "title", "description", "picture"}, new int[] { R.id.title, R.id.msg, R.id.pic });
adapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence arg0) {
dbConnector = new DatabaseConnector(view.getContext());
dbConnector.open();
cursor = dbConnector.getPlaces(arg0.toString());
dbConnector.close();
return cursor;
}
});
listView.setTextFilterEnabled(true);
listView.setAdapter(adapter);
dbConnector.close();
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
adapter.getFilter().filter(s.toString());
}
});
return view;
}
}
Asapter:
public class ImageCursorAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
String title;
String desc;
String pic;
#SuppressWarnings("deprecation")
public ImageCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
}
public View getView(int pos, View inView, ViewGroup parent) {
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.listview_each_item, null);
}
this.c.moveToPosition(pos);
title = this.c.getString(this.c.getColumnIndex("title"));
desc = this.c.getString(this.c.getColumnIndex("description"));
pic = this.c.getString(this.c.getColumnIndex("picture"));
ImageView iv = (ImageView) v.findViewById(R.id.icon);
if(pic != "")
{
try {
String file_ = pic.replace("file:///", "");
int size = 30;
File f = new File(file_);
Bitmap bitmap = decodeFile(f,60,80);
iv.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
iv.setImageResource(R.drawable.marker_green72);
}
TextView tv_title = (TextView) v.findViewById(R.id.title);
tv_title.setText(title);
TextView tv_desc = (TextView) v.findViewById(R.id.msg);
tv_desc.setText(desc);
return(v);
}
public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
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 static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
}
I would appreciate an answer that includes repair to my code.
Thank you in advance.
Well if you have an edit text its a whole lot easier , forget the other answers , I've been through the same lot as your through right now .
Firstly , identify the edit text for ex edit text a;
Then add a text watcher to it and carry out the filtering in ontextchanged.
Well, I'm on mobile and its too tough to type so you can just contact me at avrsaditya#gmail.com , give me a chance ill help you , if satisfied choose me as best answer , well I have a lot of sample code
And you might be interested of integrating to your action bar too
Related
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;
}
}
}
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);
}
}
I developed a gallery app with swipe images function (drag to the left/right and a new full screen image is appear).
The problem is that I did not succeed to overcome the small delay of large images until they appear (whatsapp images - no problem, with camera images it is not smooth like in the build-in gallery app).
I tried several method to re size/decode the image but still there is a delay.
My code:
FullScreenImageAdapter.java
public class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
private final int IMAGE_MAX_SIZE = 800;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imgDisplay;
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
false);
imgDisplay = (ImageView) viewLayout.findViewById(R.id.imgDisplay);
Bitmap bitmap = decodeSampledBitmapFromPath(_imagePaths.get(position),1000,1000);
imgDisplay.setImageBitmap(bitmap);
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
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;
}
}
FullScreenViewActivity.java
public class FullScreenViewActivity extends Activity{
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
int selectedFilePosition;
String imageFolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen_view);
//geting the selected image from the intent
/* Getting ImageURI from Gallery from Main Activity */
Uri selectedImgUri = getIntent().getData();
if (selectedImgUri!=null) {
imageFolder = getRealPathFromURI(this, selectedImgUri);
}
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this, getFilePaths(imageFolder));
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(selectedFilePosition);
}
// Reading file paths from SDCard
public ArrayList<String> getFilePaths(String selectedFilePath) {
ArrayList<String> filePaths = new ArrayList<String>();
File file = new File(selectedFilePath);
File directory = file.getParentFile();
// check for directory
if (directory.isDirectory()) {
// getting list of file paths
File[] listFiles = directory.listFiles();
// Check for count
if (listFiles.length > 0) {
// loop through all files
for (int i = 0; i < listFiles.length; i++) {
// get file path
String filePath = listFiles[i].getAbsolutePath();
//set position if this is the required image to show
if (filePath.equals(selectedFilePath)) {
selectedFilePosition = i;
// Add image path to array list
filePaths.add(filePath);
}
}
}
}
return filePaths;
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
To improve performance you need another thread to load it async. Here are the third party libraries (Picasso, Glide) that you can use when working with large images.
I also would use Picasso for loading Images into the ImageView. Picasso caches the Image if it is Loaded once. To preload some elements you can use the Consumner/Producer Pattern! Example here.
I'm new to android and have been working with a tutorial which loads all images from a directory on the SD card. I have the tutorial running but would like to add some code to the click listener which will load a full size version of the thumbnail in the gridview image adapter.
public class PicturesFragment extends Fragment {
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(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(1, 1, 1, 1);
} 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;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.pictures_fragment, container, false);
GridView gridview = (GridView) rootView.findViewById(R.id.gridview);
myImageAdapter = new ImageAdapter(getActivity());
gridview.setAdapter(myImageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/myfilepath/Images";
Toast.makeText(getActivity().getApplicationContext(), targetPath, Toast.LENGTH_LONG)
.show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
myImageAdapter.add(file.getAbsolutePath());
}
gridview.setOnItemClickListener(myOnItemClickListener);
Button camerabtn = (Button) rootView.findViewById(R.id.camerabtn);
camerabtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), CameraActivity.class);
startActivityForResult(intent, 0);
}
});
return rootView;
}
Here's the click listener where I believe I should be implementing the code to solve this problem. I think I should be launching another activity (FullImageActivity.class) which just contains a layout with an imageview and pass the image which has been clicked to this new activity , but I have little know how to go about this
OnItemClickListener myOnItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String prompt = (String) parent.getItemAtPosition(position);
Toast.makeText(getActivity().getApplicationContext(), prompt, Toast.LENGTH_LONG)
.show();
//Intent i = new Intent(getActivity().getApplicationContext(), FullImageActivity.class);
// startActivity(i);
}
};
}
Any help would be greatly appreciated.
Yes, change the onItemClick like this..
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String path = (String) myImageAdapter.getItem(position);
Intent intent = new Intent(this, FullImageActivity.class);
intent.putExtra("IMAGEPATH",path);
startActivity(intent);
}
And in FullImageActivity have a layout to show the full image from the path.
you can get the path in the FullImageActivity onCreate()
public class FullImageActivity extends ActionBarActivity{
#Override
public void onCreate(Bundle bundle){
super.onCreate(bundle);
setContentView(R.layout.image_layout);
String path = getIntent().getStringExtra("IMAGEPATH");
// load the image from the path and set it to the imageview in layout
}
}
I'm new here and new in programming Android. I found this example (below is the example) on a site in internet, It's a great tutorial! What do I want to achieve is when once I clicked a picture on the GridView I want to show the full size of the Image.
public class MainActivity extends Activity {
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 arg0) {
// TODO Auto-generated method stub
return null;
}
#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;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
myImageAdapter = new ImageAdapter(this);
gridview.setAdapter(myImageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/test/";
Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG)
.show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
myImageAdapter.add(file.getAbsolutePath());
}
}
}
Pass the image to the other activity to show it in full view.
To pass the image from Your main Activity. USe following code:
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
ImageView img = ia.getView(position, v, parent);
img.buildDrawingCache();
Bitmap bmap = img.getDrawingCache();
Intent intent = new Intent(HelloGridView.this,
Imageviewer.class);
Bundle bundle = new Bundle();
//bundle.putParcelable("image", bmap);
String par=myimageadpter.getpath(position);
bundle.putParcelable("imagepath", par);
intent.putExtras(bundle);
startActivityForResult(intent, 0);
}
});
In other activity use this code to show the passed image:
Bundle bundle = this.getIntent().getExtras();
bmp=bundle.getParcelable("image");
ImageView img=(ImageView) findViewById(R.id.imageView1);
d =new BitmapDrawable(bmp);
img.setImageBitmap(bmp);
If you pass path. the second activity look like this:
Bundle bundle = this.getIntent().getExtras();
String s=bundle.getParcelable("imagepath");
Bitmap Imagefrompath = BitmapFactory.decodeFile(s);
ImageView img=(ImageView) findViewById(R.id.imageView1);
img.setImageBitmap(Imagefrompath );