Unable to set LinearLayout BackgroundResource from URL using Picasso - android

I have a linearLayout I'd like to change the background of programatically:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/downloadLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1" >
...
and I've attempted to set the background Image of the XML layout using the following:
LinearLayout linearLayout2 = (LinearLayout) findViewById(R.id.downloadLayout);
int resId = getResources().getIdentifier(background,
"drawable", getPackageName());
linearLayout2.setBackgroundResource(resId);
However the background image never loads, there is no NPE, the image simply never loads. Any suggestions are appreciated.
I've done a bit of debugging and I currently have the following values:
linearLayout2 = android.widget.LinearLayout{529b3f58 V.E..... ......I. 0,0-0,0 #7f0a008e app:id/downloadLayout}
background = http://xxx.xxx.x.xxx/bgs/big_lebowski_bg.jpg
resID = 0
P.S.
I've also tried accomplishing the same using Picasso - I'm not sure how to get around the error stated and load it successfully:
Source:
final LinearLayout downloadLayout = (LinearLayout) findViewById(R.id.downloadLayout);
Picasso.with(this).load("http://i.imgur.com/DvpvklR.png").into(downloadLayout);
Error:
The method into(Target) in the type RequestCreator is not applicable for the arguments (LinearLayout)

Picasso works with ImageViews only, not layouts.
You could put an ImageView inside your layout, set it to match parent's width and height, and inject the image into the ImageView.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/downloadLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1" >
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This should work then:
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Picasso.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);

You have to do so in the background thread and not on the main thread . Consider using image loading libraries such as Picasso
Example is
UPDATED
Make sure you have an image view in the LinearLayout and let it fill_parent (i.e the LinearLayout), Picasso is not applicable to an ImageView directly hence the error.
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
ALTERNATIVELY
LinearLayout linearLayout=(LinearLayout)findViewById(R.id.yourLinearLayoutid);
BitmapDrawable drawableBitmap=new BitmapDrawable(getBitmap(urlString));
linearLayout.setBackgroundDrawable(drawableBitmap);
This method getBitMap, like the one in the Piccasso library should be sufficient without needing the library .
private Bitmap getBitmap(String url)
{
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}

Related

Scrolling images with ScrollView

Using the following XML and java code I add images taken with camera to LinearLayout within a ScrollView.
XML:
<HorizontalScrollView
android:layout_gravity="center_vertical"
android:scrollbars="none"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/detailsback"
android:layout_gravity="center_vertical"
android:id="#+id/imageSlider"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
Java (runs in Fragment):
private void setTakePicButton(){
mTakePicButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mBitmap = mTextureView.getBitmap();
Date currentDateTime = Calendar.getInstance().getTime();
String filename = getFileName();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream( filename);
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);// bmp is your Bitmap instance
ImageView imageView = new ImageView(getActivity());
imageView.setImageBitmap(mBitmap);
linearLayout.addView(imageView);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
});
}
Problem is whenever I add a pic to linearLayout (id:imageSlider) it is added with large margins like shows in the picture
I want the images to show in a sequence like in the following pic.
Solution 01
You can set the image to bounds using FIT_XY scale type
imgview.setScaleType(ImageView.ScaleType.FIT_XY);
You can find all the ScaleTypes here
Solution 02
If you are trying to view images like a list you can use a RecyclerView:
Create a List with RecyclerView
Solution 03
If you want to display the images side by side, Set layout_weight to imageView
This is how to do that programmatically, (The Last param is the weight )
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f
);
imageView.setLayoutParams(param);
If I understand correctly, the problem is that the image in the bottom is centered instead of outlined to the left? This might be caused by the wrap_content width for the linear layout.
I would also suggest you to use some sort of a list view instead of a LinearLayout and adding items manually. A RecyclerView would be a nice solution and is able to be set to horizontal as well.

URL images are smaller than the original image

I am using xamarin studio. I have to download a bunch of images from a web service. I only get their url and then I use the following code to make the images bitmap
SetContentView (Resource.Layout.test);
ImageView img = FindViewById<ImageView> (Resource.Id.image);
Bitmap bitimage = GetImageBitmapFromUrl ("http://apk.payment24.co.za/promotions/engensa/muffin.png");
img.SetImageBitmap (bitimage);
public static Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
The problem is the image I display is very small. If I manually download the images from the url and add it to the project it works perfectly fine.
My image view settings are with: match_parent and height: wrap_content.
How can I get the original size of the images if I download it via url.
Please see this link to see how the image look http://postimg.org/image/c3kbsz903/
You need to add android:adjustViewBounds ="true" and android:src="#drawable/ attribute in your Imageview
<ImageView
layout_width="match_parent"
layout_height="wrap_content"
android:adjustViewBounds ="true"
android:src="#drawable/ dummy drawable/>
Please Check ScaleType in android .
You stated that your view attributes are something like this
<ImageView
layout_width="match_parent"
layout_height="wrap_content" />
In order to have the original size of the image, you must set the layout_width attribute of your ImageView to wrap_content so that the ImageView won't use its parent's width but will adapt to the image original size.

Set imageview image from a url

Alright i've spent several hours try to figure this out and most solutions didn't work, the one that did work made the height and width ratio of the image stay the same, what i want is to be able to set the imageview image from a URL and make the width match_parent and the height 175dp. PLEASE SOMEONE HELP ME!!!
use following code
<ImageView android:layout_width="match_parent"
android:layout_height="175dp"
android:scaleType="fitXY"
/>
public static void LoadImageFromWebOperations(String url,ImageView img) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
img.setImageDrawable(d);
} catch (Exception e) {
}
}

Android: PNG Transparency Failing with BitmapFactory.decodeStream(...) and Assets Folder

