Not able to show image from url in imageview - android

i am trying to fetch an immage from url and setting it into a imageview
the image is small in size and i m using asynctask.
here is the main activity code.
i have tried multiple code from diff site but nothing seems to work.
plz don't suggest volly library.
package com.example.jsonimage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.widget.ImageView;
public class MainActivity extends Activity {
Thread t;
Bitmap bitmap;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv=(ImageView)findViewById(R.id.imageView1);
//runthread();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class loadimage extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL("http://wptrafficanalyzer.in//p//demo1//india.png");
InputStream is=url.openStream();
bitmap= BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//HttpURLConnection huc =(HttpURLConnection)url.openConnection();
//huc.connect();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
iv.setImageBitmap(bitmap);
}
}
}

You are not calling the Async task. On your MainActivity try:
new loadimage().execute();
Also you can use this function to get a bitmap from an URL if yours isn't working:
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;
}
}

Related

Downloading image from server using Android

I am trying to download an image from the internet. Right now the app downloads only part of the image, but then it stops. I am using AsyncTask. Any suggestions on what to do?
The error I get is:
android.os.NetworkOnMainThreadException
at com.example.reynaldo.getimageserver.MainActivity$DownloadAsyncTask.onPostExecute(MainActivity.java:74)
W/System.err: at com.example.reynaldo.getimageserver.MainActivity$DownloadAsyncTask.onPostExecute(MainActivity.java:30)
This is the code I have:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick (View view){
DownloadAsyncTask task = new DownloadAsyncTask();
task.execute(new String[] {"http://res.cloudinary.com/demo/image/upload/w_500,f_auto/sample.jpg" });
}
private class DownloadAsyncTask extends AsyncTask<String, Void, String> {
Bitmap bitmap = null;
InputStream in = null;
#Override
protected String doInBackground(String... urls){
int response = -1;
URL url;
try {
url = new URL("http://res.cloudinary.com/demo/image/upload/w_500,f_auto/sample.jpg");
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
System.out.println("This is wrong");
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
return "success";
}
}
catch (IOException e) {
System.out.println("IOException");
}
return "Download failed";
}
#Override
protected void onPostExecute(String result) {
//try {
bitmap = BitmapFactory.decodeStream(in);
/* in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
ImageView img = (ImageView) findViewById(R.id.image);
img.setImageBitmap(bitmap);
}
}
}
try this if you dont want to use third party library
new DownloadImage(Imageview).execute(YourUrl);
Create a AsyncTask Class
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) 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.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

AsyncTask Execute method showing error

I am trying to call execute method of a GetMethodExample class which has extended AsyncTask, but it is showing me the error that the method execute is undefined for the GetMethodExapmle. Here is my code.
GetMethodExample.java:
package com.shehryar.httpclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
public class GetMethodExample extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website= new URI(params[0]);
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.seperator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
return data;
} catch (Exception e) {
{
e.printStackTrace();
}
}
}
}
return null;
}
}
//MainActivity
HttpExample.java:
package com.shehryar.httpclient;
import java.util.concurrent.ExecutionException;
import com.shehryar.httpclient.R.layout;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HttpExample extends Activity {
TextView httpstuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpstuff=(TextView) findViewById(R.id.tvhttp);
String data;
String website="http://www.google.com";
String extra="";
try {
GetMethodExample obj= new GetMethodExample();
data=obj.execute(website).get(); //Here is the error
httpstuff.setText(data);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
httpstuff.setText("Error:" + e.toString());
} catch (ExecutionException e) {
// TODO Auto-generated catch block
httpstuff.setText("Error:" + e.toString());
}
}
}
data=obj.execute(website).get(); //Here is the error
You are trying to get the data synchronously from an AsyncTask.
First, you start the task:
obj.execute(website);
Then you override onPostExecute() in your AsyncTask to handle the finish:
#Override
public void onPostExecute(String data) {
httpstuff.setText(data);
}
Now somehow you have to give the AsyncTask a reference to your Activity or your TextView so that you can update the UI in onPostExecute().
Go read the reference docs on AsyncTask to understand how the threads interact and which methods run on which thread.
AsyncTask | Android Developers
Thanks to Kris Larson for reply but I got my code working just after restarting eclipse. My code was fine but it was eclipse that was making problems

async task fails when i try to use params

guys. I have this code:
package com.example.httpprogress;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class MyPicGetTask extends AsyncTask<URL , Void, Bitmap>{
InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;
#Override
protected Bitmap doInBackground(URL... urls) {
// TODO Auto-generated method stub
URL url = urls[0];
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
}
}
return bmp;
}
}
it fails, but if i use AsyncTask and describe this class as inner in my activity - it's ok . I can not say the reason because i can not debug, i can see that debug tab opens when it fails but it is not informative for me. Any ideas? Sorry for my noob question
that's my Activity:
package com.example.httpprogress;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class PicActivity extends Activity implements OnClickListener{
InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;
private URL url;
//"http://192.168.0.30/03.jpg";
/*
private class getPicTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... s) {
// TODO Auto-generated method stub
try {
url = new URL("http://192.168.0.93/image.php");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
}
}
return null;
}
};
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pic);
final ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
///////////
try {
url = new URL("http://192.168.0.30/03.jpg");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new MyPicGetTask().execute(url);
image.setImageBitmap(bmp);
}
});
////////////////
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pic, menu);
////////////////
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("httpProgress", "Onclick()");
}
}
Add Log.d() code to doInBackground(...) to print out all exceptions that occur. That should tell you what's going wrong, e.g.
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (Exception e) {
Log.d("Async","EXCEPTION",e);
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
Log.d("Close","EXCEPTION",e);
}
}
When the MyPicGetTask is an inner class it has access to the bmp field. When you pulled it out of your activity it lost access to the bmp class field.
I would suggest reading Google's documentation and following their examples for AsyncTasks.
The bitmap you return from doInBackground should then be used to update your UI in onPostExecute.
protected void onPostExecute(Bitmap bitmap) {
image.setImageBitmap(bitmap);
}
Your asyncTask subclass needs access to image in order to update the UI, so having it as a inner class is one way to make sure it can do this.
Your AsyncTask if you're using it as a public class outside the activity in which you are calling it needs to recieve the context of that activity. There are a number of posts here, here and here that explain how to set this up.

Android load an image from url on button click

I want to load an image from url on a button click & to show it on activity imageview.
how to do it?
I try the following code but it shows the system error like java.net.UnknownHostException Host is on resolved.
package com.v3.thread.fetchImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpException;
import org.apache.http.conn.HttpHostConnectException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainThreadActivity extends Activity {
ImageView img_downloaded;
Button btn_download;
String fileurl = "http://variable3.com/files/images/email-sig.jpg";
Bitmap bmImg;
private ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//new MainThreadActivity().onPreExecute();
img_downloaded = (ImageView) findViewById(R.id.imageView1);
btn_download = (Button) findViewById(R.id.btnLoad);
btn_download.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
downloadfile(fileurl);
} catch (HttpHostConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void AbstractProgressTask() {
dialog = new ProgressDialog(this);
}
protected void onPreExecute() {new MainThreadActivity().onPreExecute();
this.dialog.setMessage("Loading. Please wait...");
this.dialog.show();
}
/**
* method is called after the work is done.
*
* #param success result of #doInBackground method.
*/
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
// automatically done on worker thread (separate from UI thread)
protected Boolean doInBackground(final String... args) {
// here is your code
return true;
}
void downloadfile(String fileurl) throws HttpException,HttpHostConnectException {
URL myFileUrl = null;
try {
myFileUrl = new URL(fileurl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
if(length>0)
{
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
//img.setImageBitmap(bmImg);
}
else
{
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
please tell me where i hav to change
That seems like a lot of code just to show on an ImageView. Try this instead:
URL url = new URL("http://variable3.com/files/images/email-sig.jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
img_downloaded.setImageBitmap(bmp);
Use the following code for that, it will help you
Drawable drawable = LoadImageFromWebOperations(backImgUrl);
bagImgBtn.setBackgroundDrawable(drawable);
private Drawable LoadImageFromWebOperations(String url) {
// TODO Auto-generated method stub
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
if (LogD) {
Log.d(TAG, e.toString());
e.printStackTrace();
}
return null;
}
}
Create a new onClick method called downloadButton.
public void downloadButton(View view){
Log.i("Button Status", "Button Pressed");
downloadImage imagedownload = new downloadImage();
Bitmap image;
try {
image = imagedownload.execute("Paste URL address of an image").get();
imageView.setImageBitmap(image);
}catch (Exception e){
e.printStackTrace();
}
}
Create a class called downloadImage which extends AysncTask.
public class downloadImage extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
Just call the following method on Button Click:
Drawable drawable_from_url(String url, String src_name) throws java.net.MalformedURLException, java.io.IOException
{
return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);
}
where url is the url to pass and src_name is any String(say "src")
Hope this will help you
I want to load an image from url on a button click & to show it on activity imageview
You have to do something like below within onPageFinished:
public void onPageFinished (WebView view, String url) {
wv.loadUrl(javascript);
view.getSettings().setLoadsImagesAutomatically(true);
wv.setVisibility(View.VISIBLE);
}

Image download code works for all image format, issues with PNG format rendering

I am using the code below to download and show image from server to my ImageView
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class HTTPTest extends Activity {
ImageView imView;
String imageUrl="http://11.0.6.23/";
Random r= new Random();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button bt3= (Button)findViewById(R.id.get_imagebt);
bt3.setOnClickListener(getImgListener);
imView = (ImageView)findViewById(R.id.imview);
}
View.OnClickListener getImgListener = new View.OnClickListener()
{
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
//i tried to randomize the file download, in my server i put 4 files with name like
//png0.png, png1.png, png2.png so different file is downloaded in button press
int i =r.nextInt(4);
downloadFile(imageUrl+"png"+i+".png");
Log.i("im url",imageUrl+"png"+i+".png");
}
};
Bitmap bmImg;
void downloadFile(String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This code works file for all format of images but when it comes to PNG it wont let the image transparent after download and displaying on ImageView.
Any idea?
I dont know it will be a solution for you or not
But you can use a Drawable instead of Bitmap
Here is the code
void downloadFile(String fileUrl) {
try{
InputStream is = (InputStream) new URL(fileUrl).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
imgView.setImageDrawable(d);
} catch (IOException e) {
e.printStackTrace();
}
}
This will show a png correctly

Categories

Resources