Video thumbnail return null - android

I am creating thumbnails from videos stored in my sd card ,displaying thumbnails and its names in grid view. On item selected event of the grid view pop ups a dialog and asking x, y, right, bottom positions then pasting it to the main activity . I got the video files, and tried to create thumbnail using media store also am retrieving thumbnail as bitmap, but the bitmap is null. In the grid view video names are shown and i am able to select the corresponding thumbnail and can give positions also am able set the thumbnail to the main activity. The problem is the bitmap is null and bitmap image not showing(text vie video name shown). What's the problem ? I can't figure it out? Plz help me? My code is given below. thanks in advance.
if (f.isFile()) {
if (fName.endsWith(".mpg")
|| fName.endsWith(".mov")
|| fName.endsWith(".wmv")
|| fName.endsWith(".rm")
|| fName.endsWith(".mp4")) {
tv.setText(fName);
path = f.getAbsolutePath();
System.out.println("Video file path=>"+path);
thumb = ThumbnailUtils.createVideoThumbnail(f.getAbsolutePath(),MediaStore.Video.Thumbnails.MICRO_KIND);
if(thumb==null)
{
/**Every time it printing null**/
System.out.println("Thumb is null");
}
iv.setImageBitmap(thumb);

From ThumbnailUtils.createVideoThumbnail documentation: May return null if the video is corrupt or the format is not supported.
By default, almost all supported formats are mp4 and 3gp. See here: http://developer.android.com/guide/appendix/media-formats.html for full list of default-supported media formats.

If you are creating thumbnail from sd card video this would create ThumbnailUtils.createVideoThumbnail otherwise use a cursor.
See this example.

Try this code. It is getting the thumbnail of videos from urls. instead of pass the path of sd card .it will help you . Dont forgot to add internet permission in manifest file.
public class VideoThumbnailActivity extends Activity {
public static final String Downloader = null;
static String uri1="http://daily3gp.com/vids/lucky_guy.3gp";
static String uri2="http://daily3gp.com/vids/reporter_hit_by_plane.3gp";
static String uri3="http://daily3gp.com/vids/motorcycle_wipesout_explodes.3gp";
static String uri4="http://commonsware.com/misc/test2.3gp";
public static String uri_array[]={uri1,uri2,uri3,uri4,uri1,uri2,uri3,uri4,uri1,uri2,uri3,uri4};
ImageView imageView;
String url;
Gallery ga1,ga2;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView)findViewById(R.id.imageView);
ga1 = (Gallery)findViewById(R.id.gallery1);
ga1.setAdapter(new ImageAdapter(getApplicationContext()));
imageView.setImageBitmap(ThumbnailUtils.createVideoThumbnail(uri_array[0], MediaStore.Video.Thumbnails.FULL_SCREEN_KIND));
//on click event on gallery
ga1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, final int position,long arg3) {
imageView.setImageBitmap(ThumbnailUtils.createVideoThumbnail(uri_array[position], MediaStore.Video.Thumbnails.FULL_SCREEN_KIND));
//on click event on imageview to play video
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),PlayActivity.class);
intent.putExtra("path",uri_array[position]);
startActivity(intent);
}
});
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context ctx;
int imageBackground;
public ImageAdapter(Context c) {
ctx = c;
TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();
}
#Override
public int getCount() {
return uri_array.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View view, ViewGroup arg2) {
ImageView iv = new ImageView(ctx);
Bitmap curThumb = null;
curThumb = ThumbnailUtils.createVideoThumbnail(uri_array[position],MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
iv.setImageBitmap(curThumb);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setLayoutParams(new Gallery.LayoutParams(150,120));
iv.setBackgroundResource(imageBackground);
return iv;
}
}
let me know your problem is resolved or not.

Related

Expanding an image from a thumbnail in a GridView

