Error while setting bitmap image to ImageView - android

I am creating a to send image from java server to android client.
Here is my android code:
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.237.1", 6666);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
// dataOutputStream.writeUTF(textOut.getText().toString());
String base64Code = dataInputStream.readUTF();
Log.d("String", ":" + base64Code);
//
byte[] decodedString;
decodedString = Base64.decode(base64Code);
Log.d("Ds",""+decodedString);
Log.d("St--", ":" + decodedString.length);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inMutable=true;
bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
Drawable ob=new BitmapDrawable(getResources(),bitmap);
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setBackgroundDrawable(ob);
/*//imageView.setImageBitmap(bitmap);
ByteArrayInputStream input=new ByteArrayInputStream(decodedString);
bitmap=BitmapFactory.decodeStream(input);
imageView.setImageBitmap(bitmap);*/
Log.d("Bitmap",""+bitmap);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", "" + e);
}
}
I have encoded the byte array in java usung apache common codec and decoded in android program.
The error I am getting is it gives NullPointeException at imageView.setBackgroundDrawable (ob);.
What is the error in this code??

You need to do it like this:
private class MyAsyncTask extends AsyncTask<Void, Void, Bitmap> {
#Override
protected Bitmap doInBackground(Void... params) {
try {
socket = new Socket("192.168.237.1", 6666);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
// dataOutputStream.writeUTF(textOut.getText().toString());
String base64Code = dataInputStream.readUTF();
Log.d("String", ":" + base64Code);
//
byte[] decodedString;
decodedString = Base64.decode(base64Code);
Log.d("Ds",""+decodedString);
Log.d("St--", ":" + decodedString.length);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inMutable=true;
bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
return bitmap;
/*//imageView.setImageBitmap(bitmap);
ByteArrayInputStream input=new ByteArrayInputStream(decodedString);
bitmap=BitmapFactory.decodeStream(input);
imageView.setImageBitmap(bitmap);*/
Log.d("Bitmap",""+bitmap);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", "" + e);
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
Drawable ob =new BitmapDrawable(getResources(), bitmap);
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setBackgroundDrawable(ob);
} else {
// error
}
}
}

You can,t perform UI operations from background thread. They need to be performed in the ui thread. So try and perform thi operationn in onPostExecute().

Related

print pdf/ image file with Thermal printer android [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to print the image with a thermal printer which is stored in phone local storage. But it is printing a very small image. can anyone suggest me how to print the image via a thermal printer( Ethernet)
code:
MainActivity.java:
public class MainActivity extends Activity {
Socket socket = null;
RelativeLayout relativeLayout;
String htmlDocument;
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView =(WebView)findViewById(R.id.myWebView);
relativeLayout = (RelativeLayout) findViewById(R.id.print);
htmlDocument = "<html><body><h2>Basic HTML Table</h2><table style=\"width:30%\"><tr><th>Firstname</th><th>Lastname</th><th>Age</th></tr><tr><td>Jill</td><td>Smith</td><td>50</td></tr><tr><td>Eve</td><td>Jackson</td><td>94</td></tr><tr><td>John</td><td>Doe</td><td>80</td></tr></table></body></html>";
myWebView.loadData(htmlDocument, "text/HTML", "UTF-8");
new Timer().schedule(new TimerTask() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void run() {
laytooimag();
// this code will be executed after 2 seconds
}
}, 5000);
}
public void laytooimag() {
relativeLayout.setDrawingCacheEnabled(true);
relativeLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
relativeLayout.layout(0, 0, relativeLayout.getMeasuredWidth(), relativeLayout.getMeasuredHeight());
relativeLayout.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(relativeLayout.getDrawingCache());
relativeLayout.setDrawingCacheEnabled(false);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
Log.v("Tag_file",""+f);
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
new EthernetPrint()
.execute(resultdata);
}
private class EthernetPrint extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
resultdata = params[0];
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// socket = new Socket(r.printerDetails.ipAddress, r.printerDetails.port);
socket = new Socket("192.168.1.23", 9100);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
byte[] printformat = new byte[]{0x1B, 0x21, 0x03};
DOS.write(printformat);
Printerinterface bb = new Printerinterface(getApplicationContext(), "Ethernet", null, DOS);
Log.v("Tag_d",""+"ethdoin");
printKot_invoice(bb);
resultdata = "Executed";
DOS.flush();
DOS.close();
socket.close();
} catch (IOException e) {
resultdata = "";
e.printStackTrace();
}
return resultdata;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
//printKot_invoice();
}
public void printKot_invoice(Printerinterface bb) {
bb.printPhoto(R.drawable.testimg);
}
}
Printerinterface.java:
public class Printerinterface {
public void printPhoto(int img) {
try {
File image = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
Bitmap bitmap = decodeFile(image,100,100);
if(bitmap!=null){
byte[] command = Utils.decodeBitmap(bitmap);
_outputstream().write(PrinterCommands.ESC_ALIGN_CENTER);
printText(command);
}else{
Log.e("Print Photo error", "the file isn't exists");
}
} catch (Exception e) {
e.printStackTrace();
Log.e("PrintTools", "the file isn't exists");
}
}
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to000
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}
catch (FileNotFoundException e) {}
return null;
}
}
If I did not decode the image, it is showing the error like image width and heights are large.

