Image downloaded from server is blurred in ImageView - imageview

I am using Universal Imageloader and Volley to download an image from my server. Both result in a blurred image. It doesn't make a difference that the width and the height of the image is smaller or larger than the resolution of my screen. I tried uploading the image I am trying with in low and high resolution as well. The image is always displayed blurred.
Imageloader:
optionsImg = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.noimage)
.cacheOnDisc(true)
.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.cacheInMemory(true)
.bitmapConfig(Bitmap.Config.ARGB_8888)
.considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(1555))
.build();
imageLoader.displayImage("http://www.mywebsite.com/Images/image.png", iv_bucket, optionsImg, new SimpleImageLoadingListener() {
boolean cacheFound;
#Override
public void onLoadingStarted(String url, View view) {
List<String> memCache = MemoryCacheUtil.findCacheKeysForImageUri(url, ImageLoader.getInstance().getMemoryCache());
cacheFound = !memCache.isEmpty();
if (!cacheFound) {
File discCache = DiscCacheUtil.findInCache(url, ImageLoader.getInstance().getDiscCache());
if (discCache != null) {
cacheFound = discCache.exists();
}
}
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {}
#Override
public void onLoadingComplete(String imageUri, final View view, Bitmap loadedImage) {
if (cacheFound) { ImageLoader.getInstance().displayImage(imageUri, (ImageView) view, optionsImg);
}
}
});
Volley:
com.android.volley.toolbox.ImageLoader nil = AppController.getInstance().getImageLoader();
nil.get("http://www.mywebsite.com/Images/image.png", new ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("IMG", "Image Load Error: " + error.getMessage());
}
#Override
public void onResponse(ImageContainer response, boolean arg1) {
if (response.getBitmap() != null) {
Log.e("IMG_BG", "Image Load Success");
iv_bucket.setImageBitmap(response.getBitmap());
}
}
});

I'm so lame. My phone cached the low quality images so even if I increased the quality it displayed the cached photos

Related

Why is firebase populating my viewholder with the same image from Firebase Storage