So I have a simple application in which I am taking an image with the camera and then loading the images into a GridView, when I click on the GridView it must open a bigger version of that image. I cannot get the image to open bigger.
The problem is that I have no reference to that image when passing it to the Activity which makes the image bigger. Code is below.
MainActivity.java
protected static final String EXTRA_RES_ID = "POS";
private ArrayList<String> mThumbIdsSelfies = new ArrayList<String>();
if(populateArrayList())
{
GridView gridview = (GridView) findViewById(R.id.gridview);
// Create a new ImageAdapter and set it as the Adapter for this GridView
gridview.setAdapter(new ImageAdapter(this, mThumbIdsSelfies));
// Set an setOnItemClickListener on the GridView
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
//Create an Intent to start the ImageViewActivity
Intent intent = new Intent(MainActivity.this, ImageViewActivity.class);
// Add the ID of the thumbnail to display as an Intent Extra
intent.putExtra(EXTRA_RES_ID, (int) id);
// Start the ImageViewActivity
startActivity(intent);
}
});
}
private boolean populateArrayList()
{
File dir = getAlbumDir();
//Bitmap myBitmap;
if (dir.isDirectory())
{
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++)
{
//myBitmap = BitmapFactory.decodeFile(files[i].toString());
mThumbIdsSelfies.add(files[i].toString());
}
}
return true;
}
ImageViewActivity.java - This is the one that makes the image bigger
public class ImageViewActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get the Intent used to start this Activity
Intent intent = getIntent();
// Make a new ImageView
ImageView imageView = new ImageView(getApplicationContext());
// Get the ID of the image to display and set it as the image for this ImageView
imageView.setImageResource(intent.getIntExtra(MainActivity.EXTRA_RES_ID, 0));
setContentView(imageView);
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter
{
private static final int PADDING = 8;
private static final int WIDTH = 250;
private static final int HEIGHT = 250;
private Context mContext;
private List<String> mThumbIds;
// Store the list of image IDs
public ImageAdapter(Context c, List<String> ids)
{
mContext = c;
this.mThumbIds = ids;
}
// Return the number of items in the Adapter
#Override
public int getCount()
{
return mThumbIds.size();
}
// Return the data item at position
#Override
public Object getItem(int position)
{
return mThumbIds.get(position);
}
// Will get called to provide the ID that
// is passed to OnItemClickListener.onItemClick()
#Override
public long getItemId(int position)
{
return mThumbIds.indexOf(position);
}
// Return an ImageView for each item referenced by the Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView = (ImageView) convertView;
// if convertView's not recycled, initialize some attributes
if (imageView == null)
{
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(WIDTH, HEIGHT));
imageView.setPadding(PADDING, PADDING, PADDING, PADDING);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
//imageView.setImageResource(mThumbIds.get(position));
Bitmap b = BitmapFactory.decodeFile(mThumbIds.get(position));
imageView.setImageBitmap(b);
return imageView;
}
}
So the problem with the above function is that I cannot use getItemId as it does not return a long, rather it returns a string and I have no way of getting something useful from it.
The other thing I have tried is passing the bitmap image as an extra in my bundle and reading it on the other side, still I have no luck in getting the actual image to display.
I finally figured this out, so here is what I did.
MainActivity.java - Changed the following line
intent.putExtra(EXTRA_RES_ID, mThumbIdsSelfies.get(position)/*(int) id*/);
ImageViewActivity.java
String s = intent.getStringExtra(MainActivity.EXTRA_RES_ID);
Bitmap bitmap = BitmapFactory.decodeFile(s);
imageView.setImageBitmap(bitmap);
So those changes finally helped me, all I had to do was pass a string reference to the file location of the thumbnail I just clicked on. Then in the Activity that enlarges that image, I had to get that string reference and generate a bitmap out of it and then set that bitmap to the imageView.
Assuming that mThumbIdsSelfies is an ArrayList of the image paths you can use this:
Intent intent = new Intent(MainActivity.this, ImageViewActivity.class);
intent.putExtra(EXTRA_RES_ID, mThumbIdsSelfies[position]);
startActivity(intent);
Then retrieve it in your Activity(ImageViewActivity) and use it as you do in your adapter's getView() method.

Android: open multiple Text files from gridview

