My final year project requires me to develop a mobile application which fetches a number of Json values from a server. This is my first experience in android development but sure learned something’s and enjoyed the experience.
I have managed to develop the following.
1-a json parser class which fetches the value.
2-a class which displays these values.
3-a database where I store the json response.
However I'm one step away from completing my project, I cannot display the response string image address as real images (shame on me).
I need to do the following.
1- Parse the string path of the image and display the response as image.
I have spent most of my time trying to find the solution on the web, stack overflow. But no luck so far.
I need to do something like this in order to display these images together with the text descriptions.
I have now reached the cross roads and my knowledge has been tested.Is what i'm trying to do here posible?.
Who can show me the way? ,to this outstanding platform.
if you have the image url as a string, you can load and save the image using something like this:
try {
Bitmap bitmap = null;
File f = new File(filename);
InputStream inputStream = new URL(url).openStream();
OutputStream outputStream = new FileOutputStream(f);
int readlen;
byte[] buf = new byte[1024];
while ((readlen = inputStream.read(buf)) > 0)
outputStream.write(buf, 0, readlen);
outputStream.close();
inputStream.close();
bitmap = BitmapFactory.decodeFile(filename);
return bitmap;
} catch (Exception e) {
return null;
}
For saving, make sure you have appropriate permissions if you're going to save to sdcard.
if you just want to load the image (without saving):
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
Just make sure you fetch the image in a separate thread or using AsyncTask or else you'll get ANRs!
you can try this ImageDownloader class from google. It´s works nice :)
Is an AsynkTask that handle the download and set the bitmap to an ImageView.
ImageDownloader
Usage:
private final ImageDownloader mDownload = new ImageDownloader();
mDownload.download("URL", imageView);
Related
I have a string which as follows:
String text = "<img src="https://www.google.com/images/srpr/logo3w.png">"
When I do
TextView.setText(Html.fromHtml(text));
I need the image to be displayed in the activity.
I do not want to use a WebView.
Please let me know as to what are the other ways to achieve this.
you have to use asynctask,open connection in doInbackground() set image to textview in onPostExecute()
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL("ur Image URL");
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
Drawable d =new BitmapDrawable(bm);
d.setId("1");
textview.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);// wherever u want the image relative to textview
} catch (IOException e) {
Log.e("error", "Remote Image Exception", e);
}
Hope it will help.
I followed the idea in these below links.
http://www.docstoc.com/docs/120417139/How-To-Implement-Htmlfromhtml-With-Imagegetter-In-Android
http://shiamiprogrammingnotes.blogspot.com/2010/09/textview-with-html-content-with-images.html
You need to define your text in strings.xml
<string name="nice_html">
<![CDATA[<img src='https://www.google.com/images/srpr/logo3w.png'>
]]></string>
Then, in your code:
TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));
I have a database online that gives image file locations and file names
I am trying to update an imageview in an android screen. Here is my code that gets the image and the things I have tried:
// successfully received product details
JSONArray productObj = json.getJSONArray("product"); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// imageview
imageVw = (ImageView) findViewById(R.id.imageView1);
// display data in imageview
//imageStr = "http://somesite.com/images/" + product.getString("imagefile");
imageStr = "file://somesite.com/images/" + product.getString("imagefile");
//imgUri=Uri.parse("file:///data/data/MYFOLDER/myimage.png");
//imgUri=Uri.parse(imageStr);
//imageVw.setImageURI(imgUri);
imageVw.setImageBitmap(BitmapFactory.decodeFile(imageStr));
You can do something like this if you want to get the Bitmap of the image stored on the web. I personally use the library called ImageDownloader. The library is simple to use.
You have to understand that "A URL is a URI but a URI is not a URL. A URL is a specialization of URI that defines the network location of a specific representation for a given resource." so, if your file location is http then you need to make the function like below to get the Bitmap. I use ImageDownloader library because it runs its own thread and also manages some caches for faster image downloads.
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
i have 2 applications. One application act as server and it is created in java and sends continuously screen shot of desktop by using the following code.
public void screenCap() throws IOException, AWTException{
Rectangle captureSize = new Rectangle(lastXpos, lastYpos, 500, 500);
img = robot.createScreenCapture(captureSize);
Robot robot=new Robot();
OutputStream os = null;
BufferedImage image = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "jpg", os);
}
The second application is Android application acts a client application and has to read continuously the above image stream from inputstream.
Could please help me to read the images from inputstream in the client application.
Use Bitmap decodeStream() method of BitmapFactory Class.
public static Bitmap decodeStream (InputStream is)
Since: API Level 1
Decode an input stream into a bitmap. If the input stream is null, or cannot be used to decode a bitmap, the function returns null. The stream's position will be where ever it was after the encoded data was read.
Example:
String urlOfBitmap = ""; // Url of inputstream
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(urlOfBitmap).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
FileInputStream in;
in = ...;
bitmap = BitmapFactory.decodeStream(in);
I am working on an application where I am getting an image from the web server.
I need to save that image in a sqlite database. Maybe it will be saved in a byte[]; I have done this way, taking the datatype as blob, and then retrieving the image from db and showing at imageview.
I am stuck somewhere, however: I am getting null when I decodefrom bytearray
The code I have used is:
InputStream is = null;
try {
URL url = null;
url = new URL(http://....);
URLConnection ucon = null;
ucon = url.openConnection();
is = ucon.getInputStream();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer barb = new ByteArrayBuffer(128);
int current = 0;
try {
while ((current = bis.read()) != -1) {
barb.append((byte) current);
} catch (IOException e) {
e.printStackTrace();
}
byte[] imageData = barb.toByteArray();
Then I have inserted imageData in to the db..
To retrieve the image:
byte[] logo = c.getBlob(c.getColumnIndex("Logo_Image"));
Bitmap bitmap = BitmapFactory.decodeByteArray(logo, 0, logo.length);
img.setImageBitmap(bitmap);
But I am getting the error:
Bitmap bitmap is getting null.
Sometimes, It happens, when your byte[] not decode properly after retrieving from database as blob type.
So, You can do like this way, Encode - Decode,
Encode the image before writing to the database:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream);
mByteArray = outputStream.toByteArray(); // write this to database as blob
And then decode it like the from Cursor:
ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex));
Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);
Also, If this not work in your case, then I suggest you to go on feasible way..
Make a directory on external / internal storage for your application
images.
Now store images on that directory.
And store the path of those image files in your database. So you
don't have a problem on encoding-decoding of images.
I am making an application in android which loads Icon size images from URL
i have tried downloading images using the following code.
One image labeled default.png was downloaded from the given url but there was another image labeled v_1234.jpg is not being downloaded. I dont know whats the problem. it just returns me null for jpg image.
I am not sure that its a problem for .jpg format that my code is not downloading the jpg format images or Its the labeled name problem that due to Underscore (_) in the label makes it not downloadable..
Please help Friends you are professional in that field.
CODE:
URL url = new URL(detail.voucher_image.toString());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.getImageBitmap(bmp);
Thanks alot.
try this code
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
InputStream reader;
reader=conn.getInputStream();
System.out.println("Compressed2!!!"+conn.getContentLength());
int available = reader.available();
int i=0;
int count=0;
int cc=0;
while(reader.read()!=-1){
cc++;
}
System.out.println("available"+cc);
data2 = new byte[cc];
while ((i = reader.read(data2, count, data2.length-count)) != -1) {
count +=i;
cc++;
}
System.out.println("Compressed3!!!");
// reader.read(data2,0,cc);
System.out.println("Compressed!!!");
// printBytes(data1,data2,"after");
System.out.println("length b4!!!"+data2);
System.out.println("data::"+new String(data2));
System.out.println("The length is "+data2.length);
bmp2=BitmapFactory.decodeByteArray(data2, 0, data2.length);
if(bmp2==null)
System.out.println("The bitmap value is null");
iv.setImageBitmap(bmp2);undefined
use the following code to get bitmap from url
public Bitmap imageConvert(String url){
URL aURL = null;
Bitmap bm = null;
try {
final String imageUrl =imgstr.replaceAll(" ","%20");
Log.e("Image Url",imageUrl);
aURL = new URL(imageUrl);
URLConnection conn = aURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(new PatchInputStream(is));
is.close();
}
catch (Exception e) {
Log.e("ProPic Exception",e.getMessage());
}
return bm;
}