Image not downloading on android 2.3.3 and above android version - android

I have trouble with download image from server in my android app. If i try to download image from https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg
My Code -
bitmap = BitmapFactory.decodeStream((InputStream) new URL(url)
.getContent());
It return null means image not downloading on 4.0.3 but image downloading successfully on 2.2
I think there may be problem with os version.
Now i want anyone to help and guide me for the same.

Write below code into your activity.java file's onCreate method after setcontentview().
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Between 2.2 and 4.0.0 there were some changes regarding what you could do on the UI thread.
From your code snipit I can not tell what thread you are doing this on, but I would expect that this is the same problem.
Try loading your image using an AsyncTask, as you can not perform this http action on the UI thread.

Please confirm about Network on UI Thread Exception and make sure that you are using AsyncTask. Try the same code with AsyncTask, this will help you.

Try this code.
try
{
imageView.setImageDrawable(grabImageFromUrl(imageUrl));
}
catch (Exception e)
{
Log.i("CATCH", "ImageDrawable");
e.printStackTrace();
}
and method code is::
private Drawable grabImageFromUrl(String imageUrlInput) throws MalformedURLException, IOException, Exception
{
return Drawable.createFromStream((InputStream)new URL(imageUrlInput).getContent(), "src");
}
I have created this code for you, try it worked at my end...
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class image extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = DownloadImage("https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg");
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
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();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}

Related

Titanium android remote image not shown

I am using Titanium to build a cross-platform mobile application, which I mostly tested with the iOS simulator and where I already got all functionality working. Now I want to have the app also bugfree on Android. One of the issues I'm facing right now is that the remote images are not shown anymore (while they were on iOS). The url from the remote images can is retrieved from the server and should be correct, as I see the images on iOS. This is one of the image urls:
http://elgg.masaer.com/mod/profile/icondirect.php?joindate=1426024336&guid=47&size=large
This is the code I use to show the image:
var profilePic = Titanium.UI.createImageView({
image: post.User.avatar,
width: '60px',
height: '60px',
borderRadius: 5
});
Does anybody know what could be the issue. Maybe it is because the url doesn't really have an extension of the image file? Thanks in advance!
possible answer is this
import java.net.URLConnection;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView mImgView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
String url = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = loadBitmap(url, bmOptions);
mImgView1.setImageBitmap(bm);
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
}
After some searching I found out that android is not smart enough to work with image urls and you have to retrieve the imagedata yourself. This can be used to download the remote image.
function loadImage(imageView,url) {
var http = Titanium.Network.createHTTPClient();
http.onload = function() {
imageView.image=this.responseData;
};
http.open('GET',url);
http.send();
};

display image from URL in image view

I have been trying many of the codes that have been posted on stackoverflow itself. However, none have worked for me so far. I'm new to android and there's probably something I'm overlooking. Kindly help fix this code -
package com.alphageeks.pespitstop;
import java.io.InputStream;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class Vop extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vop);
Button bnot = (Button) findViewById(R.id.bnot);
Button bcant = (Button) findViewById(R.id.bcant);
Button bcal = (Button) findViewById(R.id.bcal);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final Toast disp = null;
bnot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
URL url = new URL("https://drive.google.com/file/d/0B-bEff6i-vWoUHpWS3h1VUR4ZkE/edit?usp=sharing");
//try this url = "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
InputStream input = b_entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(input);
img.setImageBitmap(bitmap);
} catch (Exception ex) {
disp.makeText(Vop.this, "error",Toast.LENGTH_SHORT).show();
}
}
});
}
}
Two things:
1) The URL your want is actually:
https://lh3.googleusercontent.com/pgF2BkPGEdp5KuKD535q0DNL-SkXqiaPGmeQt-F0wA-GZ3GLIu2WaOGI72i0TzlxI-Uub4FoFtY
2) You'll need to download the image in a background Thread, like an AsyncTask, otherwise you'll throw a NetworkOnMainThreadException.
private class ImageWorker extends AsyncTask<String, Void, Bitmap> {
/**
* {#inheritDoc}
*/
#Override
protected Bitmap doInBackground(String... params) {
InputStream input = null;
try {
final URL url = new URL(YOUR_URL);
input = new BufferedInputStream(url.openStream());
return BitmapFactory.decodeStream(input);
} catch (final Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (final IOException ignored) {
// Nothing to do
}
}
}
return null;
}
/**
* {#inheritDoc}
*/
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
// Set the image here
}
}
}
try this (this is in case if you don't get any exceptions, otherwise you probably do networking on UI thread and that results in error, then you may ignore my reply):
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
byte[] bytes = out.toByteArray();
Bitmap bmp=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
img.setImageBitmap(bmp);
Maybe you can take a look in this tutorial.
I hope it can solve your problem.
https://sites.google.com/site/androidhowto/diplayinganimage
Or this website that have more detailed tutorial on how to display image from URL.
Don't forget to include permission in the manifest.
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/
use picasso http://square.github.io/picasso/ is easy with less code example Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Try this..it may be help you..
URL url = new URL("YourUrl");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
Try this:
try {
URL url = new URL("https://drive.google.com/file/d/0B-bEff6i-vWoUHpWS3h1VUR4ZkE/edit?usp=sharing");
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;
}

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.

Why is the output shown for so less duration?

Can you please tell why the the output disappears so quickly?
If you want to run the code, you will need the following in your Androidmanifest.xml file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Below is the code:
package prototype.networking.textfiles;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity
{
//-------------------------------------------------------------- OpenHttpConnection()------------------------------------------------//
private InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(
urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try
{
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();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
//--------------------------------------------------OpenHttpConnection ends here-------------------------------------------------------------//
//--------------------------------------------------Download Plain Text Files (RSS) --------------------------------------------------------------//
private String DownloadText(String URL)
{
int BUFFER_SIZE = 2000;
InputStream in = null;
try
{
in = OpenHttpConnection(URL);
}
catch (IOException e1)
{
Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG) .show();
e1.printStackTrace();
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try
{
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString = String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
}
catch (IOException e)
{
Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG) .show();
e.printStackTrace();
return "";
}
return str;
}
//-------------------------------------------------DownloadText() ends here--------------------------------------------------------------------------//
//-------------------------This method downloads "PLAIN TEXT FILES"-------------------------------------------------------------------------//
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String str = DownloadText("http://www.appleinsider.com/appleinsider.rss");
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG) .show();
}
}
You say "the output vanishes within a secon". But you show it in a Toast. And that is what a Toast is supposed to do: check out the documentation - "The notification automatically fades in and out, and does not accept interaction events". It is the desired functionality, not an issue.
The length of a Toast is either Toast.LENGTH_SHORT or Toast.LENGTH_LONG. If you want to show a notification for a longer period of time consider using custom Dialog or DialogFragment or StatusBarNotification. Or if you don't want it to disappear, simply put it inside a View, e.g. TextView.

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);
}

Categories

Resources