I just started into this Android development thing, by my own, basically reading various books and searching the internet and the forums for the information that i need, but it seems I got to a halt. I am trying to make an application by which the user will be prompted with a list of images in a gridview. Upon clicking an image, the application will sent the user to an activity which will display a, sometimes short, sometimes long, story that is read from a .txt file placed inside the assets folder. I can do it the easy way, ie. making an activity for each .txt that needs to be opened but i'm talking 50+ image files in gridview and 50+ .txt files in assets folder. So I want to do this from only 2 activities, main and +1, or as few as possible. below is the code i got so far.
MainActivity.java
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById (R.id.gridv);
gridview.setAdapter(new ImageAdapter (this));
gridview.setOnItemClickListener (new AdapterView.OnItemClickListener() {
public void onItemClick (AdapterView<?> parent, View v, int position, long id) {
Intent i = new Intent (getApplicationContext(), ChronText.class);
i.putExtra("id", position);
startActivity (i);
}
});
}
}
ChronText.java
public class ChronText extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flowtext);
Intent i = getIntent();
int position = i.getExtras().getInt("id");
TextView chronview = (TextView) findViewById (R.id.chronview);
AssetManager assetManager = getAssets();
InputStream input;
try {
input = assetManager.open("");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
String text = new String (buffer);
chronview.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context myContext;
public Integer[] myThumbsId = {
R.drawable.breathingspace,
R.drawable.particletracks,
R.drawable.welcomeparty,
R.drawable.thebookofemptiness2of2,
R.drawable.uplifted
};
public ImageAdapter (Context c) {
myContext = c;
}
public int getCount() {
return myThumbsId.length;
}
public Object getItem (int position) {
return myThumbsId [position];
}
public long getItemId (int position) {
return 0;
}
public View getView (int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView (myContext);
imageView.setLayoutParams(new GridView.LayoutParams(170,111));
imageView.setImageResource(myThumbsId[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
return imageView;
}
}
The application works, however, I have to manually enter the filename in ChronText.java
InputStream input;
try {
input = assetManager.open("");
so basically, i would need to manually write the filename for each image that is clicked. Is there a way this thing could be done automatically? And if yes, how? The way I am thinking is to make a list containing all the filenames, like the gridview has, that contains the files in the corresponding order of the gridview images, and when the user clicks the image, the activity is created for the file that has the same position in filename list as the image in the gridview list. If there is another, simpler way, please, do tell/explain. If my idea is good, please tell me how to put it 'on paper'. I worked on this app for some weeks now and i'm a bit burned out. Thanks in advance.
After another week or so of head smashing, I have fount the answer and completed the app. I can show the result if anyone wishes to

display the image url in listview

I'm new to android domain..
I'm working with small app..
What i need is ??
I have videos urls and image urls in a array list,which retrive from database as json object and stored in separate array. I want this array list of images should show in listview with text.
How to implement this?? please help me..
I have went through google but still i didn't clear example.. Please any one help me..
Thanks a lot in advance...
public class act extends Activity {
/** Called when the activity is first created. */
static String uri1="http://i3.ytimg.com/vi/bQaWsVQSLdY/default.jpg";
static String uri2="http://i4.ytimg.com/vi/cJQCniWQdno/mqdefault.jpg";
static String uri3="http://i1.ytimg.com/vi/D8dA4pE5hEY/mqdefault.jpg";
public static String[] urls={uri1,uri2,uri3};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView grd=(GridView)findViewById(R.id.gridView1);
grd.setAdapter(new ImageAdapter(this));
grd.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,View v,int pos,long id)
{
Toast.makeText(getBaseContext(),"pic"+(pos+1)+"select ",Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
private int itemBackground;
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 urls.length;
}
public Object getItem(int pos)
{
return pos;
}
public long getItemId(int pos)
{
return pos;
}
public View getView(int pos,View cv,ViewGroup vg)
{
ImageView imageview=new ImageView(context);
imageview.setImageResource(urls[pos]);
imageview.setScaleType(ImageView.ScaleType.FIT_XY);
imageview.setLayoutParams(new Gallery.LayoutParams(150,120));
imageview.setBackgroundResource(itemBackground);
return imageview;
}
}
}
I try like this..i can't able to get the image...
you can't set it directly as you are trying to do, you will first need to download the image,
store the bitmap, and only then apply the image to you ImageView.
check this question:
How to set image button resource from web url in Android?
this solution is good as well:
How to load an ImageView by URL in Android?
If the requirement is of showing the imageview and textview in list row then try the concept of universal loader.
Link:
https://github.com/nostra13/Android-Universal-Image-Loader

Adding default view in listview in android

I'm using a listview in my android application in which the listitems(in my case it is bitmap images) are loaded dynamically. Actually i'm creating the bitmap images and then it is loaded one by one into the list. what i want is to show all the list items with some default image and update them correspondingly when the bitmap image is created. My code is given below,
public class BitmapDemoActivity extends Activity {
HorizontalListView listview;
Vector<Bitmap> thumbImg;
BitmapCreator creator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listviewdemo);
creator=new BitmapCreator();
thumbImg= new Vector<Bitmap>(97);
listview = (HorizontalListView)findViewById(R.id.listview);
listview.setAdapter(new BitmapAdapter());
new AsyncBitmapCreate().execute();
}
private class AsyncBitmapCreate extends AsyncTask<Void, Bitmap, Void>{
//Bitmap[] temp=new Bitmap[44];
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for(int i=0;i<97;i++){
publishProgress(creator.generateBitmap(i+1));
}
return null;
}
#Override
protected void onProgressUpdate(Bitmap... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
new BitmapAdapter().add(values[0]);
new BitmapAdapter().notifyDataSetChanged();
}
}
class BitmapAdapter extends BaseAdapter{
public void add(Bitmap bitmap)
{
Log.w("My adapter","add");
thumbImg.add(bitmap);
}
#Override
public int getCount() {
return thumbImg.capacity();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View retval = inflater.inflate(R.layout.listitem, null);
ImageView img = (ImageView) retval.findViewById(R.id.tImage);
img.setImageBitmap(thumbImg.get(position));
return retval;
}
};
}
Here i'm using a vector in which after creating each bitmap, it is inserted into that vector. I'm using an asynctask to create the bitmap. After each bitmap is created i'm calling notifydatasetchanged() method to update the listview. But now in the output whenever each bitmap image is created it is adding one item in the listview with that image. But my requirement is to show all the 97 items in my list with some default image and whenever bitmap is created update the corresponding listitem.
can anyone help me?? Thanks in advance....
The simplest would be to include the default image as the src for the ImageView with id tImage in your layout listitem.xml. And in your getView method, replace the default image if the Bitmap for that position is available.
ImageView img = (ImageView) retval.findViewById(R.id.tImage);
Bitmap bmp = null;
if(position < thumbImg.size()){
thumbImg.get(position);
}
if(null != bmp){
img.setImageBitmap(bmp);
}

