ImageView not Updating with new URL after activity is reopened - java

there are simple activities A and B. Activity A launches Activity B and i can select an image as profile image, which first I will upload it to the server and then show the image via the received url. At first when I switch to activity B everything works fine, if there is an image already downloaded its shown in the imageview or it will be downloded and shown. in this case if I select other images to upload, its working just fine and the imageview will show the new images. when I exit the activity and relaunch it, the previously downloded image is shown (if any exists), but any new image uploaded to server won't be shown not even drawables. the imageview won't update at all until I exit the activity again and relaunch it, which in this case the previous image uploaded will be shown but again no new image is shown. so to sum it, first time everything works fine, but for the next times the image is loaded properly only one time.
I've been using Glide and Frisco and thought the problem is caused by them but then used simple ImageView and simple connection to download bitmap and it was the same. it works only one time.
I've been testing both on Nokia 6.1 plus Android 9 and Nexus 5x Android 8.1 and emulators with Android 8.1 and Android 9. I've also tried the release build and still the same.In addition, I'm using AndroidX and the strategy to download image and load them is the same as my previous projects and I'd never faced this issue before.
tried these below before and after loading image and it's not working.
with Glide and Frisco the cache is also disabled. and The urls are completely random so they wont even have the chance to cache them.
here is a sample download and load, its just temporary.
image.setImageResource(0);
image.setImageBitmap(null);
image.invalidate();
new Thread(new Runnable() {
#Override
public void run() {
Bitmap bmp = null;
try {
trustEveryone();
URL url = new URL(user.image_address);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Bitmap finalBmp = bmp;
ProfileActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
_profileImage.setImageBitmap(null);
_profileImage.setImageResource(0);
_profileImage.invalidate();
_profileImage.setImageBitmap(finalBmp);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

before using below method, tested it on my backup project before migrating to androidX and it was the same so the problem was not because of androidX
so here is the solution. the activities order : Main->Profile->Gallery->Crop->Back to Profile
to return the results from Crop to Profile I'm using event bus which has to be run on UI thread, so the Activity used to runOnUI... to post the event was CropActivity which was finished after the event is posted, and although I used ProfileActivity.runOnUI ... to load the image when receiving the event from event bus, the whole code was being run on CropActivity so I used another workaround to send results back to previous activity and that solved the problem without the need for invalidate or setting the image to null.

Related

Loading Image in Image View using Glide

I am working on an app which show an image which is loaded from my firebase database. I used Glide for that purpose.
I am using a button, on the click of that button a new activity will open which shows the image fetched from the url. The image load perfectly if url loaded correctly but if I cancelled in between, the app is crashing. Why it is happening and also, Is there any option to save the image in cache using glide, so that It can load it once and show without fetching it from firebase.
Here is my code to display image from url:
public void showImage(){
mStorageRef.child("TimeTable").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
url = uri.toString();
RequestOptions options = new RequestOptions().centerCrop().placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher_round);
Toast.makeText(TimeTable.this, uri.toString(),Toast.LENGTH_SHORT).show();
Glide.with(TimeTable.this).load(url).apply(options).into(image);
}
});
}
Here is the Error log, when I closed the activity before image loaded completely..
Please ask if any further details are required.
You can cache your images loading using Glide. I am referring to the tutorial here where you can learn the basics of image caching using Glide.
Now about the crashing problem, it clearly says that you are trying to load something from an activity which is already destroyed. As you have a firebase listener added where you are loading the image, you need to destroy the listener as you are leaving the activity.
You might consider using onPause, onDestroy functions to handle the remove listener action. Check the removeEventListener function of Firebase.
However, I would recommend using activity scoped versions of the loaders so that Firebase task takes care of these things by itself. Please see the answer here.

How to view an Image View to a linear layout in android dynamically on andorid