I have a blog app that consists of username,profileImage,description and postImage. I am using this code to retrieve these items from firebase
FirebaseRecyclerAdapter<Blog,BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.blog_row,
BlogViewHolder.class,
mDatabase.orderByChild("TimeOrder")
) {
#Override
protected void populateViewHolder(final BlogViewHolder viewHolder, Blog model, int position) {
viewHolder.setDescription(model.getDescription());
if (isAdded()) {
viewHolder.setImage(getActivity(), model.getPostimage());
}
viewHolder.setUid(model.getUid());//get username and profile picture from this
Everything is fine except that the about two postImages are repeated throughout the recyclerview. The profile picture also are from the same user ie One or two pictures are used as profile pictures of the rest of the users.
This is the code for setImage
public void setImage(final Context con, final String image){
final ImageView imageView = view.findViewById(R.id.post_image);
if (postbool) {
Picasso.with(con).load(image).placeholder(R.drawable.unnamed).error(R.drawable.imageerror).networkPolicy(NetworkPolicy.OFFLINE).into(imageView, new Callback() {
#Override
public void onSuccess() {
postbool = false;
}
#Override
public void onError() {
Picasso.with(con).load(image).placeholder(R.drawable.unnamed).into(imageView);
postbool = false;
}
});
}
}
This are a few screenshots. The profile picture is the same.
Where am I going wrong?
This might be due to cache issues! My suggestion, always reset all the views in the ViewHolder before populating values.
#Override
protected void populateViewHolder(final BlogViewHolder viewHolder, Blog model, int position) {
**reset all views**
viewHolder.setDescription("");
viewHolder.imageview.setImageDrawable(null);
viewHolder.setUid("");
viewHolder.setDescription(model.getDescription());
if (isAdded()) {
viewHolder.setImage(getActivity(), model.getPostimage());
}
viewHolder.setUid(model.getUid());//get username and profile picture from this
Please let me know how it goes!

Fragment already added IllegalStateException in viewpager

I'm using viewpager to display pictures. I just need three fragments basically: previous image to preview, current display image and next image to preview. I would like to just display a preview of previous and next image, it will change to full image when user actually swipe to it. So I'm thinking of just using 3 fragment to achieve this. Code is below:
private class ImagePagerAdapter extends FragmentStatePagerAdapter implements ViewPager.OnPageChangeListener {
private ImageFragment mImageFragment;
private ImagePreviewFragment mPreviousPreviewFragment;
private ImagePreviewFragment mNextPreviewFragment;
public ImagePagerAdapter(FragmentManager fm, ImageFragment image, ImagePreviewFragment previous, ImagePreviewFragment next) {
super(fm);
mImageFragment = image;
mPreviousPreviewFragment = previous;
mNextPreviewFragment = next;
}
#Override
public Fragment getItem(int position) {
if (position == mPager.getCurrentItem()) {
mImageFragment.display(position);
return mImageFragment;
}
if (position < mPager.getCurrentItem()) {
mPreviousPreviewFragment.display(position - 1);
return mPreviousPreviewFragment;
}
mNextPreviewFragment.display(position + 1);
return mNextPreviewFragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.d(TAG, "onPageScrolled");
}
#Override
public void onPageSelected(final int position) {
Log.d(TAG, "onPageSelected " + position);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
}, 500);
}
#Override
public void onPageScrollStateChanged(int state) {
Log.d(TAG, "onPageScrollStateChanged " + state);
}
#Override
public int getItemPosition(Object item) {
return POSITION_NONE;
//return POSITION_UNCHANGED;
}
}
So basically, I pre-created three fragments to display previous/next preview and current image and return them for getItem(). I also notifydatasetchange() in onpageselected() to make all three position to update the fragment when user swipe to new page.
But the problem is that it will throw out
Fragment already added IllegalStateException
when the fragments are added a second time. I think it's because it's been added before. I can create a new fragment every time but I think that's wasteful. So how can I reuse the already created fragment and just update them?
Thanks,
Simon
FragmentStatePagerAdapter design suggests creating a new Fragment for every page (see Google's example). And unfortunately you cannot readd a Fragment once it was added to a FragmentManager (what implicitly happens inside adapter), hence the exception you got. So the official Google-way is to create new fragments and let them be destroyed and recreated by the adapter.
But if you want to reuse pages and utilize an analogue of ViewHolder pattern, you should stick to views instead of fragments. Views could be removed from their parent and reused, unlike fragments. Extend PagerAdapter and implement instantiateItem() like this:
#Override
public Object instantiateItem(ViewGroup container, final int position) {
//determine the view type by position
View view = viewPager.findViewWithTag("your_view_type");
if (view == null) {
Context context = container.getContext();
view = LayoutInflater.from(context).inflate(R.layout.page, null);
view.setTag("your_view_type");
} else {
ViewGroup parent = (ViewGroup) item.getParent();
if (parent != null) {
parent.removeView(item);
}
}
processYourView(position, view);
container.addView(view, MATCH);
return view;
}
You should add some extra logic to determine the view type by position (since you have 3 types of views), I think you can figure that out.

how to use progressbar when loading image in picasso?

I want onStart() method to load image from server using picasso and I want to show a progress bar until the photos are fully downloaded
Here is my code:
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Picasso.with(context).load(imageLoad)
.placeholder(R.id.progressBarDetails)
.error(R.drawable.friend_request).noFade().resize(200, 200)
.into(avatarImage, new Callback() {
#Override
public void onError() {
// TODO Auto-generated method stub
}
#Override
public void onSuccess() {
// TODO Auto-generated method stub
progressbar.setVisibility(View.GONE);
}
});
Picasso.with(this).load(imageLoad).into(target);
}
OnFinished a = new OnFinished() {
#Override
public void onSendFinished(IntentSender IntentSender, Intent intent,
int resultCode, String resultData, Bundle resultExtras) {
// TODO Auto-generated method stub
intent = new Intent(getApplicationContext(), Map.class);
}
};
private Target target = new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
File file = new File(Environment
.getExternalStorageDirectory().getPath()
+ "/actress_wallpaper.jpg");
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 75, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
I haven't tested your code but even if that works, the file actress_wallpaper.jpg isn't loaded in the ImageView. In the docs, it says
Objects implementing this class must have a working implementation of Object.equals(Object) and Object.hashCode() for proper storage internally.
Try this:
File file = new File(pathToFile);
Picasso.with(context)
.load(file)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
progressbar.setVisibility(View.GONE);
}
});
be warned I haven't tested my code.
Update:
I have tried version 2.3.2 and 2.3.3, it seems like that there's an issue https://github.com/square/picasso/issues/539
It is an old question but may be this answer can help others as I also had issues in showing progress bar while loading image from server.
I am using Picasso 2.4.0. and I am using Picasso Target interface to load image in imageview. Here is the tested and working code:
First add the following lines:
ImageView ivPhoto = (ImageView) findViewById(R.id.iv_photo);
ProgressBar pbLoadingBar = (ProgressBar) findViewById(R.id.pb_loading_bar);
//get image url
String imageUrl = getImageUrl();
//ImageViewTarget is the implementation of Target interface.
//code for this ImageViewTarget is in the end
Target target = new ImageViewTarget(ivPhoto, pbLoadingBar);
Picasso.with(mContext)
.load(imageUrl)
.placeholder(R.drawable.place_holder)
.error(R.drawable.error_drawable)
.into(target);
Here is the implementation of Target interface used above
private static class ImageViewTarget implements Target {
private WeakReference<ImageView> mImageViewReference;
private WeakReference<ProgressBar> mProgressBarReference;
public ImageViewTarget(ImageView imageView, ProgressBar progressBar) {
this.mImageViewReference = new WeakReference<>(imageView);
this.mProgressBarReference = new WeakReference<>(progressBar);
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//you can use this bitmap to load image in image view or save it in image file like the one in the above question.
ImageView imageView = mImageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
ProgressBar progressBar = mProgressBarReference.get();
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
ImageView imageView = mImageViewReference.get();
if (imageView != null) {
imageView.setImageDrawable(errorDrawable);
}
ProgressBar progressBar = mProgressBarReference.get();
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
ImageView imageView = mImageViewReference.get();
if (imageView != null) {
imageView.setImageDrawable(placeHolderDrawable);
}
ProgressBar progressBar = mProgressBarReference.get();
if (progressBar != null) {
progressBar.setVisibility(View.VISIBLE);
}
}
}
The above code works fine if used for loading image in activity. But if you want to load image in gridview/recyclerview or view pager etc. where same view holder is used, you might get an issue where onBitmapLoaded() is not called (as the view is recycled and Picasso only keeps a weak reference to the Target object). Here is a link to solve this problem.
change to this
Picasso.get()
.load(tImageUrl())
.into(holder.AnimImage, new Callback() {
#Override
public void onSuccess() {
holder.progressBar.setVisibility(View.GONE);
}
#Override
public void onError(Exception e) {
}
});