Gallery- viewing more than one picture

I have a working Gallery that shows one picture at a time and can be "swiped" to rotate through the images. I want to have the option of the user to view 2 or 3 pictures at a time by using the menu and selecting how many to show. So far Ive tried adjusting the Gallery width, and LinearLayout params and all crash the Activity. any advice would be appreciated.
I declare and initialize the Gallery here and have the onOptionsItemSelected method sekeleton.
public class SpeechAppActivity extends Activity implements OnClickListener{
//Menu Items
// Class variables
Gallery myGallery;
ImageView imageView;
MyDBAdapter db;
Item item1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = new MyDBAdapter(this);
db.insertEntry(item1 = new Item("Bathtub", "Bathroom", "Typical", "Clean", "fill, wash", "Round, deep", "Bathroom", "Toilet, Bathroom", R.drawable.ic_launcher));
Log.i("item", "item: " + item1.toString());
// Bind the gallery defined in the main.xml
// Apply a new (customized) ImageAdapter to it.
myGallery = (Gallery) findViewById(R.id.myGallery);
myGallery.setAdapter(new ImageAdapter(this));
//myGallery.setLayoutParams(new Gallery.LayoutParams(250, 250));
myGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.settings:
startActivity(new Intent(this, Prefs.class));
return true;
case R.id.show1:
//myGallery.findViewById(R.id.myGallery).setLayoutParams(new Gallery.LayoutParams(500, 250));
return true;
case R.id.show2:
//myGallery.findViewById(R.id.myGallery).setLayoutParams(new Gallery.LayoutParams(500, 250));
return true;
case R.id.show3:
//myGallery.findViewById(R.id.myGallery).setLayoutParams(new Gallery.LayoutParams(500, 250));
return true;
}
return false;
}
This is the Image Adapter class for the Gallery
public class ImageAdapter extends BaseAdapter {
/** The parent context */
private Context myContext;
// Put some images to project-folder: /res/drawable/
// format: jpg, gif, png, bmp, ...
private int[] myImageIds = { R.drawable.apple, R.drawable.orange,
R.drawable.ic_launcher };
/** Simple Constructor saving the 'parent' context. */
public ImageAdapter(Context c) {
this.myContext = c;
}
// inherited abstract methods - must be implemented
// Returns count of images, and individual IDs
public int getCount() {
return this.myImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// Returns a new ImageView to be displayed,
public View getView(int position, View convertView,
ViewGroup parent) {
// Get a View to display image data
ImageView iv = new ImageView(this.myContext);
iv.setImageResource(this.myImageIds[position]);
// Image should be scaled somehow
//iv.setScaleType(ImageView.ScaleType.CENTER);
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
//iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
//iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
//iv.setScaleType(ImageView.ScaleType.FIT_XY);
//iv.setScaleType(ImageView.ScaleType.FIT_END);
//iv.setScaleType(ImageView.ScaleType.FIT_START);
// Set the Width & Height of the individual images
//get scale for finding dip of a set # of pixels
final float scale = parent.getContext().getResources().getDisplayMetrics().density;
iv.setLayoutParams(new Gallery.LayoutParams((int) (300 * scale + 0.5f), (int) (250 * scale + 0.5f)));
return iv;
}
}// ImageAdapter
In your adapter,
Use View object (witn custom view) and put ImageView inside it.
This was you can put more than one images per view.
Best results can be achieved by few layout files based on number of images and using correct one according to user selection.
Let me know if you need more specific code template.

Categories

Resources