Hi I created a media player. It displays the number of video thumbnails. If I click any video thumbnail, the video will play, at the same time /mnt/sdcard/funny baby.3gb file path name is also displayed at this bottom. I want to hide that. Can someone help me out here?
source code:
package videothumb.videothumb;
//import com.example.android.apis.R;
//import popupTest.popupTest.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.PopupWindow;
//import android.widget.ListView;
//import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.net.Uri;
//import android.view.Window;
//import android.view.WindowManager;
//import android.widget.GridView;
import android.graphics.Color;
//import android.view.MotionEvent;
//import android.view.View.OnTouchListener;
import android.graphics.Canvas;
import android.graphics.Bitmap.Config;
import android.graphics.Shader.TileMode;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.graphics.PorterDuffXfermode;
public class videothumb extends Activity
{
private final static Uri MEDIA_EXTERNAL_CONTENT_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private Gallery _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
//private int video_column_index;
protected Context _context;
//PopupWindow pw = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
_context = getApplicationContext();
setContentView(R.layout.main);
//set GridView for gallery
_gallery = (Gallery) findViewById(R.id.videoGrdVw);
//set default as external/sdcard uri
_contentUri = MEDIA_EXTERNAL_CONTENT_URI;
//initialize the videos uri
//showToast(_contentUri.getPath());
initVideosId();
//set gallery adapter
setGalleryAdapter();
}
private void setGalleryAdapter() {
_gallery.setAdapter(new VideoGalleryAdapter(_context));
_gallery.setOnItemClickListener(videogridlistener);
}
private void initVideosId() {
try
{
//Here we set up a string array of the thumbnail ID column we want to get back
String [] proj={_ID};
// Now we create the cursor pointing to the external thumbnail store
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int count= _cursor.getCount();
System.out.println("total"+_cursor.getCount());
// We now get the column index of the thumbnail id
_columnIndex = _cursor.getColumnIndex(_ID);
//initialize
_videosId = new int[count];
//move position to first element
_cursor.moveToFirst();
for(int i=0;i<count;i++)
{
int id = _cursor.getInt(_columnIndex);
//
_videosId[i]= id;
//
_cursor.moveToNext();
//
}
}catch(Exception ex)
{
showToast(ex.getMessage().toString());
}
}
protected void showToast(String msg)
{
Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
private AdapterView.OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,long id) {
// Now we want to actually get the data location of the file
String [] proj={MEDIA_DATA};
// We request our cursor again
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null);
//System.gc();
// video_column_index = _cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
_columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
// Lets move to the selected item in the cursor
_cursor.moveToPosition(position);
String filename = _cursor.getString(_columnIndex);
Intent intent = new Intent(videothumb.this, ViewVideo.class);
intent.putExtra("videofilename", filename);
startActivity(intent);
showToast(filename);
// Toast.makeText(videothumb.this, "" + position, Toast.LENGTH_SHORT).show();
}
};
private class VideoGalleryAdapter extends BaseAdapter
{
int mGalleryItemBackground;
public VideoGalleryAdapter(Context c)
{
_context = c;
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
mGalleryItemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount()
{
return _videosId.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 imgVw= new ImageView(_context);
try
{
if(convertView!=null)
{
imgVw= (ImageView) convertView;
}
imgVw.setImageBitmap(getImage(_videosId[position]));
imgVw.setAdjustViewBounds(true);
//imgVw.setBackgroundColor(Color.WHITE);
imgVw.setLayoutParams(new Gallery.LayoutParams(650, 550));
imgVw.setPadding(1,1,1,1);
imgVw.setScaleType(ImageView.ScaleType.FIT_XY);
}
catch(Exception ex)
{
System.out.println("StartActivity:getView()-1 : ex " + ex.getClass() +", "+ ex.getMessage());
}
return imgVw;
}
// Create the thumbnail on the fly
private Bitmap getImage(int id) {
Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),id, MediaStore.Video.Thumbnails.MICRO_KIND, null);
System.out.println("ff"+MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),id, MediaStore.Video.Thumbnails.MICRO_KIND, null));
return thumb;
}
}
}
Are you sure it is not the line in your code that says:
showToast(filename);
This is displaying a message with the filename
Related
I saw a tutorial on youtube showing how you can add data to sqlLite db and then display these data to a ListView Video.
After doing that... I applied DragSortListView to my listview... but everytime I drag a row. This error keeps on coming and I couldn't solve it :
FATAL EXCEPTION: main
Process: com.example.justi.ricksonbar, PID: 29157
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.example.justi.ricksonbar.ProductAdapter.getItem(ProductAdapter.java:49)
at com.example.justi.ricksonbar.BackgroundTask$1.drop(BackgroundTask.java:91)
at com.mobeta.android.dslv.DragSortListView.dropFloatView(DragSortListView.java:1501)
at com.mobeta.android.dslv.DragSortListView.access$1200(DragSortListView.java:59)
at com.mobeta.android.dslv.DragSortListView$DropAnimator.onStop(DragSortListView.java:1293)
at com.mobeta.android.dslv.DragSortListView$SmoothAnimator.run(DragSortListView.java:1192)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Here's my ProductAdapter.java¨
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ProductAdapter extends ArrayAdapter{
List list = new ArrayList();
public ProductAdapter(Context context,int resource) {
super(context, resource);
}
public void add(Product object) {
list.add(object);
super.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ProductHolder productHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.product_list, parent, false);
productHolder = new ProductHolder();
productHolder.tx_name = (TextView)row.findViewById(R.id.tvProd_name);
productHolder.tx_price = (TextView)row.findViewById(R.id.tvProd_price);
productHolder.tx_type = (TextView)row.findViewById(R.id.tvProd_type);
row.setTag(productHolder);
}else{
productHolder = (ProductHolder) row.getTag();
}
Product product = (Product) getItem(position);
productHolder.tx_name.setText(product.getName().toString());
productHolder.tx_price.setText(Double.toString(product.getPrice()));
productHolder.tx_type.setText(product.getType().toString());
return row;
}
static class ProductHolder{
TextView tx_name, tx_price, tx_type;
}
}
and my BackgroundTask.java (where I put DragSortListView methods)
import android.app.Activity;
import android.app.VoiceInteractor;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
public class BackgroundTask extends AsyncTask<String, Product, String> {
Context ctx;
ProductAdapter productAdapter;
Activity activity;
DragSortListView listView;
BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
DatabaseHelper dHelper = new DatabaseHelper(ctx);
if (method.equals("add_info")){
String name = params[1];
double price = Double.parseDouble(params[2]);
String type = params[3];
SQLiteDatabase db = dHelper.getWritableDatabase();
//Call method of insertion
dHelper.addInformations(db, name, price, type);
return "One row is inserted....";
}else if (method.equals("get_info")){
listView = (DragSortListView)activity.findViewById(R.id.display_listview);
SQLiteDatabase db = dHelper.getReadableDatabase();
Cursor cursor = dHelper.getInformations(db);
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
String name, type;
double price;
while (cursor.moveToNext()){
name = cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.NAME));
price = cursor.getDouble(cursor.getColumnIndex(ProductContract.ProductEntry.PRICE));
type = cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.TYPE));
Product product = new Product(name, price, type);
publishProgress(product);
}
return "get_info";
}
return null;
}
#Override
protected void onProgressUpdate(Product... values) {
productAdapter.add(values[0]);
}
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener()
{
#Override
public void drop(int from, int to)
{
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
if (from != to)
{
Object item = productAdapter.getItem(from);
productAdapter.remove(item);
productAdapter.insert(item, to);
}
}
};
private DragSortListView.RemoveListener onRemove = new DragSortListView.RemoveListener()
{
#Override
public void remove(int which)
{
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
productAdapter.remove(productAdapter.getItem(which));
}
};
#Override
protected void onPostExecute(String result) {
if (result.equals("get_info")){
listView.setAdapter(productAdapter);
listView.setDropListener(onDrop);
listView.setRemoveListener(onRemove);
DragSortController controller = new DragSortController(listView);
controller.setRemoveEnabled(false);
controller.setSortEnabled(true);
controller.setDragInitMode(1);
listView.setFloatViewManager(controller);
listView.setOnTouchListener(controller);
listView.setDragEnabled(true);
}else{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
}
Please help me. Thank you so much
You are trying to fetch item before adding any element in a adapter.
#Override
public void drop(int from, int to)
{ // Adapter is Created here
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
if (from != to)
{
// here you are trying to get item which must throw indexoutofbounds
// because you didn't added anything yet
Object item = productAdapter.getItem(from);
productAdapter.remove(item);
productAdapter.insert(item, to);
}
}
According to your add method of your adapter will add elements in Adapter.
public void add(Product object) {
list.add(object);
super.add(object);
}
Use Cursor Adapter, it is more efficient:
https://guides.codepath.com/android/Populating-a-ListView-with-a-CursorAdapter
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want my android video gallery to get videos from a specific folder, for example sdcard/phd.
here is my code
package com.example;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class Main extends Activity implements OnItemClickListener {
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) this.findViewById(R.id.ListView);
String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,
MediaStore.Video.Thumbnails.VIDEO_ID };
String[] mediaColumns = { MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA, MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.MIME_TYPE };
cursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
mediaColumns, null, null, null);
ArrayList<VideoViewInfo> videoRows = new ArrayList<VideoViewInfo>();
if (cursor.moveToFirst()) {
do {
VideoViewInfo newVVI = new VideoViewInfo();
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media._ID));
Cursor thumbCursor = managedQuery(
MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID
+ "=" + id, null, null);
if (thumbCursor.moveToFirst()) {
newVVI.thumbPath = thumbCursor.getString(thumbCursor
.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
Log.v("", newVVI.thumbPath);
}
newVVI.filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
newVVI.title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
Log.v("", newVVI.title);
newVVI.mimeType = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
Log.v("", newVVI.mimeType);
videoRows.add(newVVI);
} while (cursor.moveToNext());
}
listView.setAdapter(new VideoGalleryAdapter(this, videoRows));
listView.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
if (cursor.moveToPosition(position)) {
int fileColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
int mimeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE);
String videoFilePath = cursor.getString(fileColumn);
String mimeType = cursor.getString(mimeColumn);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File newFile = new File(videoFilePath);
intent.setDataAndType(Uri.fromFile(newFile), mimeType);
startActivity(intent);
}
}
}
class VideoViewInfo {
String filePath;
String mimeType;
String thumbPath;
String title;
}
class VideoGalleryAdapter extends BaseAdapter {
private Context context;
private List<VideoViewInfo> videoItems;
LayoutInflater inflater;
public VideoGalleryAdapter(Context _context,
ArrayList<VideoViewInfo> _items) {
context = _context;
videoItems = _items;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return videoItems.size();
}
public Object getItem(int position) {
return videoItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View videoRow = inflater.inflate(R.layout.row, null);
ImageView videoThumb = (ImageView) videoRow
.findViewById(R.id.ImageView);
if (videoItems.get(position).thumbPath != null) {
videoThumb.setImageURI(Uri
.parse(videoItems.get(position).thumbPath));
}
TextView videoTitle = (TextView) videoRow
.findViewById(R.id.TextView);
videoTitle.setText(videoItems.get(position).title);
return videoRow;
}
}
String selection=MediaStore.Video.Media.DATA +" like?";
String[] selectionArgs=new String[]{"%FolderName%"};
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
parameters, selection, selectionArgs, MediaStore.Video.Media.DATE_TAKEN + " DESC");
I seem to have a problem loading images into my gallery from sdcard. I know I am doing something wrong with the code but don't know what. Can anyone please help me.
here is my GalleryActivity.java:
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.content.res.TypedArray;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class GalleryActivity extends Activity {
Cursor cursor;
String[] imageIDs = {MediaStore.Images.Thumbnails._ID};
GalleryActivity(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, imageIDs, null, null, MediaStore.Images.Thumbnails.IMAGE_ID);
cursor = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
{
};
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
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();
}
});
}
public class ImageAdapter extends BaseAdapter
{
Context context;
int itemBackground;
public ImageAdapter(Context c)
{
context = c;
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId (R.styleable.Gallery1_android_galleryItemBackground,0);
a.recycle();
}
public int getCount() {
return imageIDs.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 imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageIDs));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
} else {
imageView = (ImageView) convertView;
}
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
The error is under this bit of code which is to retrieve the images from the cdcard (Is this the correct code for retrieving images from sdcard?)
String[] imageIDs = {MediaStore.Images.Thumbnails._ID};
GalleryActivity(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, imageIDs, null, null, MediaStore.Images.Thumbnails.IMAGE_ID);
cursor = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
Hope anyone can help me?
These code lines have go into a method. You have them written outside any method.
GalleryActivity(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, imageIDs, null, null, MediaStore.Images.Thumbnails.IMAGE_ID);
cursor = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
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.
I have created one gallery application, its working fine. If i run the gallery display all sdcard images.
But how do I get pictures from a specific folder? Do I need to change the query?
Example: wallpapers, images, camera, album, etc.
My source code:
package image.Thumbnails;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class ImageThumbnailsActivity extends Activity {
/** Called when the activity is first created. */
private Cursor imagecursor, actualimagecursor;
private int image_column_index, actual_image_column_index;
GridView imagegrid;
private int count;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init_phone_image_grid();
}
private void init_phone_image_grid() {
String[] img = { MediaStore.Images.Thumbnails._ID };
imagecursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, img, null,
null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
image_column_index = imagecursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
count = imagecursor.getCount();
imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imagegrid.setAdapter(new ImageAdapter(getApplicationContext()));
imagegrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v,
int position, long id) {
System.gc();
String[] proj = { MediaStore.Images.Media.DATA };
actualimagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
null, null, null);
actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToPosition(position);
String i = actualimagecursor.getString(actual_image_column_index);
System.gc();
Intent intent = new Intent(getApplicationContext(),
ViewImage.class);
intent.putExtra("filename", i);
startActivity(intent);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position,View convertView,ViewGroup parent) {
System.gc();
ImageView i = new ImageView(mContext.getApplicationContext());
if (convertView == null) {
imagecursor.moveToPosition(position);
int id = imagecursor.getInt(image_column_index);
i.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
+ id));
i.setScaleType(ImageView.ScaleType.CENTER_CROP);
i.setLayoutParams(new GridView.LayoutParams(92, 92));
}
else {
i = (ImageView) convertView;
}
return i;
}
}
}
Here is a link to the source code for the Android Gallery app:
https://android.googlesource.com/platform/packages/apps/Gallery3D
You can use this as an example or a starting point for your app.
try this
How to create a new folder when taking a photo from custom camera application?