Set Linear layout background dynamically - android

I wanted to set Linear Layout background dynamically in the following way:
Fetch image from web url through XML parsing and then store that image into sd card.
Now the image saved into sd card.
Set that image as a linear layout background in the app.
Now I am stuck in the third step. Can anyone help?

Use this:
Bitmap bmImg = BitmapFactory.decodeStream(is);
BitmapDrawable background = new BitmapDrawable(bmImg);
linearLayout.setBackgroundDrawable(background);
Also check this: How to convert a Bitmap to Drawable in android?

I have done this way:
private RelativeLayout relativeLayout;
onCreate:
relativeLayout= (RelativeLayout)findViewById(R.id.relativeLayout);
new LoadBackground("http://www.tmonews.com/wp-content/uploads/2012/10/androidfigure.jpg",
"androidfigure").execute();
AsyncTask to load image in background:
private class LoadBackground extends AsyncTask<String, Void, Drawable> {
private String imageUrl , imageName;
public LoadBackground(String url, String file_name) {
this.imageUrl = url;
this.imageName = file_name;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Drawable doInBackground(String... urls) {
try {
InputStream is = (InputStream) this.fetch(this.imageUrl);
Drawable d = Drawable.createFromStream(is, this.imageName);
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
#Override
protected void onPostExecute(Drawable result) {
super.onPostExecute(result);
relativeLayout.setBackgroundDrawable(result);
}
}
Hope this will help you.

An easier way:
BitmapDrawable d = new BitmapDrawable("/sdcard/data/image.jpg");
linearLayout.setBackgroundDrawable(d);

API are deprecated you can use the below code
BitmapDrawable background = new BitmapDrawable(getResources(), bitmapImage);
linearLayout.setBackground(background);

Try to use this:
Bitmap bmpOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.img);
BitmapDrawable bmpBackground = new BitmapDrawable(getResources(), bmpOriginal)

Use #Deimos's answer, but like this since some methods are deprecated now
Bitmap bmImg = BitmapFactory.decodeStream(is);
BitmapDrawable background = new BitmapDrawable(context.getResources(), bmImg);
linearLayout.setBackground(background);

You can also set image from drawable folder.
yourView.setBackgroundResource(R.drawable.FILENAME);
That set FILENAME as background image.

Related

Load image from auto download url

While calling my url, which downloads an image from server automatically. I need to display this image on an Android ImageView. I usually using Piccaso library to load image from url but that not helping me here, is there any way to load image from auto download url to an Android ImageView?
Auto download url example is in here(wallpaperswide.com/download/bike_chase-wallpaper-2560x1600.jpg)
Well if dont want to use library like Piccaso try something like this:
public class AsyncTaskLoadImage extends AsyncTask<String, String, Bitmap> {
private final static String TAG = "AsyncLoadImage";
private ImageView imageView;
public AsyncTaskLoadImage(ImageView imageView) {
this.imageView = imageView;
}
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
bitmap = BitmapFactory.decodeStream((InputStream)url.getContent());
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
imageView.setImageBitmap(bitmap);
}
}
And you call in your activity like:
String url = "YOUR_LINK_HERE";
new AsyncTaskLoadImage(imageView).execute(url);
OR
With less code try something like this answer:
URL url = new URL("YOUR_LINK_HERE");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);

Convert URL to Bitmap results in a network error in Android

I'm trying to load an image from an URL to a Bitmap but I am getting a NetworkOnMainThreadException error but I don't know why.
This is the method I am using:
public Bitmap getBitmapFromURL(String src) {
try {
java.net.URL url = new java.net.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;
}
}
I also tried to load the image to a Target using Picasso library, because in the end, I want to get the dominant color from this image using Palette. This is the code I have using Picasso:
Picasso.with(MovieDetails.this)
.load("https://image.tmdb.org/t/p/w500" + backdrop)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Palette palette = Palette.from(bitmap).generate();
System.out.println(palette.getVibrantSwatch().toString().substring(16, Math.min(palette.getVibrantSwatch().toString().length(), 22)));
LinearLayout lLayout = (LinearLayout) findViewById(R.id.layout_bg);
lLayout.setBackgroundColor(Color.parseColor("#"+ palette.getVibrantSwatch().toString().substring(16, Math.min(palette.getVibrantSwatch().toString().length(), 22))));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
I put this inside my onCreate method, but I am getting "method does not override method from its superclass" errors in all the three #Override methods.
I managed to solve my problem by using an AsyncTask as it follows:
I put this in the end of my Activity:
public class MyAsync extends AsyncTask<Void, Void, Bitmap>{
#Override
protected Bitmap doInBackground(Void... params) {
try {
URL url = new URL("https://image.tmdb.org/t/p/w500" + backdrop);
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;
}
}
}
Please note that inside this method I put the URL for the image.
To access the Bitmap inside my Activity and get the dominant color using Palette I did this:
MyAsync obj = new MyAsync(){
#Override
protected void onPostExecute(Bitmap bmp) {
super.onPostExecute(bmp);
Bitmap bm = bmp;
if (bm != null && !bm.isRecycled()) {
Palette palette = Palette.from(bm).generate();
System.out.println(palette.getVibrantSwatch().toString().substring(16, Math.min(palette.getVibrantSwatch().toString().length(), 22)));
LinearLayout lLayout = (LinearLayout) findViewById(R.id.layout_bg);
lLayout.setBackgroundColor(Color.parseColor("#"+ palette.getVibrantSwatch().toString().substring(16, Math.min(palette.getVibrantSwatch().toString().length(), 22))));
}
}
};
obj.execute();
This code is inside my onCreate method.
The way to correct the first issue is to perform that action in a Thread or Runnable, There is a flag you can set something like StrictModeEnabled or something like that, but that's bad, don't resort to that.
As far as picasso, i dont know about the overriding methods from superclass thing, i'd try to do it in onViewCreated instead of onCreate

