I want to show picture that obtain from URLlink but I stuck in problem that's not trust in this URLlink. Then, it don't show anythings on screen. So, this is my Oncreate's code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
Bitmap bmp = null;
ImageView imgView =(ImageView)findViewById(R.id.imageView);
String imageUrl = "10.34.250.12/api/config/v1/maps/imagesource/domain_0_1500368087062.jpg";
imgView.setImageBitmap(GetBitmapfromUrl("https://httpbin.org/image/png"));
imgView.setTag("10.34.250.12/api/config/v1/maps/imagesource/domain_0_1500368087062.jpg");
new DownloadImagesTask().execute(imgView);
}
and this is DownloadImageTask's code.
class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews){
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result){
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url){
Bitmap bmp = null;
try{
URL urln = new URL(url);
HttpURLConnection con = (HttpURLConnection)urln.openConnection();
String UserCredentials = "dev : dev12345";
String basicAuth = Base64.encodeToString(UserCredentials.getBytes(), Base64.NO_WRAP);
// String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes);
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestMethod("GET");
// con.setUseCaches(false);
// con.setDoInput(true);
// con.setDoOutput(true);
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
return bmp;
}
catch (Exception e){}
return bmp;
}
}
thanks for every helps .
For https your may cast the result of openConnection to HttpsURLConnection
If you using untrust ssls you may create a X509Certificate with your keystore to use in the application, or create a X509 that ignores all certificates
Related
I'm new on android studio and I'm trying to do an AsyncTask for my Network operation.
The problem is to get the return variable from it to be able to set the image in the imageview. imgDisplay.setImageBitmap(var)
public class ZoomActivity extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zoom);
Intent intent = getIntent();
String url2 = intent.getStringExtra("image");
ImageView imgDisplay;
Button btnClose;
imgDisplay = (ImageView) findViewById(R.id.imgDisplay);
btnClose = (Button) findViewById(R.id.btnClose);
//Bitmap var = return of doInBackground??????????
imgDisplay.setImageBitmap(var);
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ZoomActivity.this.finish();
}
});
}
private class MyTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... Params) {
String myString = Params[0];
try {
URL url = new URL(URL???); //how to pass url2 var here?
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;
}
}
}
}
any examples?
First, declare this asynctask class:
class MyTask extends AsyncTask<String,Void,Bitmap>{
#Override
protected Bitmap doInBackground(String... strings) {
String myString = Params[0];
try {
URL url = new URL(myString);
Bitmap myBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imgDisplay.setImageBitmap(bitmap);
}
}
Your zoomActivity changes to:
public class ZoomActivity extends Activity {
ImageView imgDisplay;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zoom);
Intent intent = getIntent();
String url2 = intent.getStringExtra("image");
Button btnClose;
imgDisplay = (ImageView) findViewById(R.id.imgDisplay);
btnClose = (Button) findViewById(R.id.btnClose);
//call asynctask
new MyTask().execute(url2);
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ZoomActivity.this.finish();
}
});
}
hope this works
When your doInBackground returns an object, it goes to the method onPostExecute as an input parameter, and that method executes in the UI thread and not a parallel thread, so you can set the imag
AsyncTask
This this for reference.
Change you MyTask to
private class MyTask extends AsyncTask<String, Integer, BitMap> {
#Override
protected Bitmap doInBackground(String... Params) {
String myString = Params[0];
try {
URL url = new URL(URL???); //how to pass url2 var here?
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;
}
}
protected void onPostExecute(Bitmap result) {
//set the Image here.
imgDisplay.setImageBitmap(result);
}
}
You should let the AsyncTask return a Bitmap instead of a String
private class MyTask extends AsyncTask<String, Integer, Bitmap> {
#Override
protected Bitmap doInBackground(String... Params) {
String myString = Params[0];
try {
URL url = new URL(myString); //how to pass url2 var here?
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;
}
}
protected void onPostExecute(Bitmap result) {
//set your bitmap here to your imgDisplay
}
}
Then you start the task with
new MyTask().execute(/* urlString*/)
I have a method where I would download an image from a folder based on the link passed into the AsyncMethod
I have since made some changes and now the image resides on the database. I am having a little problem editing my downloadAsyn Task as it no longer receives a link but instead a long string of characters (BLOB from the database).
I have pasted my code below, and is trying to find assistance in assigning cImg1 the bitmap to display my image.
Thank you
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];// this parameter once had url of image
//but now it has the image bitmap.
Bitmap cImg1= null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
// cImg1= BitmapFactory.decodeStream(in);
cImg1=urldisplay;//Assign strings to BitMap?
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return cImg1;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Below code will be worked fine.
public class DownloadImageTask extends AsyncTask<String, Integer, Bitmap> {
Context _context;
ImageView _imageView;
private OnResponseListener _responder;
private String _errorMessage;
public DownloadImageTask(ImageView bmImage, OnResponseListener responseListener) {
this._imageView = bmImage;
_context = bmImage.getContext();
_responder = responseListener;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... urls) {
int count;
String urlDisplay = urls[0];
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(urlDisplay).openStream();
BitmapFactory.Options options = new BitmapFactory.Options(); options.inPurgeable = true; options.inInputShareable = true;
bitmap = BitmapFactory.decodeStream(in, null, options);
URLConnection urlConnection = new java.net.URL(urlDisplay).openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
int lengthOfFile = urlConnection.getContentLength();
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
int progress = (int) total * 100 / lengthOfFile;
publishProgress(progress);
}
} catch (Exception e) {
_errorMessage = e.getMessage();
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
protected void onPostExecute(Bitmap result) {
if (result != null){
_responder.onSuccess(result);
}
else
_responder.onFailure(_errorMessage);
}
public interface OnResponseListener {
void onSuccess(Bitmap result);
void onFailure(String message);
}
}
I have a task the deadline tom ,please your help with that exception. i want to load a svg image and display it on listview
com.larvalabs.svgandroid.SVGParseException:
org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column
0: no element found
at com.larvalabs.svgandroid.SVGParser.parse(Unknown Source)
at com.larvalabs.svgandroid.SVGParser.getSVGFromInputStream(Unknown
Source)
// code //
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
ImageView image;
DownloadImageTask(ImageView img)
{
image=img;
}
#Override
protected Drawable doInBackground(String... params) {
try {
String urldisplay = params[0];
final URL url = new URL(urldisplay);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
SVG svg = SVGParser.getSVGFromInputStream(inputStream,0,0);
Drawable drawable = svg.createPictureDrawable();
return drawable;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(Drawable drawable) {
// Update the view
image.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
image.setImageDrawable(drawable);
}
}
how to solve this problem?
what I have to do is to play videos on a single activity, the number of videos is undefined, could be from 1 to 8, a video in my case is an image sequence, where every image is downloaded from a cam on the internet using a fixed time interl.
Do a single video activity is not a problem, I can make it using ImageView and a AsyncTask, using many instances of this method when I try to make multiple videos activities does not work, only one of the video plays. I don't know exactly what it happens but I think it could be a cuncurrency related issue due to the UIThread.
Here the used AsyncTask code:
private class AsyncTask_LiveView extends AsyncTask<String, Integer, Void>
{
private String sImageMessage = "";
private final WeakReference<ImageView> imageViewReference;
private Bitmap bmImage = null;
private String url = "";
private String usr = "";
private String pwd = "";
private utils u = new utils();
public AsyncTask_LiveView(ImageView imageView, String Url, String Usr, String Pwd)
{
imageViewReference = new WeakReference<ImageView>(imageView);
url = Url;
usr = Usr;
pwd = Pwd;
}
// automatically done on worker thread (separate from UI thread)
#Override
protected Void doInBackground(final String... args)
{
while(!isCancelled())
{
if(isCancelled())
return null;
SystemClock.sleep(200);
Log.v("ImageDownload","test");
bmImage = u.DownloadBitmapFromUrl(url, usr, pwd);
publishProgress(0);
}
return null;
}
// can use UI thread here
#Override
public void onProgressUpdate(Integer... i)
{
Log.v("Image", "Setup Image");
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bmImage);
}
}
}
}
I start the AsyncTasks in this way:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutliveviewdouble);
this.imgV1 = (ImageView ) findViewById(R.id.imageView1);
aTaskImgV1 = new AsyncTask_LiveView(imgV1,
URL1,
"",
"");
this.imgV2 = (ImageView ) findViewById(R.id.imageView2);
aTaskImgV2 = new AsyncTask_LiveView(imgV2,
URL2,
"root",
"jenimex123");
aTaskImgV1.execute();
aTaskImgV2.execute();
}
The DownloadBitmapFromUrl method is:
public Bitmap DownloadBitmapFromUrl(String imageURL, final String usr, final String pwd) { //this is the downloader method
try {
URL url = new URL(imageURL);
/* Open a connection to that URL. */
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setRequestMethod("GET");
ucon.setDoOutput(true);
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (usr, pwd.toCharArray());
}
});
ucon.connect();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(100000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
Bitmap bmp = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.length());
return bmp;
} catch (Exception e) {
//Log.d("ImageManager", "Error: " + e);
return null;
}
}
Any Ideas?
Solution : (21/01/11)
The bounch of lines:
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (usr, pwd.toCharArray());
}
});
were braking the mechanism. In fact only one credentials pair a could have been set globally, and the other download processes stucked in requesting using the wrong credentials.
The solution is:
String authString = usr + ":" + pwd;
byte[] authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
String authStringEnc = new String(authEncBytes);
ucon = (HttpURLConnection) url.openConnection();
if(_usr != "")
ucon.setRequestProperty("Authorization", "Basic " + authStringEnc);
Thanks to all.
I think yuo should use unique AsyncTask_LiveView for each ImageView.
Does this function support multiple threads?
bmImage = u.DownloadBitmapFromUrl(url, usr, pwd);
It looks like some of the methods you call in downloadBitmapFromUrl(..) method involve synchronization by some common object. Try adding some extra logging to each part of this method and see where each thread gets stuck. I would do it this way:
public Bitmap downloadBitmapFromUrl(String imageURL, final String usr, final String pwd) { //this is the downloader method
try {
...
Log.i(toString() + " in " + Thread.currentThread(), "is about to open connection...");
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
Log.i(toString() + " in " + Thread.currentThread(), "has opened connection");
...
and so on.
How do I replace the following lines of code with an Asynctask ?
How do you "get back" the Bitmap from the Asynctask ? Thank you.
ImageView mChart = (ImageView) findViewById(R.id.Chart);
String URL = "http://www...anything ...";
mChart.setImageBitmap(download_Image(URL));
public static Bitmap download_Image(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("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
I thought about something like this :
replace :
mChart.setImageBitmap(download_Image(graph_URL));
by something like :
mChart.setImageBitmap(new DownloadImagesTask().execute(graph_URL));
and
public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
return download_Image(urls[0]);
}
#Override
protected void onPostExecute(Bitmap result) {
mChart.setImageBitmap(result); // how do I pass a reference to mChart here ?
}
private Bitmap download_Image(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("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
}
but How do I pass a reference to mChart in onPostExecute(Bitmap result) ???
Do I need to pass it with the URL in some way ?
I would like to replace all my lines of code :
mChart1.setImageBitmap(download_Image(URL_1));
mChart2.setImageBitmap(download_Image(URL_2));
with something similar ... but in Asynctask way !
mChart1.setImageBitmap(new DownloadImagesTask().execute(graph_URL_1));
mChart2.setImageBitmap(new DownloadImagesTask().execute(graph_URL_2));
Is there an easy solution for this ?
Do I get something wrong here ?
If there is no good reason to download the image yourself then I would recommend to use Picasso.
Picasso saves you all the problems with downloading, setting and caching images.
The whole code needed for a simple example is:
Picasso.with(context).load(url).into(imageView);
If you really want to do everything yourself use my older answer below.
If the image is not that big you can just use an anonymous class for the async task.
This would like this:
ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...anything ...";
mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
The Task class:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
...
}
Hiding the URL in the tag is a bit tricky but it looks nicer in the calling class if you have a lot of imageviews that you want to fill this way. It also helps if you are using the ImageView inside a ListView and you want to know if the ImageView was recycled during the download of the image.
I wrote if you Image is not that big because this will result in the task having a implicit pointer to the underlying activity causing the garbage collector to hold the whole activity in memory until the task is finished. If the user moves to another screen of your app while the bitmap is downloading the memory can't be freed and it may make your app and the whole system slower.
Try this code:
ImageView myFirstImage = (ImageView) findViewById(R.id.myFirstImage);
ImageView mySecondImage = (ImageView) findViewById(R.id.mySecondImage);
ImageView myThirdImage = (ImageView) findViewById(R.id.myThirdImage);
String URL1 = "http://www.google.com/logos/2013/estonia_independence_day_2013-1057005.3-hp.jpg";
String URL2 = "http://www.google.com/logos/2013/park_su-geuns_birthday-1055005-hp.jpg";
String URL3 = "http://www.google.com/logos/2013/anne_cath_vestlys_93rd_birthday-1035005-hp.jpg";
myFirstImage.setTag(URL1);
mySecondImage.setTag(URL2);
myThirdImage.setTag(URL3);
new DownloadImageTask.execute(myFirstImage);
new DownloadImageTask.execute(mySecondImage);
new DownloadImageTask.execute(myThirdImage);
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
Bitmap bmp =null;
try{
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
}catch(Exception e){}
return bmp;
}
}
you can create a class say..BkgProcess which contains an inner class that extends AsyncTask. while instantiating BkgProcess pass the context of your Activity class in BkgProcess constructor. for eg:
public class BkgProcess {
String path;
Context _context;
public Download(Downloader downloader, String path2){
this.path = path2;
_context = downloader;
}
public void callProgressDialog(){
new BkgProcess().execute((Void)null);
}
class Downloads extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(_context);
protected void onPreExecute(){
dialog.setMessage("Downloading image..");
dialog.show();
}
protected void onPostExecute(Boolean success) {
dialog.dismiss();
if(success)
Toast.makeText(_context, "Download complete", Toast.LENGTH_SHORT).show();
}
#Override
protected Boolean doInBackground(Void... params) {
return(startDownload(path));
}
public boolean startDownload(String img_url) {
// download img..
return true;
}
}
}
from your activity class..
BkgProcess dwn = new BkgProcess (Your_Activity_class.this, img_path);
dwn.callProgressDialog();
This will get you images of any size...
if you dont want the progress dialog just comment the codes in onPreExecute();
for(int i = 0 ; i < no_of_files ; i++ )
new FetchFilesTask().execute(image_url[i]);
private class FetchFilesTask extends AsyncTask<String, Void, Bitmap> {
private ProgressDialog dialog = new ProgressDialog(FileExplorer.this);
Bitmap bitmap[];
protected void onPreExecute(){
dialog.setMessage("fetching image from the server");
dialog.show();
}
protected Bitmap doInBackground(String... args) {
bitmap = getBitmapImageFromServer();
return bitmap;
}
protected void onPostExecute(Bitmap m_bitmap) {
dialog.dismiss();
if(m_bitmap != null)
//store the images in an array or do something else with all the images.
}
}
public Bitmap getBitmapImageFromServer(){
// fetch image form the url using the URL and URLConnection class
}