Android: ImageView load from URL - android

Tried many ways in the internet but my imageView still display blank of the image.
Wish to retrieve the image from url (download or refer it) but seems I missed out something.
I have activated the INTERNET permission in manifest.
icon.setImageResource(R.drawable.portrait_user);
try {
URL url = new URL("https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/t1.0-1/c0.0.50.50/p50x50/1499583_10202305028778787_1063740680_n.jpg");
InputStream content = (InputStream)url.getContent();
Bitmap d = BitmapFactory.decodeStream(content);
icon.setImageBitmap(d);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Doing network I/O on the main application thread like this will crash your app on Android 4.0+.
Most likely, you will be better served using a third-party library that can download the image for you in the background and update the ImageView when it is ready. Picasso and Universal Image Loader are two of the more popular libraries for this.

Related

Passing an image from webview to application (IOS and Android)

I'm building hybrid applications that rely on 2-way communication between javascript in a webview and the hosting application.
Attitudes differ somewhat as in IOS the JS can send a message to swift (using WKWebView), that listens through
userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage)
when implementing the WKScriptMessageHandler protocol,
whereas in Android the JS can actually call an Android method that has #JavascriptInterface annotation, after calling addJavascriptInterface().
Both approaches are OK for me, as I'm passing around data using JSON strings. Question is, what if I need to pass a media file, say an image or video, from the web page to the application? should I just pass a bitmap inside the json? Seems a little naive... recommendations?
edit: when passing an image from the application to the webpage I save the file to the file system and send the filename to the webview. Can it be done the other way around? Can javascript save to the hosting mobile device file system?
You have to host(in case of webapp) or store(in case of mobile app) the image and pass the image url, not exactly the image.
Almost all api that uses images bitmap also takes image url.
regards
Ashish
To answer your second question which is there are comments, use the following code.
Here the html content is your binary content:
FileWriter imageFileWriter = null;
BufferedWriter imageBufferedWriter = null;
ABOUtil.createDir(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
File imageFileDir = new File(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
String imageName = "/finalimage"+ filename + jpg
File mimageFile = new File(imageFileDir, imageName);
try {
imageFileWriter = new FileWriter(mimageFile, false);
imageBufferedWriter = new BufferedWriter(imageFileWriter);
StringBuilder sb = new StringBuilder();
sb.append(htmlContent);
sb.append(scriptInjectJavascript(lstimageNameValue));
imageBufferedWriter.write(sb.toString());
imageBufferedWriter.close();
return mimageFile;
}
catch (IOException e) {
MAFLogger.e("", "", e);
}
finally{
if(imageFileWriter!=null)
try {
imageFileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
if(imageBufferedWriter!=null)
try {
imageBufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
}

Clear BitMap Cache - koush ion

i would like to clear bitmap cache but i am not sure how to clear the bit map .
I am using Koush Ion library to load the picture
try {
bitmap = Ion.with(context).load(URLimage).withBitmap().asBitmap().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i need to clear the bitmap cache everytime i click on a button.
Thanks in advance
Use Ion.getDefault(context).getCache().clear() to clear the file cache.
Use Ion.getDefault(context).getBitmapCache().clear() to clear the in-memory bitmap cache.
See the source for the respective methods at:
https://github.com/koush/AndroidAsync/blob/master/AndroidAsync/src/com/koushikdutta/async/util/FileCache.java#L292
https://github.com/koush/ion/blob/master/ion/src/com/koushikdutta/ion/bitmap/IonBitmapCache.java#L63
Ion.dump() will NOT clear the cache. It will simply print some debug information to the log. You can look up the source code for it, too.
try this may help,,i used this code for clearing my network data cache;
Ion.getDefault(context).configure().getResponseCache().clear()

How to set a background template to a pdf using iText library in android?

I wanna set a background Template(image) in my pdf that generated by iText Library,something like this:
Click too see the image
I tried to use something like the code below:
PdfReader reader = new PdfReader("./assets/sarbargandroid.pdf");
PdfImportedPage page = writer.getImportedPage(reader, 1);
PdfContentByte cb = writer.getDirectContent();
cb.addTemplate(page, 0.0, 0.0);
but it did not work in android because .addtemplate() methode needs some awt library!
and I tried addimage stuff like this:
private void setBackground(Chapter document) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.sarbarg);
bitmap.compress(Bitmap.CompressFormat.JPEG , 100, stream);
Image img;
try {
img = Image.getInstance(stream.toByteArray());
img.setAbsolutePosition(0, 0);
document.add(img);
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But it did't work correctly because the image does not fit the page and it create a pdf like this:
Click too see image
How can I do this correctly? anyone help me??
There are several things wrong with your question and that may explain why nobody answers. I'll tell you what's wrong and then maybe you can create a new question.
You say:
it did not work in android because .addtemplate() methode needs some awt library!
If the addTemplate() method needs an AWT library, then you are using iText. When working on Android, you should use iTextG: http://itextpdf.com/product/itextg
You are using PdfReader which makes people assume that you want to add a background image to an existing document. This would imply that you use PdfStamper, yet your code looks like you're using PdfWriter. That's a contradiction.
Your setBackground() method takes a Chapter as parameter to which you add an image. This is counter-intuitive:
- If you'd want to add a background image to an existing document, you'd never use the Chapter object.
- If you'd want to add a background image to every page of a PDF that is created from scratch, you'd use a page event.
Another major problem is that you create the image and add it as-is. You didn't scale it to fit the page.
Also: if you add an image in the background of an existing PDF. Parts of that image may be covered by opaque shapes that are present in the original document.

how to make Android ImageView downloading image gradually

I am building an application that downloads and displays several images. Everything is going well.
But i want it display an image as soon as it downloading. Not when its done downloading. I'm pretty sure it's called something like Interlaced, since i use PNGs.
This is part of code i've done to download and display an image :
private class DownloadTask extends AsyncTask<String, Integer, Bitmap> {
#Override
protected void onPostExecute(Bitmap result) {
ivGambar.setImageBitmap(result);// ivGambar is an ImageView
pbDetail.setVisibility(View.INVISIBLE);
}
#Override
protected Bitmap doInBackground(String... pa) {
try {
return BitmapFactory.decodeStream((InputStream) new URL(pa[0])
.getContent());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Is it can be done in Android? How?
Thank you.
I don't know exactly, but you can try to read progressively from the URL and then decode the stream even if it is incomplete, then doing it as you read from the stream, storing it in a buffer.
You can use URL.openStream() to get the stream, copy progressively the contents in a byte array (growing it if needed) and then use BitmapFactory.decodeByteArray to get the decoded partial bitmap (if the data is enough of course).
You could even use ByteArrayOutputStream as a buffer.
Be careful not to do this too often as it may slow down everything massively.

How to prevent android app from crashing when a file has not been found using openFileInput

I want to react to a situation that no file has been found using FileInputStream. When i ran an app that loads a file that doesn't exist it opens an android popup with force close. I would like to react to the situation by changing a text in a text view and saying that the file has not been found. i tried changing the exceptions to change a text view and show that a file has not been found and the app still crashes.
Here is the piece of code:
FileInputStream fis = null;
String collected = null;
try {
fis = openFileInput("test");
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
tv.setText(collected);
To ensure that an Android application does not force-close, your options are: a) do not do anything that will cause an exception, b) catch your exception with your own try/catch block, c) install an application level uncaught exception handler. Option a is not too feasible, c is not very helpful, and based on your code snippet you seem to be trying b -- however there appears to be another exception that you're not catching with this. The contents of logcat will tell you what exception, and the stack trace will lead to a point in your code which needs the try/catch.

Categories

Resources