Javafx - Bind the background task with Scene

My application having the two Screens.
Screen-1:
It's having two buttons and one Label
1) Download:
If we click on this, then we will start the downloading process but we still in screen1 and allow you to access the "Navigate" control.
2) Navigate: If we click on this, Then we will redirect to the screen-2.
Screen-2:
1)Back: If we click on this, then we will back to the Screen-1.
While downloading process, I want to allow the user to access the other controls as well. If we started the download process and navigates to some other screen and redirects to the download screen, then we will show the current downloading progress instead of opening it as fresh. For this, I implemented like following. I created one class for implementing this download process but I am unable to update the UI of the screen from that class. Please help me on this.
Screen-1
public class MainsceneController implements Initializable {
#FXML
Button Download, Navigate;
#FXML
Label percentage;
#FXML
HBox progTag;
SyncService service = new SyncService(MainsceneController.this);
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
void DownlaodManager() {
service.downloadProjectFiles();
}
#FXML
void Naviagtion() {
URL location = SecondSceneController.class.getResource("SecondScene.fxml");
ViewManager.getInstance().setView(location);
}
}
Screen-2:
public class SecondSceneController implements Initializable {
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
void goBack() {
URL location = MainsceneController.class.getResource("mainscene.fxml");
ViewManager.getInstance().setView(location);
}
}
Background downloading task
public class SyncService {
long currentDownload, totalFileSize;
MainsceneController controller;
DownloadingFilesTask downloadingFilesTask;
public SyncService(MainsceneController controller) {
this.controller = controller;
downloadingFilesTask = new DownloadingFilesTask();
}
public void downloadProjectFiles() throws IOException {
DownloadingFilesTask downloadingFilesTask = new DownloadingFilesTask();
downloadingFilesTask.progressProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> ov, Number oldProgress, Number newProgress) {
System.out.println("Progress changed");
controller.percentage.setText("Progress changed:" + currentDownload);
}
});
downloadingFilesTask.stateProperty().addListener(new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue<? extends Worker.State> source, Worker.State oldState, Worker.State newState) {
if (newState.equals(Worker.State.SUCCEEDED)) {
System.err.println("Completed downloading files");
controller.percentage.setText("Progress changed:" + currentDownload);
}
}
});
//progress listeners.
ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(downloadingFilesTask.progressProperty());
bar.visibleProperty().bind(downloadingFilesTask.runningProperty());
controller.progTag.getChildren().clear();
controller.progTag.getChildren().add(bar);
new Thread(downloadingFilesTask).start();
}
class DownloadingFilesTask extends Task<Void> {
#Override
protected Void call() throws Exception {
try {
String fullUrl = "http://s3-us-west-2.amazonaws.com/absprod/media/25/manuals/53454a73d9eda$$53454a73d9f571397049971.mp4";
String destLocation = "C:\\Users\\naresh.repalle\\Desktop\\ABS Test\\53454a73d9eda$$53454a73d9f571397049971.mp4";
File destFile = new File(destLocation);
URL downloadingUrl = new URL(fullUrl);
RandomAccessFile file = null;
InputStream stream = null;
int downloaded = 0;
int size = -1;
try {
// Open connection to URL.
HttpURLConnection connection = (HttpURLConnection) downloadingUrl.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
connection.setConnectTimeout(10 * 1000);
connection.setReadTimeout(10 * 1000);
// Connect to server.
connection.connect();
// Make sure response code is in the 200 range.
if (connection.getResponseCode() / 100 != 2) {
System.err.println("Wrong response code while downloading file." + connection.getResponseCode());
}
// Check for valid content length.
int contentLength = connection.getContentLength();
if (contentLength < 1) {
System.err.println("Wrong file size while downloading file." + contentLength);
}
/*
* Set the size for this download if it hasn't been already set.
*/
if (size == -1) {
size = contentLength;
}
totalFileSize = size;
// Open file and seek to the end of it.
file = new RandomAccessFile(destFile, "rw");
file.seek(downloaded);
stream = connection.getInputStream();
int MAX_BUFFER_SIZE = 1024;
while (true) {
/*
* Size buffer according to how much of the file is left to download.
*/
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1) {
System.out.println("read: " + read);
break;
}
// Write buffer to file.
file.write(buffer, 0, read);
downloaded += read;
currentDownload = downloaded;
stateChanged();
}
} catch (Exception e) {
System.err.println("Exception in Downloading file: " + e.toString());
} finally {
/*
* Change status to complete if this point was reached because downloading
* has finished.
*/
// Close file.
if (file != null) {
try {
file.close();
} catch (Exception e) {
}
}
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
System.err.println("exception in downloading: " + e.toString());
}
}
}
} catch (Exception ex) {
System.err.println("Unable to download file: " + ex);
}
return null;
}
private void stateChanged() {
updateProgress(currentDownload, totalFileSize);
}
}
}
Your SyncService doesn't need to reload the FXML; it just needs to communicate with the existing controller. A simple way to do this would be to just pass a reference to SyncService's constructor:
public class SyncService {
MainSceneController controller ;
public SyncService(MainSceneController controller) {
this.controller = controller ;
}
// ...
public void downloadProjectFiles() throws IOException {
DownloadingFilesTask downloadingFilesTask = new DownloadingFilesTask();
// Remove the following:
// URL location = MainsceneController.class.getResource("mainscene.fxml");
// FXMLLoader fxmlLoader = new FXMLLoader();
// fxmlLoader.setLocation(location);
// fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
// final AnchorPane root = (AnchorPane) fxmlLoader.load(location.openStream());
//get the controller
// final MainsceneController controller = (MainsceneController) fxmlLoader.getController();
// Then code as before
// ...
}
}
I think I would actually do it differently: I don't like the strong coupling between the SyncService and the MainSceneController. I would initialize the progress bar in the MainSceneController, expose the progress as a property in the SyncService and bind to it in the controller. But you should be able to use the simpler approach to get it working.

