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);
}
}
Related
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);
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
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!
I am using async to load the image into a grid view / list view. For each place download the image for internet , I use a class to handle it. The problem is , how to set a loading icon on it (at the center of the image view)? Thanks
The imageloader class:
public class ImageLoader extends AsyncTask<Object, Void, Bitmap> {
private static String TAG = "ImageLoader";
public InputStream input;
public ImageView view;
public String imageURL;
#Override
protected Bitmap doInBackground(Object... params) {
try {
view = (ImageView) params[0];
imageURL = (String) params[1];
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null && view != null) {
view.setImageBitmap(result);
}
}
}
You could use a custom layout in your GridView or ListView that is a RelativeLayout containing your ImageView and a ProgressBar for the loading-animation.
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
You would then need to pass the RelativeLayout to the AsyncTask from which you can retreive
a) your ImageView and
b) the ProgressBar
When the download is complete (e.g. you enter the method onPostExecute) you do the following:
#Override
protected void onPostExecute(Bitmap result) {
if (result != null && image != null) {
image.setImageBitmap(result); // change 'image' to the ImageView you retreived earlier from your RelativeLayout
}
progressBar.setVisibility(View.GONE); // hide the ProgressBar
}
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.