Url image to imageview - java

ImageView imgview = (ImageView)findViewById(R.id.image);
Drawable drawable = LoadImage("http://192.168.172.1/myproject/images/st1.jpg");
imgview.setImageDrawable(drawable);
...
...
public Drawable LoadImage(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable b = Drawable.createFromStream(is, url);
return b;
}catch(Exception e){
System.out.println(e);
return null;
}
}
.java
...
...
<ImageView
android:id="#+id/image"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
.xml
getting the image from wamp server as a Url and display it onto my xml but image doesn't shown

I use the following code to get an image from url and add it to an ImageView:
ImageRequest imgRequest = new ImageRequest(url,
new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
mImageView.setImageBitmap(response);
Toast.makeText(MainActivity.this, "Succes", Toast.LENGTH_SHORT).show();
}
}, 0, 0, ImageView.ScaleType.FIT_XY, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
mImageView.setBackgroundColor(Color.parseColor("#ff0000"));
error.printStackTrace();
}
});
Volley.newRequestQueue(this).add(imgRequest);
All you need to do is to use Volley Library made by google developers(trusted source). More info here
Hope it helps!

Use http://square.github.io/picasso/ it's really easy to implement, follow the following steps:-
1- If you haven’t done it already. If you are using eclipse as your development IDE, then just copy the downloaded picasso-2.5.2.jar file into your application lib folder. If you are using Android Studio IDE, then you have to add below dependency in build.gradle file.
dependencies {
...
compile "com.squareup.picasso:picasso:2.5.2"
...
}
2- Now let us download the image and display on imageView:-
//Loading image from below url into imageView
Picasso.with(this)
.load("YOUR IMAGE URL HERE")
.into(imageView);//Your image view
That's all, Hope this will help you !!

Are you given internet permission on manifest
and running this code in background such as asyn task
class LoadImageLoader extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
drawable = LoadImage("http://i.imgur.com/DvpvklR.png");
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
imgview.setImageDrawable(drawable);
}
}

Use Picasso works great and is easy to use.

There are many third party libraries that can help you with that.
Their use is strongly recommended, ie. don't create your own tool for that.
Picasso by guys from Square
Glide used in sample apps by Google

Related

Firebase Storage and Image View

I want to get image from Firebase Storage and than show at Image View. I trying this code but not working. Always I getting my "ERROR" toast message.
App is opening but I dont see my JPEG.
** I found one way but it is not enough for me.
If I delete 'com.google.firebase:firebase-auth:19.3.2' from build gradle, this code working.
I need FirebaseAuth because I have User login and logout page.
Do you know another way for Firebase storage and image ?
Thank you for help.
enter image description here
private StorageReference mStorageReference;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vardiya);
mStorageReference=FirebaseStorage.getInstance().getReference().child("vardiyaandroid.jpeg");
final File localfile;
try {
localfile = File.createTempFile("vardiyaandroid","jpeg");
mStorageReference.getFile(localfile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(vardiya.this,"Resim Hazır",Toast.LENGTH_LONG).show();
Bitmap bitmap = BitmapFactory.decodeFile(localfile.getAbsolutePath());
(imageView=findViewById(R.id.imageView)).setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(vardiya.this,"ERROR",Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
I found my false.
You will change this code
mStorageReference=FirebaseStorage.getInstance().getReference().child("vardiyaandroid.jpeg");
with
mStorageReference=FirebaseStorage.getInstance().getReferenceFromUrl("gs://YOURAPPID.appspot.com/vardiyaandroid.jpeg");
StorageReference pathreferance =mStorageReference.child("vardiyaandroid.jpeg");
and the storege rules must be this:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, writ, auth: if true;
}
}
}

Picasso can't load image inside StorageReference's onSuccess method

