Need to generate thumbnail from video stored in server, below is my code but "path" variable is giving problem, how to get it resolved. If i remove path parameter with url parameter then i am getting the thumbnails but not in proper order or sometimes same thumbnail is generated for 2 or 3 videos, below is my code -
Video video = mVideos.get(position);
//play video using android api, when video view is clicked.
url = video.getVideoUrl(); // your URL here
Uri videoUri = Uri.parse(url);
new DownloadImage(holder.videothumbView).execute(url);
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (ImageView ) bmImage;
}
protected Bitmap doInBackground(String... urls) {
Bitmap myBitmap = null;
MediaMetadataRetriever mMRetriever = null;
try {
mMRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mMRetriever.setDataSource(path, new HashMap<String, String>());
else
mMRetriever.setDataSource(path);
myBitmap = mMRetriever.getFrameAtTime();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (mMRetriever != null) {
mMRetriever.release();
}
}
return myBitmap;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
All the network related task must be done in a separate thread. You can't do it in main thread. You can use Picasso image library. It is open source and you can show different image for different state like loading, error etc.
Picasso.with(context) // your activity of other context referance
.load(video.getVideoUrl())
.placeholder(R.drawable.user_placeholder) // this will show during image loading from network
.error(R.drawable.user_placeholder_error) // error image to display
.into(holder.videothumbView);
Related
I have a problem with the user profile picture update in my android application.
Introduction
In my MainActivity I can switch between two Fragments, the first one is the HomeFragment and the second is the UserProfileFragment.
In the UserProfile, the user can decide to upload a new image, so i let the user pick the image from local storage, then i upload this picture into FirebaseStorage and get the download link.
I use a class called LoadImageTask extending an AsyncTask that download the image from url and then upload the resulting bitmap into an ImageView that i have in my UserProfileFragment.
The problem:
When a user uploads a new profile picture, LoadImageTask does his job correctly. The problem is that, when the user tries to update his profile picture, the ImageView is still showing the old image and the user must go to HomeFragment and then go back to the UserProfileFragment to see the update. So, basically the update works but the Profile Picture change is not showed immediately.
What i tried to do
I tried many things like invalidating the imageView or trying to force the imageView in other ways but it didn't worked.
public class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
private ImageView image;
public LoadImageTask(ImageView image) {
this. image = image;
}
#Override
protected Bitmap doInBackground(String... urls) {
String downloadUrl = urls[0];
Bitmap bitmap = null;
try {
java.net.URL url = new java.net.URL(downloadUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if(result != null) {
image.setImageBitmap(circleTransformation(result));
}
}
}
When you pick image from the local storage you can set image to imageView from the uri in your onActivityResult.
imageView.setImageURI(imgUri);
I would like to use Glide to load bitmap to ImageView after cropping and re-sizing a bitmap.
I don't want to use ImageView.setImageBitmap(bitmap); because I am loading lots of images and it might be taking up some memory, although the images are small in size, I just need to use Glide because I know it optimises image caching.
I read this post, but I didn't quite understand his solution when I tried implementing it. So maybe someone has a cleaner and more easily understandable solution.
This is my code which picks up an image and creates a bitmap out of it.
I need to use glide instead of ImageView.setImageBitmap(bitmap);.
new AsyncTask<String, Void, Void>() {
Bitmap theBitmap = null;
Bitmap bm = null;
#Override
protected Void doInBackground(String... params) {
String TAG = "Error Message: ";
try {
//Load the image into bitmap
theBitmap = Glide.
with(mContext).
load("http://example.com/imageurl").
asBitmap().
into(-1, -1).
get();
//resizes the image to a smaller dimension out of the main image.
bm = Bitmap.createBitmap(theBitmap, 0, 0, 210, 80);
} catch (final ExecutionException e) {
Log.e(TAG, e.getMessage());
} catch (final InterruptedException e) {
Log.e(TAG, e.getMessage());
} catch (final NullPointerException e) {
//
}
return null;
}
#Override
protected void onPostExecute(Void dummy) {
if (null != theBitmap) {
//Set image to imageview.
**// I would like to Use Glide to set the image view here Instead of .setImageBitmap function**
holder.mImageView.setImageBitmap(bm);
holder.mImageView.setAdjustViewBounds(true);
holder.mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
}
}.execute();
You don't need AsyncTask to load image with Glide. Glide load image asynchronys.
Try to use this code:
Glide.with(mContext)
.load("http://example.com/imageurl")
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
// you can do something with loaded bitmap here
// .....
holder.mImageView.setImageBitmap(resource);
}
});
So the problem is
1. We are using listView for chat application
2 . each time a chat is sent or rec we update the arrayList and update the adapter and do notifydatasetAdaper() for refreshing the list view.
3. So if we send 10 images in chat and then send 11th chat msg(let say text chtat) and then call notifydatasetadapter() in this case all the 10 images are refreshing.
4. So i need to stop this refreshing of images.
5. ListView must be refreshed without refreshing the images
So any idea how can i achieve this.. or may be m on the wrong path please show me the correct way of doing it.....!!!
I also tried using picaso but the library is conflicting with okhttp library ....!!!
Also this is the way i am showing the images
public class ImageFromSd extends AsyncTask<Object, Bitmap, Bitmap> {
ImageView im;
// int targetWidth = 200;
// int targetHeight = 200;
#Override
protected Bitmap doInBackground(Object... params) {
// TODO Auto-generated method stub
Bitmap bitmap = null;
try {
im = (ImageView) params[0];
String path = (String) im.getTag();
Log.d("ankit", "image path :::::" + path);
bitmap = BitmapFactory.decodeFile(path);
// bitmap.compress(CompressFormat.JPEG, 100, new
// FileOutputStream(
// path));
//
// bitmap = Bitmap.createScaledBitmap(bitmap, targetWidth,
// targetHeight, false);
}
// catch (FileNotFoundException e) {
// e.printStackTrace();
// bitmap = null;
// }
catch (OutOfMemoryError e) {
e.printStackTrace();
bitmap = null;
} catch (NullPointerException e) {
e.printStackTrace();
bitmap = null;
} catch (Exception e) {
e.printStackTrace();
bitmap = null;
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result != null) {
im.setScaleType(ScaleType.FIT_CENTER);
im.setImageBitmap(result);
}
}
}
and then calling it like this
im.setTag(items.get(i).getTextChat());
new ImageFromSd().execute(im);
Firstly, You have to refresh listview as any data updates within listview.
Secondly, the method you using for loading image is not good.
try this library to load remote or local image. it maintains cache automatically and very efficient for image loading.
Universal Image Loader
https://github.com/nostra13/Android-Universal-Image-Loader
I am not checking for the bitmap is already cached or not.
Everytime when a imageView is passed to AsynTask, i am decoding from the path. Which is wrong.
I shouuld LRUCache or DiskCache and store the bitmap in cache with the path as key.
http://developer.android.com/reference/android/util/LruCache.html
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
I am new for Android. I want to create an jar file if i call a method of that jar file in another android application it will show an image in imageview of the application. For example
a method in jar file as DisplayImg(URL); i will use this jar as library in another application and here i will create an imageview
ImageView imageView;
imageView = (ImageView) findViewById(R.id.img);
Then if i call imageView.DisplayImg(URL); then it will display specified url image on the imageview. I spend lot more time to get the solution but not work.plz help with the code thank
You don't need to create a library, in fact, there is a same library available for doing exactly what you want to!
It's called Picasso. You can find it here.
Also note that if you want imageView.DisplayImage(URL); you should create a new instance of ImageView class, because it doesn't contain this method. I recommend using DisplayImage(URL, imageView);.
But in case you REALLY WANT to do this, here you go:
1- For creating a library, create a New Android Application Project, and in the second window, check Mark this project as a library option. Also notice that we don't need Activity.
2- Create a new class, such as ImageUtils.java in the newly-created project. Here you need to put the DisplayImage() method:
public static void DisplayImage(String URL, ImageView imageView) {
new DownloadImageTask(imageView).execute(URL);
}
And this for the DownloadImageTask class :
public static class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public DownloadImageTask(ImageView bmImage) {
this.imageView = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap imageBitmap = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
imageBitmap = BitmapFactory.decodeStream(in);
} catch (IOException e) {
// Probably there's no Internet connection. Warn the user about checking his/her connection.
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return imageBitmap;
}
protected void onPostExecute(Bitmap result) {
if (imageView != null) imageView.setImageBitmap(result);
}
}
3- Execute your project as an android application.
4- There should be a jar file under the bin folder. It's your library. Import it to your other applications and use it. In that applications you can use it with this code:
ImageView imageView = (ImageView) findViewById(R.id.img);
ImageUtils.DisplayImage(URL, imageView);
5- Don't forget to add this permission to the apps that use this library:
<uses-permission android:name="android.permission.INTERNET" />
Hope it helps :)
I am getting json data. In that json I have a url for an image. Now I want to display that Image in ImageView. How can I do acheive this? Here is my code
class LoadInbox extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Home.this);
pDialog.setMessage("Loading Inbox ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Inbox JSON
* */
protected String doInBackground(String... arg0) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = userFunctions.homeData();
Log.e("Data", json.toString());
// Check your log cat for JSON reponse
Log.d("Inbox JSON: ", json.toString());
try {
data = json.getJSONArray(TAG_DATA);
Log.d("inbox array: ", data.toString());
// looping through All messages
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String profile_img = c.getString(TAG_PROFILE_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PROFILE_IMG, profile_img);
// adding HashList to ArrayList
inboxList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Home.this, inboxList,
R.layout.home_list_item, new String[] { TAG_PROFILE_IMG },
new int[] { R.id.profile_img2 });
// updating listview
setListAdapter(adapter);
}
});
}
here is my layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/profile_img2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="8dip"
android:paddingLeft="8dip"
android:paddingBottom="4dip" />
</RelativeLayout>
So you'll want to create another AsyncTask that given a URL will load the image, and populate some control. I typically do something like this:
ImageView imageView = (ImageView)findById(R.id.blah);
new ImageLoader( person.getImageUri(), imageView, 128, 128 ).execute();
The ImageLoader would be another AsyncTask like this:
public class ImageLoader extends AsyncTask<URI,Integer,BitmapDrawable> {
private Uri imageUri;
private ImageView imageView;
private int preferredWidth = 80;
private int preferredHeight = 80;
public ImageLoader( URI uri, ImageView imageView, int scaleWidth, int scaleHeight ) {
this.imageUri = uri;
this.imageView = imageView;
this.preferredWidth = scaleWidth;
this.preferredHeight = scaleHeight;
}
public BitmapDrawable doInBackground(URI... params) {
if( imageUri == null ) return null;
String url = imageUri.toString();
if( url.length() == 0 ) return null;
HttpGet httpGet = new HttpGet(url);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute( httpGet );
InputStream is = new BufferedInputStream( response.getEntity().getContent() );
try {
Bitmap bitmap = BitmapFactory.decodeStream(is);
if( preferredWidth > 0 && preferredHeight > 0 && bitmap.getWidth() > preferredWidth && bitmap.getHeight() > preferredHeight ) {
return Bitmap.createScaledBitmap(bitmap, preferredWidth, preferredHeight, false);
} else {
return bitmap;
}
} finally {
is.close();
}
}
}
public void onPostExecute( BitmapDrawable drawable ) {
imageView.setImageBitmap( drawable );
}
}
Then you can kick this AsyncTask off when the image is being bound in your ListView by creating your own subclass ListAdapter. So you'll have to ditch using SimpleAdapter because things aren't simple anymore. This has a lot of advantages so you only load the images being displayed. That means a very small number is loaded out of the total. Also your user can see the data before the image loads so quicker access to the data. If you did this in your existing AsyncTask you'd load every image, and the user would have to wait for every single one to finish before the data is shown to the user. There are somethings that can be improved by this. One AsyncTask uses its own thread so you'll be running a lot of threads potentially (10 or more) all at once. That can kill your server with lots of clients. You can centralize these using an ExecutorService (ie thread pool) but you'll have to ditch using AsyncTask and implement your own facility to run the job off the UI thread and post the results back on the UI thread. Second, your images will load every time the user scrolls. For this I implemented my own caching scheme based on the URI of the image so I only load the image once and return it from the cache. It's a little too much code to post here, but these are exercises for the reader.
Also notice I'm not posting back to the UI thread in onPostExecute(). That's because AsyncTask does that for me I don't have to do it again as your code above shows. You should just remove that extra runnable and inline the code in onPostExecute().
you can try picasso is really easy to use and works really well.
Picasso.with(this.getActivity()).load(person.getImageUri()).into(imageView); // if person.getImageUri() has the url image loaded from json
And that's it.
As it looks you are getting the more than one url (as in array)
1- Keep all the url in an hastable with key as url and value as image View.
2- Show your UI and with loading image.
3- create the other task download image one by one and update in the image view.
as example lazy imageloader......
http://iamvijayakumar.blogspot.in/2011/06/android-lazy-image-loader-example.html
http://codehenge.net/blog/2011/06/android-development-tutorial-asynchronous-lazy-loading-and-caching-of-listview-images/
Android Out of Memory error with Lazy Load images
Android lazy loading images class eats up all my memory
Lazy Load images on Listview in android(Beginner Level)?
Lazy load of images in ListView