load image from URL and save on memory in android

How to load image from URL and save that on memory of device in android? Dont say me use Picasso or oser laibrary.
I need to:
If device get internet conection I load image to ImageView from url and save it on memory of device, else I need to load one of save image to imageView. Thank`s for helps
P.S. Sorry me, I can make some mistakes in question because I don`t very good know English.
This my class:
public class ImageManager {
String file_path;
Bitmap bitmap = null;
public Bitmap donwoaledImageFromSD() {
File image = new File(Environment.getExternalStorageDirectory().getPath(),file_path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
return bitmap;
}
private void savebitmap() {
File file = new File("first");
file_path = file.getAbsolutePath();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90,fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchImage(final String url, final ImageView iView) {
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... iUrl) {
try {
InputStream in = new URL(url).openStream();
bitmap = BitmapFactory.decodeStream(in);
savebitmap();
} catch (Exception e) {
donwoaledImageFromSD();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (iView != null) {
iView.setImageBitmap(result);
}
}
}.execute(url);
}
}
Try to use this code:
Method for loading image from imageUrl
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
return imageBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And You should use it in a separate thread, like that:
new Thread(new Runnable() {
#Override
public void run() {
try {
Bitmap bitmap = getBitmapFromURL(<URL of your image>);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
But using Picasso - indeed a better way.
Update:
For saving Bitmap to file on external storage (SD card) You can use method like this:
public static void writeBitmapToSD(String aFileName, Bitmap aBitmap) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
File sdPath = Environment.getExternalStorageDirectory();
File sdFile = new File(sdPath, aFileName);
if (sdFile.exists()) {
sdFile.delete ();
}
try {
FileOutputStream out = new FileOutputStream(sdFile);
aBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
Remember that You need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
for it.
And for loading `Bitmap` from file on external storage You can use method like that:
public static Bitmap loadImageFromSD(String aFileName) {
Bitmap result = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
FileInputStream fis = new FileInputStream(new File(Environment.getExternalStorageDirectory(), aFileName));
result = BitmapFactory.decodeStream(fis);
fis.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "loadImageFromSD: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
You need
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
to do this.
Update 2
Method getBitmapFromURL(), but ImageView should be updated from UI thread, so You should call getBitmapFromURL(), for example, this way:
new Thread(new Runnable() {
#Override
public void run() {
try {
final Bitmap bitmap = getBitmapFromURL("<your_image_URL>");
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
I had this same issue and I hope this helps. First, To download Image from URL into your app, use the code below:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
In order for the image to be displayed inside the app, use the method below in your onCreate method:
new DownloadImageTask((ImageView) -your imageview id-)
.execute(-your URL-);
In order for the image to be saved INTERNALLY inside the app/phone, use the code below:
#SuppressLint("WrongThread")
protected void onPostExecute(Bitmap result) {
if (result != null) {
File dir = new File(peekAvailableContext().getFilesDir(), "MyImages");
if(!dir.exists()){
dir.mkdir();
}
File destination = new File(dir, "image.jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
bmImage.setImageBitmap(result);
}
}
To load the image from the internal storage, use the code below:
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "image.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.businessCard_iv);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
Things to note: 1. path is the a string containing the path of the file. 2. "image.jpg" is the file name so ensure that matches with yours. 3. "MyImages" is a folder in your path which contains the actual saved image.

Why can't I retrieve FaceBook profile pic in Android?

I am trying to retrieve my FaceBook Profile pic using a Url in Android. I am not able to retrieve any image. I have no error logs as such but I get the following Log.
04-05 04:14:41.005: D/skia(2987): --- SkImageDecoder::Factory returned null. I am posting the codes. Please tell me step by step what am I doing wrong.
final ImageView photoImageView=(ImageView)findViewById(R.id.imageView1);
AsyncTask<Void, Void, Bitmap> t = new AsyncTask<Void, Void, Bitmap>(){
protected Bitmap doInBackground(Void... p) {
Bitmap bm = null;
try {
URL aURL = new URL("http://graph.facebook.com/+"id"+/picture?type=small");
URLConnection conn = aURL.openConnection();
conn.setUseCaches(true);
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
// photoImageView.setImageBitmap(bm);
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
protected void onPostExecute(Bitmap bm){
// Drawable drawable = new BitmapDrawable(getResources(), bm);
photoImageView.setImageBitmap(bm);
// photoImageView.setBackgroundDrawable(drawable);
}
};
t.execute();
Try this below code, This is perfectly working for me.
try {
URL image_value = new URL("http://graph.facebook.com/"+ user.getId()+ "/picture?type=large");
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
profile_pic.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL aURL = new URL("https://graph.facebook.com/"+id+"/picture?type=small");
Try this.
And if id is integer convert to string
And also not http , try https

Downloaded image can not be displayed

I previously worked on fetching image from sd card displaying it in a list view, that worked using:
imgView.setImageURI(Uri.parse(ImagePath));
Now, I am trying to display image from URL, with the following lines but the image is not displayed in the list view, the following are the lines used:
imgView.setImageBitmap(getBitmapFromURL(ImagePath));
Where, getBitmapFromURL is:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
There is no exception displayed, the image just not get displayed.
Need of an urgent solution....
Thanks,
This is a synchronous loading.(Personally I would not use this cause if there are so many Image to be loaded, the apps is a bit laggy)..
URL url = new URL(//your URL);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);//your imageview
If I were you I would study Async or the lazy adapter..
EDIT
I forgot where I got these code (well thank you for a wonderful code author)
Here it is
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch(Exception ex) {return null;}
}
public enum BitmapManager {
INSTANCE;
private final Map<String, SoftReference<Bitmap>> cache;
private final ExecutorService pool;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
private Bitmap placeholder;
BitmapManager() {
cache = new HashMap<String, SoftReference<Bitmap>>();
pool = Executors.newFixedThreadPool(5);
}
public void setPlaceholder(Bitmap bmp) {
placeholder = bmp;
}
public Bitmap getBitmapFromCache(String url) {
if (cache.containsKey(url)) {
return cache.get(url).get();
}
return null;
}
public void queueJob(final String url, final ImageView imageView,
final int width, final int height) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (msg.obj != null) {
imageView.setImageBitmap((Bitmap) msg.obj);
} else {
imageView.setImageBitmap(placeholder);
Log.d(null, "fail " + url);
}
}
}
};
pool.submit(new Runnable() {
public void run() {
final Bitmap bmp = downloadBitmap(url, width, height);
Message message = Message.obtain();
message.obj = bmp;
Log.d(null, "Item downloaded: " + url);
handler.sendMessage(message);
}
});
}
public void loadBitmap(final String url, final ImageView imageView,
final int width, final int height) {
imageViews.put(imageView, url);
Bitmap bitmap = getBitmapFromCache(url);
// check in UI thread, so no concurrency issues
if (bitmap != null) {
Log.i("inh","Item loaded from cache: " + url);
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageBitmap(placeholder);
queueJob(url, imageView, width, height);
}
}
private Bitmap downloadBitmap(String url, int width, int height) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
url).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
Log.i("nandi2 ako", ""+bitmap);
cache.put(url, new SoftReference<Bitmap>(bitmap));
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Now to call it
String fbAvatarUrl = "//Your URL";
BitmapManager.INSTANCE.loadBitmap(fbAvatarUrl, //Your ImageView, 60,60);
//60 60 is my desired height and width
I encountered this kind problem before, you can refer to this thread, if no luck, try my code,
public static Bitmap loadImageFromUrl(String url) {
URL m;
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i,1024 * 8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len = bis.read(buffer)) != -1){
out.write(buffer, 0, len);
}
out.close();
bis.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = out.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
return bitmap;
}

How can I fetch a large image from a url?

I used the code below to fetch the image from a url but it doesn't working for large images.
Am I missing something when fetching that type of image?
imgView = (ImageView)findViewById(R.id.ImageView01);
imgView.setImageBitmap(loadBitmap("http://www.360technosoft.com/mx4.jpg"));
//imgView.setImageBitmap(loadBitmap("http://sugardaddydiaries.com/wp-content/uploads/2010/12/how_do_i_get_sugar_daddy.jpg"));
//setImageDrawable("http://sugardaddydiaries.com/wp-content/uploads/2010/12/holding-money-copy.jpg");
//Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
//imgView.setImageDrawable(drawable);
/* try {
ImageView i = (ImageView)findViewById(R.id.ImageView01);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://sugardaddydiaries.com/wp-content/uploads/2010/12/holding-money-copy.jpg").getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
System.out.println("hello");
} catch (IOException e) {
System.out.println("hello");
}*/
}
protected Drawable ImageOperations(Context context, String string,
String string2) {
// TODO Auto-generated method stub
try {
InputStream is = (InputStream) this.fetch(string);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
You're trying to download the Large Image from within the UI Thread....This will cause an ANR (Application not Responding)
Use AsyncTask to download the images, that way, a seperate thread will be used for the download and your UI Thread wont lock up.
see this good example that loads image from server.
blog.sptechnolab.com/2011/03/04/android/android-load-image-from-url/.
If you want to download the image very quickly then you can use AQuery which is similar to JQuery just download the android-query.0.15.7.jar
Import the jar file and add the following snippet
AQuery aq = new AQuery(this);
aq.id(R.id.image).image("http://4.bp.blogspot.com/_Q95xppgGoeo/TJzGNaeO8zI/AAAAAAAAADE/kez1bBRmQTk/s1600/Sri-Ram.jpg");
// Here R.id.image is id of your ImageView
// This method will not give any exception
// Dont forgot to add Internet Permission
public class MyImageActivity extends Activity
{
private String image_URL= "http://home.austarnet.com.au/~caroline/Slideshows/Butterfly_Bitmap_Download/slbutfly.bmp";
private ProgressDialog pd;
private Bitmap bitmap;
private ImageView bmImage;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bmImage = (ImageView)findViewById(R.id.imageview);
pd = ProgressDialog.show(this, "Please Wait", "Downloading Image");
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { image_URL });
// You can also give more images in string array
}
private class DownloadWebPageTask extends AsyncTask<String, Void, Bitmap>
{
// String --> parameter in execute
// Bitmap --> return type of doInBackground and parameter of onPostExecute
#Override
protected Bitmap doInBackground(String...urls) {
String response = "";
for (String url : urls)
{
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
// Only for Drawable Image
// try
// {
// URL url = new URL(image_URL);
// InputStream is = url.openStream();
// Drawable d = Drawable.createFromStream(is, "kk.jpg");
// bmImage.setImageDrawable(d);
// }
// catch (Exception e) {
// // TODO: handle exception
// }
// THE ABOVE CODE IN COMMENTS WILL NOT WORK FOR BITMAP IMAGE
try
{
URL m = new URL(image_URL);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i, 1024*8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[4096];
while((len = bis.read(buffer)) != -1)
{
out.write(buffer, 0, len);
}
out.close();
bis.close();
byte[] data = out.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
catch (Exception e)
{
e.printStackTrace();
}
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result)
{
if(result!=null)
bmImage.setImageBitmap(result);
pd.dismiss();
}
}
}

Categories

Resources