When trying Picasso on the runtime onStart() method it normally loads the image from Firebase using the download link from the console.
But when I try to load an image inside StorageReference onSuccess method it just won't work.
This class is extending Fragment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_IN && resultCode == Activity.RESULT_OK) {
isGranted = true;
String path = FireStorage.retUID() + "/";
showIndProgress();
Uri uri = data.getData();
StorageReference childPathRef = FireStorage.storageRef.child(path + uri.getLastPathSegment());
childPathRef.putFile(uri)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
Picasso.with(mContext).load(task.getResult().getDownloadUrl())
.into(profView);
Picasso.Builder build = new Picasso.Builder(mContext);
build.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
Toast.makeText(mContext, "exception\n" + exception.toString(), Toast.LENGTH_SHORT).show();
}
});
progressDialog.dismiss();
} else {
//failed
}
}
});
}
}
This is my FirebaseStorage instance on another Class:
public static FirebaseStorage storage = FirebaseStorage.getInstance();
public static StorageReference storageRef =
storage.getReferenceFromUrl("gs://myurl.appspot.com/");
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
My XML layout:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#drawable/gcover"
android:id="#+id/relativeLayout">
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profPhoto"
android:clickable="true"
android:layout_width="120dp"
android:layout_height="120dp"
android:padding="20dp"
android:src="#drawable/default_prof"
android:scaleType="centerCrop"
app:civ_border_color="#color/trans"
app:civ_border_width="2dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
My views initialization:
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_prof, container, false);
profView = (CircleImageView) view.findViewById(R.id.profPhoto);
btn1 = (Button) view.findViewById(R.id.btn_1);
btn2 = (Button) view.findViewById(R.id.btn_2);
btn3 = (Button) view.findViewById(R.id.btn_3);
return view;
}
Update 2:
While the code I posted works for me, you indicate that it fails for you. My test does not use a fragment, I don't know what version of the libraries you are using, it's now known how the fragment is being added to the layout, etc. There are too many possible causes of the different behavior to effectively debug it on SO.
As an experiment, you can try using Glide and FirebaseUI to perform the download instead of Picasso. The code is shown below and works for me. Because the download is from the storage reference and not the URL, this approach requires read access to the storage. You also need to add these lines to your build dependencies:
// FirebaseUI 2.0.1 is the version to use for Firebase SDK version 11.0.1
// SDK/Firebase version compatibility is important.
// See the FirebaseUI docs for a table of compatible versions.
compile 'com.firebaseui:firebase-ui-storage:2.0.1'
compile 'com.github.bumptech.glide:glide:3.8.0'
.
childPathRef.putFile(Uri.fromFile(file))
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Upload: SUCCESS");
Glide.with(mContext)
.using(new FirebaseImageLoader())
.load(childPathRef)
.dontAnimate()
.listener(new RequestListener<StorageReference, GlideDrawable>() {
#Override
public boolean onException(Exception e, StorageReference model,
Target<GlideDrawable> target, boolean isFirstResource) {
Log.e(TAG, "Download: FAILED: ", e);
return false;
}
#Override
public boolean onResourceReady(GlideDrawable resource,
StorageReference model, Target<GlideDrawable> target,
boolean isFromMemoryCache, boolean isFirstResource) {
Log.d(TAG, "Download: SUCCESS");
return false;
}
})
.into(mCircleImageView);
} else {
Log.e(TAG, "Upload: FAILED: " + task.getException().getMessage());
}
}
});
Update:
Additional debugging showed that the upload and download were both completing sucessfully. The problem was with the rendering of the downloaded image. The documentation for CircleImageView indicates that noFade() must be used when downloading from Picasso:
If you use an image loading library like Picasso or Glide, you need to
disable their fade animations to avoid messed up images. For Picasso
use the noFade() option, for Glide use dontAnimate().
It was also found that small images were rendered but large images were displayed as black. fit() was added to cause Picasso to resize the image.
To detect both upload success and failure, use a completion listener instead of just a success listener, and test task.isSuccessful(). The upload is probably failing because of security rules, or invalid StorageReference:
StorageReference childPathRef = Class.storageRef.child(path + uri.getLastPathSegment());
childPathRef.putFile(uri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Upload: SUCCESS");
Picasso.with(mContext)
.load(task.getResult().getDownloadUrl())
.noFade()
.fit()
.into(profView, new Callback() {
#Override
public void onSuccess() {
Log.d(TAG, "Download: SUCCESS");
Toast.makeText(mContext, "download done" , Toast.LENGTH_SHORT).show(); }
#Override
public void onError() {
Log.d(TAG, "Download: FAILED");
}
});
Toast.makeText(mContext, "upload done" , Toast.LENGTH_SHORT).show();
} else {
Log.e(TAG, "Upload: FAILED: " + task.getException().getMessage());
}
progressDialog.dismiss();
}
});
Limitations for de.hdodenhof.circleimageview.CircleImageView
The ScaleType is always CENTER_CROP and you'll get an exception if you try to change it. This is (currently) by design as it's perfectly fine for profile images.
Enabling adjustViewBounds is not supported as this requires an unsupported ScaleType
If you use an image loading library like Picasso or Glide, you need to disable their fade animations to avoid messed up images. For Picasso use the noFade() option, for Glide use dontAnimate(). If you want to keep the fadeIn animation, you have to fetch the image into a Target and apply a custom animation yourself when receiving the Bitmap.
Using a TransitionDrawable with CircleImageView doesn't work properly and leads to messed up images.
I just switched from CircleImageView to a normal ImageView and it suddenly worked.
It is possible that in this line of code:
Picasso.with(mContext).load(task.getResult().getDownloadUrl())
.into(profView);
profView is recreating with fragment, and Picasso.into(View view) keeps week reference to view.
From docs:
public void into(android.widget.ImageView target) Asynchronously
fulfills the request into the specified ImageView. Note: This method
keeps a weak reference to the ImageView instance and will
automatically support object recycling.
Try to use:
public void into(#NotNull ImageView target,
Callback callback)
Maybe it's a conflict with the CircleImageView.
Try to change it with an ImageView or define the CircleImageView like an ImageView.
Try :
ImageView profView = (ImageView) view.findViewById(R.id.profPhoto);