FragmentDialog loose reference to activity

I am using the support library to create dialogs using fragments.
And i Have the following code to show and dismiss the dialogs:
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d("Create", "Create");
setContentView(R.layout.activity_report);
init();
addListeners();
addhandlerListener();
super.onCreate(savedInstanceState);
}
private void showDialog(final Class<?> classs) {
if (classs.equals(AddressValidateProgress.class)) {
addressValidateProgress = AddressValidateProgress.newInstance();
addressValidateProgress.show(getSupportFragmentManager(), null);
Log.d("counter", "+1");
}
if (classs.equals(GPSSearchProgress.class)) {
showDialog(gpsSearchloadId);
}
}
private void dismissDialog(final Class<?> classs) {
if (classs.equals(AddressValidateProgress.class)) {
FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.remove(addressValidateProgress).commitAllowingStateLoss();
addressValidateProgress = null;
Log.d("super", addressValidateProgressId + ":dismissed");
}
if (classs.equals(AddressChooseDialog.class)) {
FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.remove(addressChooseDialog).commitAllowingStateLoss();
addressChooseDialog = null;
}
if (classs.equals(GPSSearchProgress.class)) {
dismissDialog(gpsSearchloadId);
Log.d("super", gpsSearchloadId + ":dismissed");
}
}
If i start the application in portrait mode i can use the dialogs normally, i can even rotate the screen and the dialogs are reconstructed.
The problem is that if i start the application rotate the screen and click the button that open the dialogs i get an exception:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
Solution found.
It was caused by a static Handler declared

Resources