An alternate way to display images on an android app - java

I have my ImageView laid out in an .xml file and in my main java file I am using the code
static int[] images = { R.drawable.green_0, R.drawable.blue_1,
R.drawable.purple_2, R.drawable.pink_3, R.drawable.red_4,
R.drawable.yellow_5, R.drawable.white_6, R.drawable.teal_7,
R.drawable.babyblue_8, R.drawable.lightgreen_9,
R.drawable.magenta_10, R.drawable.grey_12, R.drawable.black_11 };
to display images. However, later in the code I am trying to use the line
holder.image.setImageBitmap(images[position].getImage());
which gives the error
"Cannot invoke getImage() on the primitive type int"
How else can I display images in my app to use that line of code with no errors (not declaring the images as boolean type int).

Your problem is that you are working with integer values.
You need to transform this int in Drawable, or Bitmap like this:
holder.image.setImageResource(images[position])
or
holder.image.setImageDrawable( getResources().getDrawable( images[position] ));
or
holder.image.setImageBitmap(BitmapFactory.decodeResource(getResources(), images[position]));

setImageBitmap() takes in a Bitmap object, not an int. The int you are supplying is just the id in the R.java generated resources file.
Use BitmapFactory.decodeResources():
holder.image.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), images[position]));

Related

How do I access an image as a Drawable in AndroidStudio?

I'm working on an android app using java in AndroidStudio. I have an ImageView pic and I want to set its image as a .png that I have saved in my /drawable folder. I may try
pic.setImageDrawable(R.drawable.image_name);
However, setImageDrawable() requires a Drawable, while R.drawable.image_name returns an Integer (the ID of the image).
How may I resolve this?
You can use setImageResource() for this:
pic.setImageResource(R.drawable.image);
More about it here
Use this for java
ContextCompat.getDrawable(getActivity(), R.drawable.drawable_resource_name);
and then set this drawable to your image view

How to shuffle/randomize ImageView on Android Studio Using Java?

This is the app, in xml every image have ID and I instantiate them on Main Java file using ImageView img = findByID(R.id.imgViewOnXml), but I can't randomize their position can someone help me how can I store them in an array, I'm having a trouble
Hello if i undrestand you want to create multiple imgs with random positions so you have to instantiate every imga liké this :
ImageView i = ImageView(contexte);
i.x=somex;
i.y=somey

Android Studio App crash whenever I click on login button [duplicate]

I'm running Ubuntu 16.04. And on Android Studio when I try to run my application in the emulator I get the following error:
FATAL EXCEPTION: main
Process: project name here, PID: 2528
java.lang.RuntimeException: Canvas: trying to draw too large(216090000bytes) bitmap.
at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
at android.graphics.Canvas.drawBitmap(Canvas.java:1415)
at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:528)
at android.widget.ImageView.onDraw(ImageView.java:1316)
at android.view.View.draw(View.java:17185)
at android.view.View.updateDisplayListIfDirty(View.java:16167)
at android.view.View.draw(View.java:16951)
at android.view.ViewGroup.drawChild(ViewGroup.java:3727)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3513)
at android.view.View.updateDisplayListIfDirty(View.java:16162)
at android.view.View.draw(View.java:16951)
at android.view.ViewGroup.drawChild(ViewGroup.java:3727)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3513) at
etc...
I did have to run through some hoops to get my emulator working however, needed to create a sym-link so I can run the emulator on AMD. Not sure if this is part of the problem. And for the life of me I cannot figure why it continues to do this. In my group there are others who emulate the project just fine on the same emulated phone and SDK.
Move your image in the (hi-res) drawable to drawable-xxhdpi. But in app development, you do not need to use large image. It will increase your APK file size.
The solution is to move the image from drawable/ folder to drawable-xxhdpi/ folder, as also others have mentioned.
But it is important to also understand why this somewhat weird suggestion actually helps:
The reason is that the drawable/ folder exists from early versions of android and is equivalent to drawable-mdpi. When an image that is only in drawable/ folder is used on xxhdpi device, the potentially already big image is upscaled by a factor of 3, which can then in some cases cause the image's memory footprint to explode.
This solution worked for me.
Add these lines in your Manifest application tag
android:largeHeap="true"
android:hardwareAccelerated="false"
I had the same problem.
If you try to upload an image that is too large on some low resolution devices, the app will collapse.
You can make several images of different sizes (hdpi, xxdpi and more) or simply use an external library to load images that solve the problem quickly and efficiently.
I used Glide library (you can use another library like Picasso).
panel_IMG_back = (ImageView) findViewById(R.id.panel_IMG_back);
Glide
.with(this)
.load(MyViewUtils.getImage(R.drawable.wallpaper)
.into(panel_IMG_back);
This issue can be resolved by 3 methods as follows:
Method 1:
By adding image into a res/drawable-nodpi folder (By doing this it will not pre-scale your image).
Method 2:
Generate all dpi(hdpi,ldpi,mdpi,xhdpi,xxhdpi,xxxhdpi) of image and add to drawable folder. (This process will increase APK size).
Method 3:
Add image to drawable/drawable-xxhdpi folder.
All these methods are verified.
Turns out the problem was the main image that we used on our app at the time. The actual size of the image was too large, so we compressed it. Then it worked like a charm, no loss in quality and the app ran fine on the emulator.
For this error was like others said a big image(1800px X 900px) which was in drawable directory, I edited the image and reduced the size proportionally using photoshop and it worked...!!
If you don't want your image to be pre-scaled you can move it to the res/drawable-nodpi/ folder.
More info: https://developer.android.com/training/multiscreen/screendensities#DensityConsiderations
if you use Picasso change to Glide like this.
Remove picasso
Picasso.get().load(Uri.parse("url")).into(imageView)
Change Glide
Glide.with(context).load("url").into(imageView)
More efficient Glide than Picasso draw to large bitmap
I also had this issue when i was trying to add a splash screen to the android app through the launch_backgrgound.xml . the issue was the resolution. it was too high so the images memory footprint exploded and caused the app to crash hence the reason for this error. so just resize your image using a site called nativescript image builder so i got the ldpi,mdpi and all the rest and it worked fine for me.
I just created directory drawable-xhdpi(You can change it according to your need) and copy pasted all the images to that directory.
This can be an issue with Glide. Use this while you are trying to load to many images and some of them are very large:
Glide.load("your image path")
.transform(
new MultiTransformation<>(
new CenterCrop(),
new RoundedCorners(
holder.imgCompanyLogo.getResources()
.getDimensionPixelSize(R.dimen._2sdp)
)
)
)
.error(R.drawable.ic_nfs_default)
.into(holder.imgCompanyLogo);
}
Try using an xml or a vector asset instead of a jpg or png.
The reason is quite obvious in the exception name itself i.e. the resolution of the resource is too large to render.
You can png to xml using online tools like https://svg2vector.com/ OR add your image to drawable-xxhdpi folder.
Solution for Picasso is add Transformation for resize image.
class ResizeTransformation(private val maxSize: Int) : Transformation {
override fun transform(source: Bitmap?): Bitmap? {
var result:Bitmap? = null
if (source != null) {
var width = source.width
var height = source.height
val bitmapRatio = width.toFloat() / height.toFloat()
if (bitmapRatio > 1) {
width = maxSize;
height = (width / bitmapRatio).toInt()
} else {
height = maxSize;
width = (height * bitmapRatio).toInt()
}
result = Bitmap.createScaledBitmap(source, width, height, true)
source.recycle()
}
return result
}
override fun key() = "resize()"
}
Use:
Picasso.get()
.load(url)
.transform(ResizeTransformation(2400)) //FHD+ resolution
.into(view)
Convert your all png formats into webs format. You can do it by Android Studio.

