this is my gallery program,in which i am displaying the content with static files,how to modify this program to show the photos in the SDcard,if there are no photos or SD card give an alert
package DisplayViewsExample.com;
import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class DisplayViewsExampleActivity extends Activity {
Integer[] imageIDs = {
R.drawable.sample_1,
R.drawable.sample_2,
R.drawable.sample_3
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent,
View v, int position, long id)
{
/* Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();*/
ImageView imageView = (ImageView) findViewById(R.id.image1);
imageView.setImageResource(imageIDs[position]);
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
private int itemBackground;
public ImageAdapter(Context c)
{
context = c;
//---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
//---returns the number of images---
public int getCount() {
return imageIDs.length;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
You should set permission in your Manifest first:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Then, write the function which recursively fetches all your image files from SD:
final static String[] IMAGE_FORMATS = new String[] {
".JPEG", ".GIF", ".PNG", ".BMP"};
public static ArrayList<File> getImageFilesFromSD() {
File dir = Environment.getExternalStorageDirectory();
if (dir == null || !dir.exists())
return null;
ArrayList<File> images = getImageFilesFromDir(dir);
return images;
}
private static ArrayList<File> getImageFilesFromDir(File dir) {
File[] files = dir.listFiles();
ArrayList<File> result = new ArrayList<File>();
if (files != null)
for (File file : files) {
if (file.isDirectory()) {
result.addAll(getImageFilesFromDir(file));
} else {
final String fileName = file.getName();
final String fileNameLwr = fileName.toLowerCase();
// filtering images by extension
boolean contains = false;
for (int i = 0; i < IMAGE_FORMATS.length; i++) {
final String formatLwr = IMAGE_FORMATS[i].toLowerCase();
if (fileNameLwr.endsWith(formatLwr)) {
contains = true;
break;
}
}
if (contains) {
result.add(file);
}
}
}
return result;
}
After that in your list adapter:
imageView.setImageURI(Uri.fromFile(file));
where file is the element of ArrayList returned by getImageFilesFromSD()function.
Good luck.
The
Environment.getExternalStoragePublicDirectory(String type)
function gives you access to the external extorage. There are even contants for the most usual standard folder names.
Don't forget to put the permission to access it on the manifest.
Related
I am trying to figure out a way to use this example in a fragment:
http://sampleprogramz.com/android/browse.php
I have changed the OnCreate method to the OnCreateView method and have tried to correct any of the errors that Android Studio flags but I can't seem to get it working.
Here is the code:
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import static android.app.Activity.RESULT_OK;
public class FilePicker extends ListFragment {
public final static String EXTRA_FILE_PATH = "file_path";
public final static String EXTRA_SHOW_HIDDEN_FILES = "show_hidden_files";
public final static String EXTRA_ACCEPTED_FILE_EXTENSIONS = "accepted_file_extensions";
private final static String DEFAULT_INITIAL_DIRECTORY = "/";
protected File Directory;
protected ArrayList<File> Files;
protected FilePickerListAdapter Adapter;
protected boolean ShowHiddenFiles = false;
protected String[] acceptedFileExtensions;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View emptyView = inflater.inflate(R.layout.empty_view, container, false);
((ViewGroup) getListView().getParent()).addView(emptyView);
getListView().setEmptyView(emptyView);
// Set initial directory
Directory = new File(DEFAULT_INITIAL_DIRECTORY);
// Initialize the ArrayList
Files = new ArrayList<File>();
// Set the ListAdapter
Adapter = new FilePickerListAdapter(getActivity(), Files);
setListAdapter(Adapter);
// Initialize the extensions array to allow any file extensions
acceptedFileExtensions = new String[] {".rc"};
// Get intent extras
if(getActivity().getIntent().hasExtra(EXTRA_FILE_PATH))
Directory = new File(getActivity().getIntent().getStringExtra(EXTRA_FILE_PATH));
if(getActivity().getIntent().hasExtra(EXTRA_SHOW_HIDDEN_FILES))
ShowHiddenFiles = getActivity().getIntent().getBooleanExtra(EXTRA_SHOW_HIDDEN_FILES, false);
if(getActivity().getIntent().hasExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS)) {
ArrayList<String> collection =
getActivity().getIntent().getStringArrayListExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS);
acceptedFileExtensions = (String[])
collection.toArray(new String[collection.size()]);
}
return emptyView;
}
#Override
public void onResume() {
refreshFilesList();
super.onResume();
}
protected void refreshFilesList() {
Files.clear();
ExtensionFilenameFilter filter =
new ExtensionFilenameFilter(acceptedFileExtensions);
File[] files = Directory.listFiles(filter);
if(files != null && files.length > 0) {
for(File f : files) {
if(f.isHidden() && !ShowHiddenFiles) {
continue;
}
Files.add(f);
}
Collections.sort(Files, new FileComparator());
}
Adapter.notifyDataSetChanged();
}
public void onListItemClick(ListView l, View v, int position, long id) {
File newFile = (File)l.getItemAtPosition(position);
if(newFile.isFile()) {
Intent extra = new Intent();
extra.putExtra(EXTRA_FILE_PATH, newFile.getAbsolutePath());
getActivity().setResult(RESULT_OK, extra);
getActivity().finish();
}
else {
Directory = newFile;
refreshFilesList();
}
super.onListItemClick(l, v, position, id);
}
private class FilePickerListAdapter extends ArrayAdapter<File> {
private List<File> mObjects;
public FilePickerListAdapter(Context context, List<File> objects) {
super(context, R.layout.list_item, android.R.id.text1, objects);
mObjects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item, parent, false);
}
else
row = convertView;
File object = mObjects.get(position);
ImageView imageView = (ImageView)row.findViewById(R.id.file_picker_image);
TextView textView = (TextView)row.findViewById(R.id.file_picker_text);
textView.setSingleLine(true);
textView.setText(object.getName());
if(object.isFile())
imageView.setImageResource(R.drawable.sound);
else
imageView.setImageResource(R.drawable.folder);
return row;
}
}
private class FileComparator implements Comparator<File> {
public int compare(File f1, File f2) {
if(f1 == f2)
return 0;
if(f1.isDirectory() && f2.isFile())
// Show directories above files
return -1;
if(f1.isFile() && f2.isDirectory())
// Show files below directories
return 1;
// Sort the directories alphabetically
return f1.getName().compareToIgnoreCase(f2.getName());
}
}
private class ExtensionFilenameFilter implements FilenameFilter {
private String[] Extensions;
public ExtensionFilenameFilter(String[] extensions) {
super();
Extensions = extensions;
}
public boolean accept(File dir, String filename) {
if(new File(dir, filename).isDirectory()) {
// Accept all directory names
return true;
}
if(Extensions != null && Extensions.length > 0) {
for(int i = 0; i < Extensions.length; i++) {
if(filename.endsWith(Extensions[i])) {
// The filename ends with the extension
return true;
}
}
// The filename did not match any of the extensions
return false;
}
// No extensions has been set. Accept all file extensions.
return true;
}
}
}
Thanks.
I was able to get it working by inflating a new xml layout for the filepicker fragment,
I replaced:
View emptyView = inflater.inflate(R.layout.empty_view, container, false);
((ViewGroup) getListView().getParent()).addView(emptyView);
getListView().setEmptyView(emptyView);
// Set initial directory
Directory = new File(DEFAULT_INITIAL_DIRECTORY);
// Initialize the ArrayList
Files = new ArrayList<File>();
// Set the ListAdapter
Adapter = new FilePickerListAdapter(getActivity(), Files);
setListAdapter(Adapter);
With:
View viewlist = inflater.inflate(R.layout.file_picker, container, false);
lv = (ListView) viewlist.findViewById(R.id.filebrowselist);
// Set initial directory
Directory = new File(String.valueOf(DEFAULT_INITIAL_DIRECTORY));
// Initialize the ArrayList
Files = new ArrayList<File>();
// Set the ListAdapter
Adapter = new FilePickerListAdapter(getActivity(), Files);
lv.setAdapter(Adapter);
In my app i want to get the Images from SD card to a specific position and i need to display in gallery,
The code i used is attaching
private Gallery gallery;
private ImageView imgView;
int position;
private byte[] data = { };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
try{
String filepath = "/sdcard/data/Crak/";
File imagefile = new File(filepath +"abcd.jpg" );
FileInputStream fis = new FileInputStream(imagefile);
Bitmap bi = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
System.out.println("cnvrtn");
}
catch(Exception e) {
e.printStackTrace();
}
final Bitmap bitmapimage = BitmapFactory.decodeByteArray(data, 0, data.length);
position = 0;
imgView = (ImageView) findViewById(R.id.ImageView01);
imgView.setImageBitmap(bitmapimage);
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
imgView.setImageBitmap(bitmapimage);
DisplayImage.this.position = position;
}
});
System.out.println("Enter the activity//////////");
imgView.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View paramView) {
// TODO Auto-generated method stub
}
});
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
#SuppressWarnings("null")
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(
R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView = new ImageView(cont);
final Bitmap bitmapimage = BitmapFactory.decodeByteArray(data, 0, data.length);
imgView.setImageBitmap(bitmapimage);;
imgView.setLayoutParams(new Gallery.LayoutParams(100, 100));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
The problems are
1)How can i get all image in the specific folder in SD card
2) GalleryView is indefiniite or a long one without end
here is the UPDATED code to get images from specific path...
package com.example.gall;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.example.gall.R;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class gall extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this, ReadSDCard()));
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
}
});
}
private List<String> ReadSDCard()
{
List<String> tFileList = new ArrayList<String>();
//It have to be matched with the directory in SDCard
File f = new File("/android/sdcard2/");
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
/*It's assumed that all file in the path are in supported type*/
tFileList.add(file.getPath());
}
return tFileList;
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private List<String> FileList;
public ImageAdapter(Context c, List<String> fList) {
mContext = c;
FileList = fList;
TypedArray a = obtainStyledAttributes(R.styleable.gall);
mGalleryItemBackground = a.getResourceId(
R.styleable.gall_android_galleryItemBackground,0);
a.recycle();
}
public int getCount() {
return FileList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView,
ViewGroup parent) {
ImageView i = new ImageView(mContext);
Bitmap bm = BitmapFactory.decodeFile(
FileList.get(position).toString());
i.setImageBitmap(bm);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
public TypedArray obtainStyledAttributes(int theme) {
// TODO Auto-generated method stub
return null;
}
}
Getting all the images will cause a memory overflow the best way is to keep a list of paths in string form and supply that to the gallery. If you are making a custom gallery you will have to create bitmaps and garbage collect them.
This is a good way to access sd-card:
String path = Environment.getExternalStorageDirectory().getPath()+ "/yourFolder/"
This is how to get the list
File directory = new File(path);
if(directory.isDirectory)
{
if(directory.list().length > 0 /*&& check if its an img etc*/)
{
for(String s: directory.list())
{
Log.d(TAG, "adding " + s);
fileNames.add(s);
}
}
}
you should make sure to check sd-card is loaded
//YOUR CODE HERE...
String[] projection = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA, // add DATA column
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN,
MediaStore.Images.Media.TITLE,
};
// Get the base URI for the People table in the Contacts content provider.
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Log.i("URI", images.toString());
// Make the query.
Cursor cur = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
MediaStore.Images.Thumbnails.IMAGE_ID // Ordering
);
Log.i("ListingImages"," query count="+cur.getCount());
if (cur.moveToFirst()) {
String bucket;
String date;
String name;
int bucketColumn = cur.getColumnIndex(
MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int dateColumn = cur.getColumnIndex(
MediaStore.Images.Media.DATE_TAKEN);
int nameColumn = cur.getColumnIndex(
MediaStore.Images.Media.TITLE);
// Get the field values
bucket = cur.getString(bucketColumn);
date = cur.getString(dateColumn);
name = cur.getString(nameColumn);
int columnIndex = cur.getColumnIndex(MediaStore.Images.Media.DATA);
String picPath = cur.getString(columnIndex);
imageView.setImageBitmap(BitmapFactory.decodeFile(picPath));
// Do something with the values.
Log.i("ListingImages", " bucket=" + bucket
+ " name_taken=" + name);
}
}
The code contains a gallery with one button (which has to be added into your manifest file), I just need a suggestion on the button action; what to put inside "imageIDs* or bitmap to reference to the image which previously is clicked and shown.
Here is the complete code:
package net.keivan.gallery;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class GalleryActivity extends Activity {
//---the images to display---
Integer[] imageIDs = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6,
R.drawable.pic8,
R.drawable.pic9,
R.drawable.pic10,
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
//---Displays the name of images as just as i click on them---
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
//---display the images selected---
ImageView imageView = (ImageView) findViewById(R.id.image1);
imageView.setImageResource(imageIDs[position]);
}
});
}
//---Set Wallpaper button---
public void onClick(View v) {
try {
/*at this part can you suggest what to put inside "imageIDs* or *bitmap* to reference
to the image which previously is clicked and shown*/
/* first.the activity is created second.the image which i clicked is shown third.whin
the user click on the button the image which previously is clicked on is set as background.*/
WallpaperManager.getInstance(this).setResource(imageIDs[position]);
//WallpaperManager.getInstance(this).setBitmap(mBitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
///////////////////////////////////////////////
public class ImageAdapter extends BaseAdapter
{
Context context;
int itemBackground;
public ImageAdapter(Context c)
{
context = c;
//---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
{ getApplicationContext().getWallpaper(); }
//---returns the number of images---
public int getCount() {
return imageIDs.length;
}
//---returns the item---
public Object getItem(int position) {
return position;
}
//---returns the ID of an item---
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
} else {
imageView = (ImageView) convertView;
}
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
try {
// Set background from a resource
WallpaperManager.getInstance(this).setResource(imageIDs[position]);
// or set background from a bitmap
//WallpaperManager.getInstance(this).setBitmap(mBitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In your manifest file:
<uses-permission android:name="android.permission.SET_WALLPAPER"></uses-permission>
I have an activity, where in i display list of media files i.e Video, Audio, Images and Animations. On clicking the list item, (as of now Images), the activity must display all the images in the local assets folder in grid View. To do so, i use a single adapter and have a switch case in my getView() function. Depending on the options that is set in the constructor, the switch cases would execute. It works fine for the ListView display, but i am unable to display list of images in grid View. Any help would be apprecaited. Thanks in advance. Here is my code:
package com.bookshelf;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MediaGalaryListActivity extends Activity implements
OnItemClickListener {
private ArrayList<String> mGalary = new ArrayList<String>();
private Bitmap mBitArray[];
private Gallery mMediaGallery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mediagalary);
mGalary.add("Videos");
mGalary.add("Audios");
mGalary.add("Images");
mGalary.add("Animation");
ListView lv = (ListView) findViewById(R.id.mediaGal);
mMediaGallery = (Gallery) findViewById(R.id.mediaGallery);
lv.setAdapter(new MediaGalaryAdapter(this, mGalary, 1));
lv.setOnItemClickListener(this);
}
class MediaGalaryAdapter extends BaseAdapter {
private ArrayList<String> mGal = new ArrayList<String>();
private Bitmap[] mImgArray;
private Context context;
private LayoutInflater mInflate;
private int mAdapterOpt;
public MediaGalaryAdapter(Context ctx, ArrayList<String> gal,
int adapOpt) {
context = ctx;
mGal = gal;
mAdapterOpt = adapOpt;
mInflate = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public MediaGalaryAdapter(Context ctx, Bitmap[] imgArray, int adapOpt) {
context = ctx;
mImgArray = imgArray;
mInflate = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mAdapterOpt = adapOpt;
}
public int getCount() {
int size = 0;
switch (mAdapterOpt) {
case 1:
size = mGal.size();
break;
case 2:
size = mImgArray.length;
break;
}
return size;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
switch (mAdapterOpt) {
case 1:
convertView = mInflate.inflate(R.layout.medialayout, null);
TextView tv = (TextView) convertView.findViewById(R.id.text);
tv.setText(mGal.get(position));
break;
case 2:
ImageView imgView;
convertView = mInflate.inflate(R.layout.image_gallery, null);
imgView = new ImageView(context);
imgView.setImageBitmap(mImgArray[position]);
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setLayoutParams(new GridView.LayoutParams(100, 100));
imgView.setPadding(8, 8, 8, 8);
break;
}
return convertView;
}
}
// For filtering the filename with extensions
class FileNamFilter implements FilenameFilter {
private String mFileExtn;
public FileNamFilter(String extn) {
mFileExtn = "." + extn;
}
public boolean accept(File dir, String filename) {
return filename.endsWith(mFileExtn);
}
}
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
String mediaType = mGalary.get(pos);
String list[] = null;
AssetManager assetManager = getAssets();
try {
list = assetManager.list("Immersive");
mBitArray = new Bitmap[list.length];
System.out.println("Length of list ="+list.length);
for (int i = 0, idx = 0; i < list.length; i++)
{
if (list[i].endsWith(".png") || list[i].endsWith(".gif")
|| list[i].endsWith(".jpeg")
|| list[i].endsWith(".jpg"))
{
mBitArray[idx++] = BitmapFactory.decodeStream(assetManager
.open("Immersive/" + list[i]));
System.out.println("Image at position "+i+" is "+list[i]);
}
;
}
mMediaGallery
.setAdapter(new MediaGalaryAdapter(this, mBitArray, 2));
} catch (IOException e) {
e.printStackTrace();
}
AlertDialog.Builder build = new AlertDialog.Builder(this);
build.setTitle("InProgress....");
// build.setIcon(android.R.drawable.)
build.setMessage(mediaType + " is Inprogress...");
build.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// finish();
}
});
AlertDialog alert = build.create();
alert.show();
// Toast.makeText(getApplicationContext(), mediaType, 30).show();
}
class MediaGalary {
private ImageView mImage;
private TextView mName;
public MediaGalary(ImageView img, TextView strName) {
mImage = img;
mName = strName;
}
public ImageView getmImage() {
return mImage;
}
public void setmImage(ImageView mImage) {
this.mImage = mImage;
}
public TextView getmName() {
return mName;
}
public void setmName(TextView mName) {
this.mName = mName;
}
}
}
each application in the device will be allocated some amount of memory by the DVM. you are getting out of memory error becoz your application is exceeding the memory the allocated by dvm to ur application. for example in froyo, memory allocated for an application is 16Mb. if your application exceeding more than 16Mb, you will get out of memory error. The solution for this is you have to compress the images you are using in your application, and you have to clear all the collection you are using. try clearing all collection you are using once there job is done. you can check how much memory has been consumed by your application in ddms using heap tool. hope this will be helpfull for you.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to create a project in which I need my application to read locally store pdf, doc, xls files.
I don't have any idea on how to do it. I want to show all that locally stored files in my webview. Is there any library to render this files or any other way to do it? If any one can guide me on it than it will be my pleasure.
package com.cdn.file;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FileExplorerActivity extends Activity {
/** Called when the activity is first created. */
private Button buttonList, buttonBack;
// Stores names of traversed directories
ArrayList<String> str = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
private static final String TAG = "F_PATH";
private List<Item> fileList;
private Item item;
private File path = new File(Environment.getExternalStorageDirectory() + "");
private String chosenFile = "";
ListView listViewDir;
ListAdapter adapter;
ListFile listFileAdaptor;
int value = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listViewDir = (ListView) findViewById(R.id.listViewDir);
buttonBack = (Button) findViewById(R.id.buttonBack);
buttonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttonList = (Button) findViewById(R.id.buttonList);
buttonList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isSdPresent()) {
Toast.makeText(FileExplorerActivity.this, "Un Mounted",
Toast.LENGTH_SHORT).show();
loadFileList();
listFileAdaptor = new ListFile(FileExplorerActivity.this,
fileList);
listViewDir.setAdapter(listFileAdaptor);
}
else {
Toast.makeText(FileExplorerActivity.this, "Mounted",
Toast.LENGTH_SHORT).show();
}
}
});
listViewDir.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// if (value == 0) {
chosenFile = fileList.get(position).getFile();
/*} else {
chosenFile = backList.get(position).getFile();
value =0;
}*/
File sel = new File(path + "/" + chosenFile);
Log.v("Prashant111 ==", sel.toString());
Log.v("Prashant222 ==", "" + sel.toURI());
if (sel.isDirectory()) {
// Adds chosen directory to list
str.add(chosenFile);
path = new File(sel + "");
loadFileList();
listFileAdaptor = new ListFile(FileExplorerActivity.this,
fileList);
listViewDir.setAdapter(listFileAdaptor);
// Log.d(TAG, path.getAbsolutePath());
Log.d("Prashant333 ==", "" + path.toURI());
Log.d("Prashant444 ==", "" + path.toString());
}
// Checks if 'up' was clicked
// File picked
else {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(chosenFile));
intent.putExtra(Intent.ACTION_VIEW, uri);
Intent chooser = Intent.createChooser(intent, "Prashant");
startActivity(chooser);
}
}
});
}
public static boolean isSdPresent() {
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
private class Item {
public String file;
public int icon;
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new ArrayList<FileExplorerActivity.Item>();
for (int i = 0; i < fList.length; i++) {
item = new Item();
item.setIcon(R.drawable.file_icon);
item.setFile(fList[i]);
// fileList.add(item);
// Convert into file path
File sel = new File(path, fList[i]);
Log.v("sel ====", sel.toString());
String name = sel.getName();
// Set drawables
if (sel.isDirectory()) {
item.setFile(name);
item.setIcon(R.drawable.directory_icon);
fileList.add(item);
} else {
if (name.endsWith(".mp4") || name.endsWith(".3gp")) {
Log.v("aaaaaaaaaaa", name);
item.setFile(name);
item.setIcon(R.drawable.icon);
fileList.add(item);
} else {
fileList.remove(item);
}
}
}
} else {
Log.e(TAG, "path does not exist");
}
}
class ViewHolder {
TextView textViewName;
ImageView view;
}
class ListFile extends BaseAdapter {
List<Item> fileList;
private LayoutInflater inflator;
Context context;
ListFile(Context context, List<Item> fileList) {
this.fileList = fileList;
this.context = context;
inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return fileList.size();
}
#Override
public Object getItem(int position) {
return fileList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
if (getItemViewType(position) == 0) {
convertView = inflator.inflate(R.layout.file_list, null);
}
holder = new ViewHolder();
holder.textViewName = (TextView) convertView
.findViewById(R.id.textView1);
holder.view = (ImageView) convertView
.findViewById(R.id.imageView1);
convertView.setTag(holder);
// Set the display text
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewName.setText(fileList.get(position).getFile());
holder.view.setImageResource((fileList.get(position).getIcon()));
return convertView;
}
}
}
Try using this code. I am taking video files but you can specify the type of files that you want.