Inputstream failed to connect to a URL - android

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.

Related

Why is Android file creation suddenly failing when it worked on Android 11 previously?

In the last few days, my Android app is suddenly failing to download files from a web server to store in the app. This is the same for all users I have contacted. It was previously working in Android 11, so it's something that has only just changed. It's a (free) niche app for UK glider pilots to process NOTAMS, and has relatively large number of users who I don't want to let down.
The published app uses getExternalFilesDir(null) to return the directory in which to store the downloaded files, with android:requestLegacyExternalStorage set to "true" in the manifest.
I changed getExternalFilesDir(null) to getFilesDir() in Android Studio since that's what I understand should now be used for internal app data files. This returns /data/user/0/(my package name)/files. I'm running the Pixel 2 API 30 emulator for debugging, and the File Explorer shows that /data/data/(my package name)/files directory has been created. Everything I've read on here says that this is what is supposed to happen and it should all work. However no file was created when I attempted the download.
I changed android:requestLegacyExternalStorage to "false", and this time a file was created as expected. However it was empty and the download thread was giving an exception "unexpected end of stream on com.android.okhttp.Address#89599f3f".
This is the relevant code in my DownloadFile class which runs as a separate thread (comments removed for compactness):
public class DownloadFile implements Runnable
{
private String mUrlString;
private String mFileName;
private CountDownLatch mLatch;
public DownloadFile(String urlString, String fileName, CountDownLatch latch)
{
mUrlString = urlString;
mFileName = fileName;
mLatch = latch;
}
public void run()
{
HttpURLConnection urlConnection = null;
// Note for StackOverflow: following is a public static variable defined in the main activity
Spine.mDownloadStatus = false;
try
{
URL url = new URL(mUrlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.connect();
File file = new File(Spine.dataDir, mFileName);
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0; // used to store a temporary size of the buffer
while ((bufferLength = inputStream.read(buffer)) > 0)
{
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
Spine.mDownloadStatus = true;
}
// catch some possible errors...
catch (IOException e)
{
Spine.mErrorString = e.getMessage();
}
if (urlConnection != null)
urlConnection.disconnect();
// Signal completion
mLatch.countDown();
}
}
I now believe the problem lies with the URL connection, rather than the changes to local file storage access which is what I first thought. Incidentally, if I enter the full URL into my web browser the complete text file is displayed OK, so it's not a problem with the server.
The problem has been narrowed down to changes to the functionality of the website that hosts the data files to be downloaded. It's been made https secure and they are currently working on further changes.
I temporarily moved the hosting to my own website in Android Studio and everything worked so it's down to those website changes and nothing to do with my code (at least it may need changing later to support the upgrade to the main hosting site).
Thanks to all for responding.

How to access lottie files outside res folder programatically

I don't know this is a duplicate question or not, but i tried to search similar question according to this.
I want to access the file that located outside /res folder programatically.
I already know if we want to access /res folder, then we just call it's id like getString(), getDrawable() etc.
But in my case, I want to access anim_empty.json programatically. How to do that?
Try following method for accessing JSON data:
public static String loadJSONFromAsset(Context mContext, String fileName) {
String json;
try {
InputStream is = mContext.getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Modify the method according to your usage..
In the truth, i just wanted to call the Lottie animation files, i thought that i need to write script like the answer above but all i need is just these (Getting Started With Animations in Android Using Lottie — Kotlin and enter link description here):
lottieAnimationView = findViewById(R.id.empty_hstanim);
lottieAnimationView.setAnimation("anim_empty.json");
lottieAnimationView.playAnimation();
Thanks for the kind answer anyway!

loading full image from url into image view with any image loading library

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

Image load in webview or not?

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.

OutOfMemoryError on batch image download

I have a large list of objects, all of whom have a path to their image "ex. http://www.google.com/image.jpg" and I need to download the image and save the drawable to the object..
I was using AsyncTask, but even if I use my own threads I always end up with 'OutOfMemoryError' at some arbitrary point in the list. The images are never larger than 82Kb (Is this too big for android tablets?) in size, but I think the sheer number of images is causing the process as a whole to fail.
Here is what I'm currently doing.
class DownloadImageTask extends AsyncTask<ArrayList<Item>, Void, Void> {
private static int num =1;
#Override
protected Void doInBackground(ArrayList<Item>... items) {
try {
if(items.length == 0)
return null;
HttpURLConnection connection;
InputStream input;
for(ArrayList<Item> itemlist : items) {
for(Item i : itemlist) {
Log.d(JusTouchMenu.TAG,"[Item]Image request to url:"+i.getImagePath());
try {
connection = (HttpURLConnection)new URL(i.getImagePath()).openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
input = connection.getInputStream();
i.setImage(new BitmapDrawable(BitmapFactory.decodeStream(input)));//Requires a drawable
connection.disconnect();
} catch(Exception e) {Log.e(JusTouchMenu.TAG,"[Item]Unable to download image # '"+i.getImagePath()+"'",e);}
Log.v(JusTouchMenu.TAG, "[Item]Image decoded # '"+i.getImagePath()+"' #"+num++);
for(Tag pt : i.tags()) {
Log.d(JusTouchMenu.TAG,"[Item->Tag]Image request to url:"+pt.getImagePath());
try {
connection = (HttpURLConnection)new URL(pt.getImagePath()).openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
input = connection.getInputStream();
pt.setImage(new BitmapDrawable(BitmapFactory.decodeStream(input))); //Requires a drawable
connection.disconnect();
} catch(Exception e) {
Log.e(JusTouchMenu.TAG,"[Item->Tag]Unable to download image # '"+i.getImagePath()+"'",e);
}
Log.v(JusTouchMenu.TAG, "[Item->Tag]Image decoded # '"+pt.getImagePath()+"' #"+num++);
}
}
}
} catch(Exception e) {
Log.e(JusTouchMenu.TAG,"Error decoding image inside AsyncTask",e);
}
return null;
}
Thanks!
How many of these images are you trying to get at once? How are you using them?
You should probably consider using the capabilities of Gallery or GridView and thereby only be loading the images that are in view at the moment. You can even get fancy and cache them so scrolling is nice and smooth. Trying to load all of the images into an ArrayList when youre not likely to be able to display them all at once is not a mobile friendly approach.
Here are some decent references to caching approaches but you should probably get started with a basic gallery or grid view loading as needed and then add the caching on.
Lazy load of images in ListView
http://code.google.com/p/libs-for-android/wiki/ImageLoader

Categories

Resources