Open a resource file just with specific String variable

Sorry for the title, had troubles describing what I'm trying to do. I've always had this question for Java as a whole, but right now, its specific for Android. Let's say that I am parsing an API and get this special String, let's say "clear". Inside my drawables, I have a clear.jpg that I would like to set as an ImageView programically . That's not the hard part. What I was wondering is if there was a quick way where I Could call on the .jpg with just the variable name? I know I can easily make different if statements, such as:
if(string == "clear")
{
//setImageView to drawable/clear
}
but is there anyway I can do something such as
//setImageView to drawable/string
where string would be clear? I know obviously it would look for a string inside drawable, but is there anyway I could do what I'm describing? Just a general question I had; it was something I always wondered about.
Let me know! Thanks!
private void showImage() {
String uri = "drawable/icon";
// int imageResource = R.drawable.icon;
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
Drawable image = getResources().getDrawable(imageResource);
imageView.setImageDrawable(image);
}
Else I would recommend you to work with R.* references like this:
int imageResource = R.drawable.icon;
Drawable image = getResources().getDrawable(imageResource);
Reference -> Android - Open resource from #drawable String
With what i know, the quickest way to call up that picture is putting the
picture's name in the xml file; For instance if you want to change the background
of an imageview, you can just put in your xml file this code below
android:background="#drawable/clear".
Note the image must have been in the drawable folder. Thanks, i hope this helps.
It looks like Java 8 provides limited support for local variable annotations, but its reflection API can't give you access within method bodies. So you'd need to parse the class file itself. And for that, a library like ASM would do the trick.
if(string.equals("clear")){
int resID = getResources().getIdentifier("clear", "drawable", getPackageName());
imageView.setBackgroundResource(resID);
}
Same as other ones at the point which is using getIdentifier method.
imageView.setImageView(getResources().getIdentifier(string, "drawable",
getPackageName()));
However, by doing this, you can process without if-condition block and just specify a Drawable of the value from string directly (I think it is your intention of this question).

Applying sobel filter on jpg picture with OpenCV 2.4.10 in Java

I'm trying to add sobel operator on a jpg picture with Java. I found example here: http://www.tutorialspoint.com/java_dip/applying_sobel_operator.htm but it doesn't work. Instead it prints black image. Could someone explain to me what I did wrong, please? Other imgproc functions works well.
Here is my code:
Mat sourceImage = Highgui.imread(sourcePath, Highgui.CV_LOAD_IMAGE_GRAYSCALE);
Mat destinationImage = new Mat(sourceImage.rows(), sourceImage.cols(), sourceImage.type());
Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F){
{
put(0,0,-1);
put(0,1,0);
put(0,2,1);
put(1,0-2);
put(1,1,0);
put(1,2,2);
put(2,0,-1);
put(2,1,0);
put(2,2,1);
}
};
Imgproc.filter2D(sourceImage, destinationImage, -1, kernel);
Highgui.imwrite(destinationPath, destinationImage);
//display
new ShowImage(sourcePath, sourceImage);
new ShowImage(destinationPath, destinationImage);
First up, is there a reason why you're not using
Imgproc.Sobel(Mat src, Mat dst, int ddepth, int dx, int dy);
I'm not sure of the Java syntax used here. When does the block of puts get executed? Is it assumed to part of a constructor for a subclass of Mat that you define ? Having said that, assuming that this does what it looks like it's intended to do then it's possible that your output file type is not correctly specified; what is the value of destinationPath ?
Have you tried opening the saved file in an alternative image viewer to determine if it's the ShowImage() code or the saved file that's at fault ?
Have you tried opening the saved file in a hex editor to see if it has 'sensible' looking values or is all zeros ?

Categories

Resources