I have two activities. One that submits the data and one that shows the submitted data. I am able to add the images to the first activity fine and the data is then stored in a singleton data object with a ArrayList instance called "images".
The problem I have is that when trying to retrieve the images from the image array and display them it crashes the app. I have tried to debug the code and it runs perfectly until you get to the last line:
attachmentLayout.addView(image,imParams);
The Images are stored in the singleton correctly and when you debug it, it shows that they are in fact there.
I tried to figure it out for myself, but I can't find what it is. I am quite new to android programming so help would be much appreciated. I have added my code that tries to get the images below.
if(values.getImage()!=null){
int count = images.size()-1;
for (int x=0;x<=count;x++){
//declare attachments and get image from arraylist<ImageView>
LinearLayout attachmentLayout = (LinearLayout) findViewById(R.id.attachments);
ImageView image;
image = images.get(x);
//set parameters
LinearLayout.LayoutParams imParams =
new LinearLayout.LayoutParams(90,270);
image.setBottom(attachmentLayout.getBottom());
image.setVisibility(View.VISIBLE);
image.isShown();
//add to linear layout
attachmentLayout.addView(image,imParams);
}
}
Edit:
This is the logcat I get when the app restarts after is crashes. I don't believe this is helpful though.
08-24 12:34:18.522 4782-4820/com.example.jules_gribble.test I/Adreno﹕ QUALCOMM build : 065751b,
Build Date : 04/15/15
OpenGL ES Shader Compiler Version: E031.25.03.07
Local Branch :
Remote Branch : quic/LA.BF64.1.2.1_rb2.9
Remote Branch : NONE
Reconstruct Branch : AU_LINUX_ANDROID_LA.BF64.1.2.1_RB2.05.01.00.081.016 + 065751b + NOTHING
Managed to answer my question myself. Turns out it was crashing because I wa overlooking that in the submit activity it was declared
ImageView image = new ImageView(Test.this);
This meant it could not be used in a different activity (Test is the name of the class of the submit activity which will be changed).
To solve this I changed it to
ImageView image = new ImageView(Submitted.this);
where submitted is the name of the submitted activity. I then needed to get the bitmap of the image and set the bitmap to the new imageview.
Bitmap bitmap = ((BitmapDrawable)images.get(x).getDrawable()).getBitmap();
image.setImageBitmap(bitmap);
I found this from HERE.
Hope this will help someone in the future.

Why does it require a reboot after copy/cutting/pasting a file/folder?

I am working on a small File manager to get the hang of things on Android and I have cut/copy/paste operation. It seems to work fine, but I run into issues with pasting things. On my app it is displayed fine, but for it to be recognized by other apps, it requires that I reboot the phone. For example, if I cut/paste an image from the download folder to the DCIM folder, the gallery app does not display that image unless I reboot the whole phone. I am using an algorithm that takes data byte by byte. Its extremely inefficient, but I am not totally sure how to implement a faster algorithm.
Thanks.
No actually you wont need to reboot our phone. When you copy an image and paste it to other location your newly copied media file is not added to the android's ContentResolver. So you should scan your data using the class MediaScannerConnection
Eg:
When you paste a file you have the file right ?
Modify as your wish, this works fine
private void scanImage(File targetLocation) {
// Scans the media to load images
String mimetype = Utility.getMimeType(targetLocation.getAbsolutePath());
if(mimetype.contains("image"))
{
MediaScannerConnection.scanFile(context, new String[] { targetLocation.getPath() }, new String[] { "image/jpeg" }, this);
}
}
UPDATE
Callback should be like
either you can implement OnScanCompletedListener in your class and add unimplemented method, So you can pass this as callback OR you can use
OnScanCompletedListener listener = new OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
// you will get the callback here
}
};
and pass listener as callback

Eclipse Java Memory Error: Heap. Developing in Android with Phonegap.