How to display dynamic ImageView from URL in infoWindow

I'm trying to download an image and show it as an ImageView in my infoWindow , working with InfoWindowsAdapter , i put all the necessary code in the getInfoContents() method, but i can't get the image , in fact i can get it but still can't show it .
As i read in the documentation,i have to recall the treatment to set the downloaded image , i have to use showInfoWindow() method because it's the only way to do it . I tried to use it in getInfoContents() just before the return but , it blocks my app , need help !
This is my getInfoContents() :
public View getInfoContents(Marker marker) {
// set the view
View v = (View) getLayoutInflater().inflate(R.layout.info_window,null);
//assign values to the view field
ImageView imagePlace =(ImageView) v.findViewById(R.id.imageview1);
TextView tvLocality = (TextView) v.findViewById(R.id.tv_place);
//setting values with the parameter
Picasso.with(getApplicationContext()).load(url_image_place).into(imagePlace);
tvLocality.setText(marker.getTitle());
//marker.showInfoWindow();
return v;
}
This my downloadIcon() :
private Bitmap downloadIcon(String iconURL) {
Bitmap bmImg = null;
try {
URL url = new URL(iconURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
bmImg = null;
}
return bmImg;
}
EDIT :
I used picasso to download my image , but the image is shown only after the second click , and any marker's infowindow that use the same image get the image in the first time , it means that the image have to be downloaded first !! i edited my getInfoContents() and i'm not using downloadIcon() anymore !
Using Picasso, this is extremely easy. Simply write:
String url = ...;//Your url
ImageView imageView; //Your ImageView
Picasso.with(context).load(url).into(imageView);
Or, If you want to do it yourself, you can implement an AsyncTask:
Definition:
private class ImageDownloader extends AsyncTask {
#Override
protected Bitmap doInBackground(String... param) {
return downloadIcon(param[0]);
}
#Override
protected void onPostExecute(Bitmap result) {
//Handle your result, i.e. your bitmap
}
}
Execution:
new ImageDownloader().execute(iconURL);
You should not dowmload image by using main UI thread, so you need another thread to do it, something like:
public void setImage(final ImageView img, final String iconURL)
{
Thread thread = new Thread(new Runnable() {
#Override
public void run()
{
Bitmap bmImg;
try {
URL url = new URL(iconURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e) {
e.printStackTrace();
bmImg = null;
}
//after downloading, then talk to main ui
runOnUiThread(new Runnable()
{
#Override
public void run()
{
img.setImageBitmap(bmImg);
}
}
}}).start();
}
Hope this help!

How to change Layout background dynamically in Android?

I have parsed JSON at the time of Splash screen, in which image url is parsed for background image for login screen. Here is sample XMLcode for login screen:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/loginLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background_bg" <!-- I want to change this background dynamically. -->
android:focusableInTouchMode="true"
android:gravity="center"
tools:context=".activity.LoginActivity" >
<ScrollView
android:id="#+id/mainScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- .... Here is edit text for login inputs and buttuns for singnup and login. -->
</LinearLayout>
</ScrollView>
</RelativeLayout>
In above i have placed static image in the background of RelativeLayout but i want to make backgroud as changeble according to image url.
Thanks in advance.
You need to convert url image to bitmap then bitmap image to Drawable and set it RelativeLayout.
First convert url image to bitmap, see the sample code.
Bitmap myImage = getBitmapFromURL("http://looksok.files.wordpress.com/2011/12/me.jpg");
Take RelativeLayout reference
RelativeLayout rLayout=(RelativeLayout)findViewById(R.id.relativeLayout);
BitmapDrawable(obj) convert Bitmap object into drawable object.
Drawable dr = new BitmapDrawable(myImage);
rLayout.setBackgroundDrawable(dr);
Url image to bitmap convertion method
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
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;
}
}
Try this way,hope this will help you to solve your problem.
Download Latest AndroidQuery jar from here:
Put this jar to your libs folder and right click on jar and Build Path -> Add to bulid path.
How to use see this example:
AQuery androidQuery = new AQuery(this);
androidQuery.ajax(url.trim(), Bitmap.class, 0, new AjaxCallback<Bitmap>() {
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
super.callback(url, object, status);
yourRelativeLayout.setBackground(new BitmapDrawable(object));
}
});
This is how I would do it
Call the AsyncTask like this
new GetImageFromServer().execute(strUrl); // strUrl is your URL
Here is the AsyncTask class
public class GetImageFromServer extends AsyncTask<String, Void, Bitmap>
{
private Bitmap image;
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... params){
try{
URL urli = new URL(params[0].trim());
URLConnection ucon = urli.openConnection();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
image = BitmapFactory.decodeStream(ucon.getInputStream(),null,options);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image; //<<< return Bitmap
}
#Override
protected void onPostExecute(Bitmap result){
RelativeLayout relative = (RelativeLayout) findViewById(R.id.loginLayout);
Drawable dr = new BitmapDrawable(result);
relative.setBackgroundDrawable(dr);
}
}

Android : Loading an image from the Web with Asynctask

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
}

Categories

Resources