I am using the following method to pull a PNG file from the assets folder in my Android application:
public static Bitmap getBitmapFromAssets(Context context, String fileName) {
try {
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open(fileName);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
catch(Exception ex) {
ex.printStackTrace();
return null;
}
}
I am then setting the source of an ImageView, in the item of a GridView, to that Bitmap.
Here is the layout XML in question:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/containingLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"
android:background="#android:color/transparent"
android:padding="0dp"
android:layout_margin="0dp"
>
<ImageView
android:id="#+id/ivPackageIcon"
style="#style/smLargeGridItemPackageIconStyle"
/>
</LinearLayout>
And the style referred to in that XML is:
<style name="smLargeGridItemPackageIconStyle">
<item name="android:scaleType">fitXY</item>
<item name="android:layout_width">100dp</item>
<item name="android:layout_height">142dp</item>
<item name="android:layout_margin">5dp</item>
<item name="android:background">#android:color/transparent</item>
</style>
Here is the code that sets the source of the ImageView:
ImageView ivPackageIcon = (ImageView)containingView.findViewById(R.id.ivPackageIcon);
if(ivPackageIcon != null) {
Bitmap coverImage = getBitmapFromAssets(containingView.getContext(), "myimage.png");
ivPackageIcon.setImageBitmap(coverImage);
}
The PNG image has some transparent areas, but for some reason when the image is displayed in my GridView, the transparent areas come through as black.
To preempt some questions: No, the background of the Activity, ImageView, GridView, and GridView item are not black. As a matter of fact, no matter what the background colors are set to, the transparent parts of the image always come through as black.
Consider this, though...If I place the PNG image in the drawable folder and set the ImageView as follows, the transparency is perfect:
ivPackageIcon.setImageResource(R.drawable.myimage);
I'm pretty sure that I'm using the decodeStream(...) method incorrectly somehow, but I don't know what I'm doing wrong. I even modified my original method to set some options as shown here:
public static Bitmap getBitmapFromAssets(Context context, String fileName) {
try {
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open(fileName);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = true;
options.inPreferredConfig = Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
return bitmap;
}
catch(Exception ex) {
ex.printStackTrace();
return null;
}
}
But that gave me the same poor result.
Any ideas, anyone?
Thank you.
Instead this, try:
ImageView img=new ImageView(this);
Drawable d = Drawable.createFromStream(getAssets().open(path_in_assets), null);
img.setImageDrawable(d);
In case your image is made out of application resource and it is placed under res/drawable/ instead of one of the specific resolution folders (e.g. res/drawable-hdpi)
The android compiler is optimizing the PNG so the transparent pixels are made white (or black in case of GIFF files)
Resolution:
move your PNG file to res/drawable-hdpi or one of the other drawable folders, and you should be OK.

setImageBitmap has no visible effect

I have a byte array which contains an image fetched from the net. I am lazily loading them on my UI activity (or i am trying to at least :D ) using Bitmapfactory, BitmapDrawable and setImageDrawable. here is my code:
RelativeLayout r =(RelativeLayout) adap.getGroupView(Integer.parseInt(groupPos), false, null, null);
ImageView iv = (ImageView) r.findViewById(R.id.imgGruppo);
Log.w("",""+raw_img.length);
Bitmap bm = BitmapFactory.decodeByteArray(raw_img, 0, raw_img.length);
Drawable drawable = new BitmapDrawable(bm);
Log.i("","pre setimage");
iv.setImageDrawable(drawable);
//added for testing only, with no effects.
//((ELA) Activity_Titoli_2.this.getExpandableListAdapter()).notifyDataSetChanged();
//ELA is my expandable list adapter
Log.i("","post setimage"+bm.getRowBytes()); //just to see that i have actual data in raw_img and such
here is the XML involved
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayoutTitoli2_gruppo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textNomeGruppo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Large Text"
android:textColor="#FF0000"
android:padding="14dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textNoteGruppo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textNomeGruppo"
android:paddingLeft="14dp"
android:paddingRight="14dp"
android:paddingBottom="7dp"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<ImageView
android:id="#+id/imgGruppo"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:src="#drawable/icon"
/>
</RelativeLayout>
I have added "android:src..." just to check if the imageview is visible, and it is. The only problem is that i cannot change it!
I have tried setImageBitmap, using only the bitmap i created, i tried setimageDrawable creating a BitmapDrawable, but no effects at all. no errors, no nothing.
Please, where is the mistake? thank you
It's an out of memory problem, you can fix it using this method as below,
The "inSampleSize" option will return a smaller image and save memory. You can just call this in the ImageView.setImageBitmap
private Bitmap loadImage(String imgPath) {
BitmapFactory.Options options;
try {
options = new BitmapFactory.Options();
options.inSampleSize = 4;// 1/4 of origin image size from width and height
Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
My guess is you're not doing this in the right thread. You could test this out by calling this code, then rotating the screen (or opening the physical keyboard, if you have one of those phones). This will cause the UI to refresh.
Anyway, what context are you calling this in? Background thread? You'd want to update the UI in the UI thread, or you'll have to call something like 'invalidate' on the View to get it to force a re-draw.
The below solution worked for me. I used Picasa library.
private Uri getImageUri(Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(activity.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public void bitmapIntoImageView(ImageView imageView, Bitmap bitmap, Activity activity){
Uri imageUri = getImageUri(bitmap);
Picasso.with(activity).load(imageUri).into(imageView);
}
public void imagePathIntoImageView(ImageView imageView, String imagePath, Activity activity) {
Uri imageUri = Uri.fromFile(new File(imagePath));
Picasso.with(activity).load(imageUri).into(imageView);
}
Picasa: http://square.github.io/picasso/
Call the below function to set the bitmap into ImageView
bitmapIntoImageView(imageView, bitmap, MainActivity.this)

Categories

Resources