I have a Android App I have developed, It has been created from a successful ios App that was released and works fine. On one device it works correctly, no errors and does not crash. However on another device (newer, newer version of Android, faster processor) it crashes. Here are the memory errors when it crashes.
The app is designed to take a picture and to then use that picture as the background for a canvas, then a screen shot is taken. I can go through this process once, but then if I repeat the process and take another picture, the application crashes on exit of the camera API for the second time. And displays these errors. The application is Developed in Eclipse using Phonegap and Jquery mobile. I am unsure which parts of my code I should post to help this problem, but please feel free to ask if you feel some may be relevant.
Any help is really appreciated.
Okay, if you review my post on why we run out of memory on PhoneGap Android apps:
http://simonmacdonald.blogspot.ca/2012/07/change-to-camera-code-in-phonegap-190.html
You may find some tips when you use the camera.getPicture() command. Other than that I'm currently working on fixing some of these Camera issues by bringing everything in house instead of firing a camera intent.
You can make such trick.... To set picture as background use...
public void setbg(){
String pathName = Environment.getExternalStorageState() + "scm_pic.jpg";
Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
BitmapDrawable bd = new BitmapDrawable(res, bitmap);
View view = findViewById(R.id.container);
view.setBackgroundDrawable(bd);
}
And then when you don't need this picture or want to #Override onPause methods or to switch another activity use...
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
To use it in #Override use for examole...
unbindDrawables(findViewById(R.id.container));
System.gc();
if you use camera means Destination type must in FILE_URL in android. because DATA_URI gives base64 string so it gives out of memory error sometime. First u get URL from camera then Convert base64 format using filesystem concepts...

Loading Images from Web Directory, display in ImageView

I am trying to write a simple application that loads images that are stored in a web directory I've created. I want the application to grab ALL of the images that are stored in said directory and display them in a layout.
The code below works for only certain type of URLs(mainly tinypic, but not photobucket, imageshack etc) and also not for directories.
I've my image names formatted in sequence like image1.png, image2.png, etc. so that the code snippet and the downloadFile()-method would work.
But, I'm not sure how I would grab all the images from the server simultaneously because this only grabs one image at a time, sets it as a bitmap and then displays it in an IV. I'm pretty new to Android so some help in the right direction would be appreciated.
public class NewWallpapersActivity extends Activity {
ImageView imView1;
String imageUrl="http://i133.photobucket.com/albums/q44/slimjady/Wallpapers";
Random r= new Random();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.newwallpapers);
Button bt3= (Button)findViewById(R.id.get_imagebt);
bt3.setOnClickListener(getImgListener);
imView1 = (ImageView)findViewById(R.id.IV1);
}
View.OnClickListener getImgListener = new View.OnClickListener(){
public void onClick(View view) {
//i tried to randomize the file download, in my server i put 4 files with name like
//png0.png, png1.png, png2.png so different file is downloaded in button press
int i =r.nextInt(4);
downloadFile(imageUrl+"png"+i+".png");
Log.i("im url",imageUrl+"png"+i+".png");
}
};
Bitmap bmImg;
void downloadFile(String fileUrl){
URL myFileUrl = null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
imView1.setImageBitmap(bmImg);
} catch (IOException e) {
String exception = "Erro: An Exception Was Thrown";
Toast errortoast = Toast.makeText(this, exception, Toast.LENGTH_SHORT);
errortoast.show();
e.printStackTrace();
}
}
}
Here are some thoughts on this one:
Displaying all Images
Since you want to display all Images from within a single folder, I would suggest you to have a Directory-Activity, which displayes all the images in the given directory and one Image-Activity which displays only one single Image.
To proper present this I would suggest using a GridView to display all the Images and a normal Activity with a full-screen ImageView to display the single Image.
You could also use the Gallery-widget to "combine" both those ideas.
Not letting the user wait
One of the bigger problems with your approach is, that the images are getting downloaded on the UI-Thread.
Depending on the size of all or on single image and the available connection-speed, Downloading the image can take a while. While the images are getting downloaded, the UI-Thread will wait for your downloadStuff()-method to return and the UI will freeze. This might create the illusion that your App just crashed.
So, you'll want to do the downloading in a separate thread. Android has a handy wrapper for this called an AsyncTask.
As a little bonus to show your user that the process might take a while you can use a ProgressDialog to illustrate this (on the UI-Thread).
Knowing whats in a directory
Now we come to the point where we have to face some limitations. If you want to use Picture-Hosters like the ones you listed above, you'll need to check if they offer you an API (or something equal) to get a list of Images (or their URLs) from a certain directory/album (look for a "API"-link on the front-page).
If you host the images on your own Server, you should be able to create a little PHP-script (or whatever script/programming language you prefer), which then lists all image-files in the directory and presents them in an easy-to-parse way (either JSON or XML).
This should enable you to get a list of URLs to the Image-files you want to display.

Categories

Resources