I'm using a webview to show image. I used the webview.loadUrl("imagepath"); these code to show image but the webview failed to load the image then i want to show my default image in the webview.
You have to add file:/// before your image Path.
Did you try with something like
// Exemple from asset folder
webview.loadUrl("file:///android_asset/mu_image.jpg");
// From external storage
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
String imagePath = "file://"+ base + "/YOUR_FILE.jpg";
webview.loadUrl(base);
EDIT (after understanding the question ...)
You have to check if your web file exist
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
Then 2 choices :
- The file exists, show it
- Or, show your default image
Source : Check if file exists on remote server using its URL
It is not a good practice to load image in a webview.
The solution is to use some kind of image loader and the best one for your case is VOLLEY. It provides cache and image loading functionality better then any other image loader.
Here is the link.
Related
I am using Picasso for retrieving and showing images in my Android app. To avoid downloading all images over the network I am trying to add some images with the apk file, as sort of a pre-cached set of images. These images are stored in the assets folder and then copied to the Picasso cache folder on installation. This works as expected, but Picasso still download all images through the network and caches them as .0 and .1 files like this:
root#generic_x86:/data/data/com.my.app/files/images_cache #
ls
10.JPG
100.JPG
101.JPG
102.JPG
11.JPG
1f94664dec9a8c205b7dc50f8a6f3b79.0
1f94664dec9a8c205b7dc50f8a6f3b79.1
2.JPG
4621206beccad87a0fc01df2d080c644.0
4621206beccad87a0fc01df2d080c644.1
The *.JPG images are the ones I copied and the others are the Picasso cached images. Is there a way to make Picasso cache these images properly on installation?
If not, are there any other similar libraries that supports this kind of pre-caching?
Update: trying to cache from Assets folder
I tried making a small snippet that is run at first run of the app. The idea is to iterate the files in the given assets folder and fetch those images with Picasso. However, the below does not cache anything, although I end up in the onSuccess() method of the callback. The asset file names are correct. This is also verified by using the wrong folder name, which puts me in the onError() method of the callback.
I also tried loading it into a temporary ImageView, but it did do any difference.
public static boolean cacheImagesFromAssetsFolder(Context context)
{
boolean ok = false;
try
{
String[] images = context.getAssets().list("my_images");
for (String image : images)
{
Picasso.with(context).load("file:///android_asset/my_images/" + image).fetch(new Callback()
{
#Override
public void onSuccess()
{
// This is where I end up. Success, but nothing happens.
}
#Override
public void onError()
{
}
});
}
ok = true;
}
catch (Exception e)
{
e.printStackTrace();
}
return ok;
}
You could use File URI to request the Picasso to pick the image from your asset location instead of n/w.
Picasso.with(activity) //
.load(Uri.fromFile(file)) // Location of the image from asset folder
Update: How to use your own cache
import com.squareup.picasso.LruCache;
import com.squareup.picasso.Util;
LruCache imageCache = new LruCache(context);
Request request = Request.Builder(Uri.fromFile(asset_file), 0, null).build();
String cacheKey = Util.createKey(request, new StringBuilder());
imageCache.set(cacheKey, bitmap_object_of_asset_image);
Picasso.Builder(context)
.memoryCache(imageCache)
.build().load(asset_url).fetch(callback);
I'm downloading an image from a URL and displaying it in an ImageView. I need to download the image at its full original size. I've tried Glide, Picasso and Universal Image Loader with no success. Is there any library or mehod out there to achieve this? I even tried making my own AsyncTask to do it, something like this:
public class ImageLoader extends AsyncTask<Void, Void, Bitmap> {
#Override
protected Bitmap doInBackground(Void... params) {
try {
URL url = new URL(bundle.getString("selectedImage"));
HttpURLConnection conn =
(HttpURLConnection)url.openConnection();
conn.setReadTimeout(6000);
conn.setConnectTimeout(6000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int respose = conn.getResponseCode();
InputStream is = conn.getInputStream();
BufferedInputStream bufferedInputStream = new
BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(bufferedInputStream);
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
but no success. Anyone have anything to help me?
1) Try to use Volley library.
https://developer.android.com/training/volley/request.html#request-image
2) Use WebView instead ImageView
I'm not really sure what you mean by "its full original size". I haven't experienced any automagic scaling of images simply by downloading them.
Maybe you could double-check that you have an appropriate android:scaleType on the target ImageView. You can read more on the different values of the scale type property here: http://developer.android.com/reference/android/widget/ImageView.ScaleType.html
If you want to pan the image, like an "unscaled" web page in the browser (typically when the image is bigger than the screen), you might need to add further logic to manage this. Maybe it could be as easy as having a ScrollView wrap your ImageView (which then would wrap its content, of course).
The error was down to photo bucket giving me a scaled down URL instead I used flikr and on my device I get an image almost identical to my original (Picasso limit is 2048x2048) but on other devices I still seem to get a 1080 x 910 image, will investigate further but it seems the answer is not to use photo bucket
I am getiing a xml content of a page and parsing some URL from that xml which are all images Url.
Then I am making the image to be shown in imageviwer using bitmap. Further I need that image for my next layout design. How can I store the images for further use, can I store the images in drawable folder if I can how to do it. I have mentioned below in the code where I need to save the imageview content to drawable folder..
protected Void doInBackground(String... params) {
try {
url=new URL(UrlLink2) ;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
InputStream isp=urlConnection.getInputStream();
DocumentBuilderFactory DBF=DocumentBuilderFactory.newInstance();
DocumentBuilder Db=DBF.newDocumentBuilder();
doc=Db.parse(isp);
Element rootElem=doc.getDocumentElement();
NodeList itemlist=rootElem.getElementsByTagName("item");
Node currentitem=null;
Node childnode=null;
Node ContentChild=null;
Node CddatatChild=null;
NodeList childnodeList=null;
NodeList CddataList=null;
NodeList ContentChilList=null;
for(int i=0;i<itemlist.getLength();i++){
currentitem=itemlist.item(i);
childnodeList=currentitem.getChildNodes();
for(int j=0;j<childnodeList.getLength();j++){
childnode=childnodeList.item(j);
if(childnode.getNodeName().equalsIgnoreCase("content:encoded")){
ContentChilList=childnode.getChildNodes();
ContentChilList.getLength();
CddatatChild=ContentChilList.item(0);
CddataList=CddatatChild.getChildNodes();
if(CddatatChild.getNodeName().equalsIgnoreCase("#cdata-section")){
GetCddata=CddatatChild.getTextContent().toString();
GetCddata=CddatatChild.getTextContent();
}
}
}
}
}
catch(Exception e){
}
try{
int i=0;
String ss=GetCddata;
Pattern PatternImgURLS = Pattern.compile("(?<=a href=\")(.*?)(?=\")");
Pattern PatternImgname = Pattern.compile("(?<=2014\\/09\\/)(.*?)(?=\\.)");
Matcher Imagematcher = PatternImgURLS.matcher(ss);
Imagematcher.matches();
while (Imagematcher.find()) {
ImgUrl=Imagematcher.toMatchResult().group();
ImageUrls.add(ImgUrl);
i++;
}
for(int count=0;count<ImageUrls.size();count++){
Matcher Namematcher = PatternImgname.matcher(ImageUrls.get(count));
Namematcher.matches();
while (Namematcher.find()) {
String MatchTxt=Namematcher.toMatchResult().group();
String lowerMatchTxt = MatchTxt.toLowerCase();
ImageName.add(lowerMatchTxt);
Log.v("dd",ImageName.get(count));
}
}
Log.v("dd",ImageUrls.get(0));
int t=ImageUrls.size();
Log.v("dd",toString().valueOf(t));
urlConnection.disconnect();
url=new URL(ImageUrls[0]) ;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
InputStream isp2=urlConnection.getInputStream();
bitmap=BitmapFactory.decodeStream(isp2);
urlConnection.disconnect();
}
catch(Exception e){
Log.v("h",e.toString()) ; }
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
Here I am displaying---> Imageview.setImageBitmap(bitmap);
the image in Image viwer
Now how do I store the image from the imageviewer to
drawable folder in andriod is that possiable.
}
}
I recommend not to implement it by yourself, but take well known library that can do it for you. For instance, Picasso has features that should suit your needs. You just pass an URL to it and Picasso will download and save an image in a cache folder for next use:
Picasso.with(context).load(imageUrl).into(imageView);
All you have to do is to parse those image URLs and store them somewhere in memory.
You cannot store/write to res/drawable during run time.But you can change your program to use alternate forms of storage refer this
http://developer.android.com/guide/topics/data/data-storage.html
First of all, you cannot save youur images in res/drawable because once the .apk file has been deployed, the resources cannot change.
But you can use cache directory of your application. It's a non-public folder which belongs to your application and will be deleted on uninstall. furthermore the system can delete from this directory for you if the device is running short of space. It can be accessed via :
context.getCacheDir()
Note though that the docs say:
you should not rely on the system deleting these files for you; you should always have a reasonable maximum, such as 1 MB, for the amount of space you consume with cache files, and prune those files when exceeding that space
If you need a lot of space and would rather use the SD card you can call
getExternalCacheDir()
instead. These will also get removed on uninstall, but the system does not monitor the space available in external storage, so won't automatically delete these files if low on space. If using this option you should also check that external storage is available with
Environment.getExternalStorageState()
Environment.getExternalStorageState()
before attempting to write to it.
I have an array of ParseObjects that are being displayed in a list view. Three text views are loaded into my custom cell, and then there's an image in a ParseFile that should also be loaded. The code I have gets the first cell to load correctly, but in every other cell the image doesn't load. Here's my code:
this.origImage = (ParseFile) posts.get(position).get("image");
try {
Log.d("MyMessage", "Gonna convert image");
this.imageData = this.origImage.getData();
this.options = new BitmapFactory.Options();
this.options.inDither = true;
this.options.inPreferredConfig = Bitmap.Config.ARGB_8888;
this.options.inSampleSize = 8;
this.notConvertedYet = BitmapFactory.decodeByteArray(this.imageData, 0, this.imageData.length, this.options);
if (this.notConvertedYet != null)
this.myBitmap = rotateImage(90, this.notConvertedYet);
else
this.myBitmap = this.notConvertedYet;
mHolder.picImageView.setImageBitmap(this.myBitmap);
Log.d("MyMessage", "Converted image");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
What is happening that's messing it up?
when its bound to a list adapter, what does the
posts.get(position).get("image");
do actually? Is the parse SDK calling a series of AsyncTasks for the network Http GET on the actual URL in parse's file CDN?
You may have to find out more about what its doing because , as is, it may not be very efficient as used by the Adapter.getView()...
Any image loader framework like Volley, like Universal Image Loader, like AQuery will work like an api where you make a call providing the ImageView and the CDN URL for the image as parms. The framework will handle multithreading, pooled Parse.com connections , memCache and fileCache for all images. When using parse to store bitmaps in the file CDN you can still use any of the image loading frameworks.
AQuery sample in an adapter...
ImageView thumbnail=(ImageView)vi.findViewById(R.id.imageView1); // thumb image
mAquery.id(thumbnail).width(110).image($thumbUrl_CDN,
true, true, 0, R.drawable.default_video, null, 0, mAspectRatio);
Your code looks ok.. maybe the reason all the imageViews are black is that the adapter did not have time to get the files loaded across the network and the loop statement did not block the UI thread??
I have an app where I have one banner in the top with News, when I want to put other news I need to open the code and change the resource .jpg and the Link. There is a way to change the banner and the Link (or at least the banner) without modifing the code? Idk maybe uploading it to a webpage or something like this.
thanks
My suggestion would be to upload a banner.jpg to a server that your app can access and dynamically load. This would prevent having to update your app every time you want to change the banner, and makes it cleaner (no excessive Google Play updates). To do actually load the image you can use this code:
ImageView image1 = (ImageView) findViewById(R.id.mybanner);
new Thread(new Runnable(){//create a new thread so we can do network operations
#Override
public void run() {//main thread function
try {//attempt to do network stuff
URL url = new URL("http://your-hosting-site.com/banner.jpg");//create aURL object with the path to your banner
HttpURLConnection con = (HttpURLConnection) url.openConnection();//create the connection object from the url
con.setReadTimeout(15000);
con.setConnectTimeout(15000);
con.setRequestMethod("GET");
con.setDoInput(true);
con.connect();//connect to the server
InputStream is = con.getInputStream();//get the stream so we can read the image
Drawable d = Drawable.createFromStream(is, "MyBanner");//create a drawable from the image
Bitmap bmp = ((BitmapDrawable) d).getBitmap();//create a bitmap from the drawable
final Drawable dS = new BitmapDrawable(Bitmap.createScaledBitmap(bmp, 192, 192, true));//scale it to whatever size you need
con.disconnect();//disconnect now that we're done
runOnUiThread(new Runnable(){//run UI update code on the main thread
#Override
public void run() {
image1.setImageDrawable(dS);//set the imageview to the banner we downloaded
}
});
} catch (MalformedURLException e) {//catch url error
e.printStackTrace();
} catch (IOException e) {//catch io error when downloading
e.printStackTrace();
}
}
}).start();//run the thread
Change "http://your-hosting-site.com/banner.jpg" (line 6) to wherever you uploaded the .jpg, R.id.mybanner (line 1) to the id of your ImageView, and "MyBanner" (line 14) to whatever you want to call the image.
You might want to save your banner to the phone and only check after X days/hours for an update to save data, but that is up to you.