I have a set of buttons and i want them to be visible only when the image is loaded..and the progressbar to hide,how can i do that..whenever use onPreExecute() or write
buttonname.setVisibility(View.VISIBLE);
in post execute it stops loading the image..Here is what i am using..please help me out i am stuck
public class Main extends Activity{
ImageView image,next,back;
Button a;
static int fullWidth;
static int fullHeight;
ProgressBar progressbar;
Button setWallpaper;
private class BackgroundTask extends AsyncTask <String, Void, Bitmap> {
protected Bitmap doInBackground(String...url) {
//--- download an image ---
Bitmap bitmap = DownloadImage(url[0]);
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
ImageView image = (ImageView) findViewById(R.id.imageView1);
bitmaptwo=bitmap;
image.setImageBitmap(bitmap);
image.setScaleType(ScaleType.FIT_CENTER);
}
}
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){
Toast.makeText(this,e1.getLocalizedMessage(),
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
return bitmap;
}
public static Bitmap bitmaptwo;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
try
{
new BackgroundTask().execute("http://meluha.in/wp-content/uploads/1.jpg");
}
catch(Exception e)
{
e.printStackTrace();
}
setWallpaper = (Button) findViewById(R.id.abcd);
ImageView next = (ImageView) findViewById(R.id.next);
ImageView back = (ImageView) findViewById(R.id.back);
setWallpaper.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager wManager;
try {
// Bitmap bitmap = ((BitmapDrawable)imageView1.getDrawable()).getBitmap();
wManager = WallpaperManager.getInstance(getApplicationContext());
fullWidth = wManager.getDesiredMinimumWidth();
fullHeight = wManager.getDesiredMinimumHeight();
Bitmap bitmapResized = Bitmap.createScaledBitmap(bitmaptwo, fullWidth, fullHeight,true);
wManager.setBitmap(bitmapResized);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Add this code yo your onPostExecute method:
button1.setVisibility(View.VISIBLE);
button2.setVisibility(View.VISIBLE);
//....
progressbar.setVisibility(View.INVISIBLE);
Related
My code is as follows:
public class MainActivity extends Activity {
ImageView[] targetImage = new ImageView[5];
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) {
Log.d("Networking", ex.getLocalizedMessage());
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) {
Log.d("NetworkingActivity", e1.getLocalizedMessage());
}
return bitmap;
}
private class DownloadImageTask extends AsyncTask<String, Bitmap, Long> {
//---takes in a list of image URLs in String type---
protected Long doInBackground(String... urls) {
long imagesCount = 0;
for ( int i = 0; i < urls.length; i++) {
//---download the image---
Bitmap imageDownloaded = DownloadImage(urls[i]);
if (imageDownloaded != null ) {
//---increment the image count---
imagesCount++;
try {
//---insert a delay of 3 seconds---
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//---return the image downloaded---
publishProgress(imageDownloaded);
}
}
//---return the total images downloaded count---
return imagesCount;
}
//---display the image downloaded---
protected void onProgressUpdate(Bitmap... bitmap) {
if(bitmap.length > 0) {
for(int i = 0; i < bitmap.length; i++) {
targetImage[i].setImageBitmap(bitmap[i]);
}
}
// tIV[values[i]].setImageBitmap(tBM[values[i]]);
}
//---when all the images have been downloaded---
protected void onPostExecute(Long imagesDownloaded) {
Toast.makeText(getBaseContext(),
"Total" + imagesDownloaded + " images downloaded" ,
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
targetImage[0] = (ImageView)findViewById(R.id.target0);
targetImage[1] = (ImageView)findViewById(R.id.target1);
targetImage[2] = (ImageView)findViewById(R.id.target2);
new DownloadImageTask().execute(
"http://solutionboat.com/work_2/asset/images/sobin.jpg" ,
"http://solutionboat.com/work_2/asset/images/shamol.jpg",
"http://solutionboat.com/work_2/asset/images/rifat.jpg"
);
ViewFlipper flipper = (ViewFlipper) findViewById(R.id.viewFlipper1);
flipper.startFlipping();
}
}
Import picasso library in your project:
http://square.github.io/picasso/
And try this:
public class MainActivity extends Activity {
ImageView[] targetImage = new ImageView[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
targetImage[0] = (ImageView)findViewById(R.id.target0);
targetImage[1] = (ImageView)findViewById(R.id.target1);
targetImage[2] = (ImageView)findViewById(R.id.target2);
Picasso.with(MainActivity.this).load("http://solutionboat.com/work_2/asset/images/sobin.jpg").into(targetImage[0]);
Picasso.with(MainActivity.this).load("http://solutionboat.com/work_2/asset/images/shamol.jpg").into(targetImage[1]);
Picasso.with(MainActivity.this).load("http://solutionboat.com/work_2/asset/images/rifat.jpg").into(targetImage[2]);
}
}
On the site http://218.93.33.59:85/map/zjmap/ibikegif.asp?flag=2&id=9, we can get a gif image named ibikegif.gif. However I can't display it on my android phone. My code like this:
/**
*#param url the imageURL.it references to
*"http://218.93.33.59:85/map/zjmap/ibikegif.asp?flag=2&id=9" here
*
**/
public Bitmap returnBitMap(String url) {
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is); //Attention:bitmap is null
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
Could you help me?
I have tested this code and it works. It's basically what you did with one difference, i have also set request method explicitly to GET.
public class MyActivity extends Activity {
private ImageView imageView;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.imageView);
}
#Override
protected void onResume() {
super.onResume();
new AsyncTask<Void, Void, Void>() {
Bitmap bitmap;
#Override
protected Void doInBackground(Void... params) {
try{
bitmap = returnBitMap("http://218.93.33.59:85/map/zjmap/ibikegif.asp?flag=2&id=9");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
}
}.execute();
}
public Bitmap returnBitMap(String url) throws IOException {
URL myFileUrl = null;
Bitmap bitmap = null;
InputStream is = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.connect();
is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
if(is != null) {
is.close();
}
return bitmap;
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android image view from url
I am trying to fetch the image from url and load in imageView, but I cannot encode the url string, please let me know how to encode this.
Please find the code & url used for your reference.
URL: http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/%7BB690E93E-F7C9-48AF-B72A-BFF944FA6D4A%7D_104_9169.JPG
Code
String link=URLEncoder.encode(urlStr);
bitmap=loadBitmap(link);
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(url).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
}
return bitmap;
}
Use this Code it will fetch the image from server
String URL = "http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/%7BB690E93E-F7C9-48AF-B72A-BFF944FA6D4A%7D_104_9169.JPG";
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();
final String msg = e1.getMessage();
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "" + msg, Toast.LENGTH_SHORT).show();
}
});
}
return bitmap;
}
FYI, URLEncoder.encode(String) has been deprecated.
Reference:
http://developer.android.com/reference/java/net/URLEncoder.html
You can encode the url as below:
String URL = "http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/%7BB690E93E-F7C9-48AF-B72A-BFF944FA6D4A%7D_104_9169.JPG";
String encodeUrl=URLEncoder.encode(URL, "utf-8");
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();
final String msg = e1.getMessage();
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "" + msg, Toast.LENGTH_SHORT).show();
}
});
}
return bitmap;
}
I have create example for How to display image from URL. Use that example it works for me and i also check it by replace you image url.
Please Use below code for download and display image into imageview.
public class MainActivity extends Activity {
ImageView my_img;
Bitmap mybitmap;
ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView mImgView1 = (ImageView) findViewById(R.id.mImgView1);
DownloadImageFromURL mDisImgFromUrl = new DownloadImageFromURL(mImgView1);
mDisImgFromUrl.execute("http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/%7BB690E93E-F7C9-48AF-B72A-BFF944FA6D4A%7D_104_9169.JPG");
}
private class DownloadImageFromURL extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Loading...");
pd.show();
}
public DownloadImageFromURL(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;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
pd.dismiss();
}
}
}
I have a problem to display this image in my internet.
I have no idea how to make it work.
I am new to android.
The problem is that part ...
imView = (ImageView) findViewById(R.id.imageView1);
imView.setImageBitmap(bm); //error
Thank you.
my code
public class CarregaImagem extends AsyncTask<String, Void, String>{
String imageUrl = "http://www.cuboweb.com.br/android/images/logoconsulfarma.png";
private ProgressDialog progress;
private Activity activity;
Bitmap bmImg;
public CarregaImagem(Activity activity){
this.activity = activity;
}
protected void onPreExecute() {
progress = new ProgressDialog(activity);
progress.setTitle("Aguarde...");
progress.setMessage("Carregando...");
progress.show();
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
URL aURL = new URL(imageUrl);
final URLConnection conn = aURL.openConnection();
conn.connect();
final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
final Bitmap bm = BitmapFactory.decodeStream(bis);
BitmapFactory.decodeStream(new URL(imageUrl).openConnection().getInputStream());
bis.close();
} catch (IOException e) {
imageUrl = "";
} catch(Exception f){
imageUrl = "";
}
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
if(!imageUrl.equals("")){
imView = (ImageView) findViewById(R.id.imageView1);
imView.setImageBitmap(bm); //error
} else{
Toast.makeText(activity, "Não foi possível obter resultados", Toast.LENGTH_LONG).show();
}
progress.dismiss();
}
}
You create a bitmap in doInBackground that you never use.
Return instead the bitmap and use it in onPostExecute.
Try below code to download image from web and display in imageview.
public class MainActivity extends Activity {
ImageView mImgView1;
static Bitmap bm;
ProgressDialog pd;
String imageUrl = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
pd = ProgressDialog.show(MainActivity.this, "Aguarde...",
"Carregando...");
new ImageDownload().execute("");
}
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
loadBitmap(imageUrl, bmOptions);
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
pd.dismiss();
if (!imageUrl.equals("")) {
mImgView1.setImageBitmap(bm);
} else {
Toast.makeText(MainActivity.this,
"Não foi possível obter resultados", Toast.LENGTH_LONG)
.show();
}
}
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
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;
}
}
hey i faced the same problem for showing image from url, this link was very useful. also u can refer to stackoverflow discussion
Apparently android 3 onwards network connectivity is strict hence network connection fails
Cheers!
Hi everyone I've check the post on the set wallpaper from URL but I am really new to programing and I still do not undertand it, could someone provide me with an example, basically I have an image on a server and I want to push a button and set it as the phone wallpaper thank you again for the help
public class TestingThree extends Activity {
ImageView image;
private class BackgroundTask extends AsyncTask
<String, Void, Bitmap> {
protected Bitmap doInBackground(String...url) {
//--- download an image ---
Bitmap bitmap = DownloadImage(url[0]);
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.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){
Toast.makeText(this,e1.getLocalizedMessage(),
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
return bitmap;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper);
new BackgroundTask().execute("http://myglobaljournal.com/images/imagetest.jpg");
Button setWallpaper = (Button) findViewById(R.id.button3);
setWallpaper.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
WallpaperManager wManager;
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeFile(null);
wManager = WallpaperManager.getInstance(getApplicationContext());
wManager.setBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
am trying to implement it to the button at the bottom where i pull the image from the link and set it directly as a wallpaper
thank you again
try this:
ImageView image;
private class BackgroundTask extends AsyncTask
<String, Void, Bitmap> {
protected Bitmap doInBackground(String...url) {
//--- download an image ---
Bitmap bitmap = DownloadImage(url[0]);
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
ImageView image = (ImageView) findViewById(R.id.imageView1);
bitmaptwo=bitmap;
image.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){
Toast.makeText(this,e1.getLocalizedMessage(),
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
return bitmap;
}
public Bitmap bitmaptwo;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper);
new BackgroundTask().execute("http://myglobaljournal.com/images/imagetest.jpg");
Button setWallpaper = (Button) findViewById(R.id.button3);
setWallpaper.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
WallpaperManager wManager;
try {
// bitmap = BitmapFactory.decodeFile(null);
wManager = WallpaperManager.getInstance(getApplicationContext());
wManager.setBitmap(bitmaptwo);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Required Permission:
<uses-permission android:name="android.permission.SET_WALLPAPER"/>