why are my images loaded so slow to the listView?

I have a listView with ImageViews.
I try to compress the bitmaps with the following code:
public void getImage(final String urlStr, final ImageView toSet) {
// set the tag immediately, to prevent delayed image downloads from
// setting this image.
toSet.setTag(urlStr);
getImage(urlStr, new ImageRepository.ImageRepositoryListener() {
#Override
public void onImageRetrieved(final Drawable drawable) {
if (drawable == null)
return;
toSet.post(new Runnable() {
#Override
public void run() {
// make sure the tag is still the one we set at the
// beginning of this function
if (toSet.getTag() == urlStr) {
toSet.setImageDrawable(drawable);
drawable.setCallback(null);
}
}
});
}
});
}
public class DownloadImageAsyncTask2 extends
AsyncTask<String, Void, Bitmap> {
private final ImageView imageView;
private String imageUrl;
public DownloadImageAsyncTask2(ImageView imageView) {
this.imageView = imageView;
}
#Override
protected void onPreExecute() {
Log.i("DownloadImageAsyncTask", "Starting image download task...");
}
#Override
protected Bitmap doInBackground(String... params) {
imageUrl = params[0];
try {
imageRepository.getImage(imageUrl, imageView);
return BitmapFactory.decodeStream((InputStream) new URL(
imageUrl).getContent());
} catch (IOException e) {
Log.e("DownloadImageAsyncTask", "Error reading bitmap" + e);
downloadingImageUrls.remove(imageUrl);
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
imageCache.put(imageUrl, bitmap);
downloadingImageUrls.remove(imageUrl);
if (bitmap != null
&& ((String) imageView.getTag()).equals(imageUrl)) {
imageView.setImageBitmap(bitmap);
}
}
}
How can I make the image loading time be faster?
(I have tried to downsize the images on the server side, but I want to think what can I improve in the client side).
I use async download task to download the images and a cache layer to persist them.
Here is the code:
Your image loading is slow because:
After downloading and saving images in the cache , the AsyncTask is used to load but it doesn't give the result immediately.
Firstly, it is controlled by the global Thread's pool with the number maximum of thread in concurrence. Sometimes , it begins after finishing the other AsyncTask .
Secondly, the method "onPostExecute" is executed in Main Thread but after finishing all the other messages of Main Thread.
So:
Use AsyncTask only to download and save images in the cache.
Try to check if the expected image exists in the cache before using AsyncTask. If it exists then you display it directly in Main thread. Make sure that the size of expected image fits well in your image view .
In your case , add the code like this:
public void getImage(final String urlStr, final ImageView toSet) {
//get the expected image associated with this url and the size of this image view in the cache
Bitmap bitmap = getExpectedBitmap(urlStr,expectedSize);
if(bitmap != null) {
//if it exists , set it in the image view and finish.
toSet.setImageBitmap(bitmap);
return;
}
// set the tag immediately, to prevent delayed image downloads from
// setting this image.
toSet.setTag(urlStr);
getImage(urlStr, new ImageRepository.ImageRepositoryListener() {
#Override
public void onImageRetrieved(final Drawable drawable) {
if (drawable == null)
return;
toSet.post(new Runnable() {
#Override
public void run() {
// make sure the tag is still the one we set at the
// beginning of this function
if (toSet.getTag() == urlStr) {
toSet.setImageDrawable(drawable);
drawable.setCallback(null);
}
}
});
}
});
}

Issues with calling AsyncTask on Button press

I am working on an app which requires that I download an image after a button press. I was going to use AsyncTask, until I found out that you can only call a particular AsyncTask once. What should I use instead so that I can still use Progress Dialog and whatnot but still call it on button press?
called on button press, passing in an int
class ImageDownloader
extends AsyncTask<Integer, Integer, Bitmap> {
protected void onPreExecute(){
launchDialog();
}
#Override
protected Bitmap doInBackground(Integer... params) {
//TODO Auto-generated method stub
try{
//finding and downloading an image, and passing back the proper bitmap to the onPostExecute
}catch(Exception e){
Log.e("Image", "Failed to load image", e);
}
return null;
}
protected void onProgressUpdate(Integer... params){
}
protected void onPostExecute(Bitmap img){
ImageView iv = (ImageView) findViewById(R.id.imageView);
if(iv!=null && img!=null){
iv.setImageBitmap(img);
new PhotoViewAttacher(iv);
}
closeDialog();
enablebuttons();
}
protected void onCancelled(){
closeDialog();
enablebuttons();
}
}
Thanks in advance!
Just create a new instance of the AsyncTask in your click handler every time and run that (as opposed to executing a single instance over and over).

MetaIO progressDialog freezes when loading SDK

I am quite new to Android/Java, and my first app is using MetaIO SDK.
I am trying to implement "Loading" progress bar, while app (MetaIO SDK) is loading.
Overlay background is shown
Loading dialog is appeared and "loading image" starts spinning
Overlay background disappears and loading image stops spinning <- the problem
After 2-3 seconds it unfreezes and ARELViewActivity is executed.
The code:
public void onScanButtonClick(View v)
{
new ScanLoadingDialog().execute(0);
}
private class ScanLoadingDialog extends AsyncTask<Integer, Integer, Boolean>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Boolean doInBackground(Integer... params)
{
try
{
synchronized (this) {
AssetsManager.extractAllAssets(getApplicationContext(), true);
startActivity( new Intent(getApplicationContext(), ARELViewActivity.class));
}
}
catch (IOException e)
{
MetaioDebug.log(Log.ERROR, "Error extracting assets: "+e.getMessage());
MetaioDebug.printStackTrace(Log.ERROR, e);
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
finish();
}
}
Am I doing something wrong?
P.S. Full source code can be found here: link text
P.S.S. Related to this question, but I am using technique suggested there, and it still doesn't want to work
I had a similar problem and i solved it by running the UI handling code on the UI thread like so
runOnUiThread(new Runnable() {
#Override
public void run() {
if (imgvExampleOverlay != null)
imgvExampleOverlay.setVisibility(View.VISIBLE);
}
});
imgvExampleOverlay is an image like the one the user has to capture.
Hope this helps

Categories

Resources