create drawable from path problem - android

For some reason d=null when creating a drawable from coverArtURLStr, which is the full http path to the resource on the LAN.
Anything obvious wrong? It's a path to a .png
[I can access the LAN OK, and Data.defaultCoverArt works fine]
public static void updateCoverArt(String coverArtURLStr)
{
String coverArtURL = coverArtURLStr;
Drawable d;
if (coverArtURL.equals(""))
d = Data.defaultCoverArt;
else
d = Drawable.createFromPath(coverArtURL);
Data.coverArtIV.setImageDrawable(d);
}

I don't think Drawable.createFromPath() method can handle URLs. Try this solution Android Drawable Images from URL.

Related

how do I transform a string of url's into drawable?

I currently have an arraylist as follows:
private void loadImages() {
images = new ArrayList<>();
images.add(getResources().getDrawable(R.drawable.imag1));
images.add(getResources().getDrawable(R.drawable.imag2));
images.add(getResources().getDrawable(R.drawable.imag3));
}
I want to be able to convert a url into these drawables such that:
drawable1 = "http.someimage.com/image.png"
drawable2 = "http.someimage.com/newimage.png"
followed by
private void loadImages() {
images = new ArrayList<>();
images.add(getResources().getDrawable(drawable1));
images.add(getResources().getDrawable(drawable2));
...etc }
Is there any easy way to go around this? I definitely want to stick to drawables ,but I cant find any way to convert a url to drawable
Any ideas? Thanks!
If you have a URL of the picture you need to download it first.
You can't "convert" a URL into a drawable.
you need something like this:
URL url = new URL("http.someimage.com/image.png");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Then if you need to add the image into an ImageView object you can call the method .setImageBitmap(bmp).
Otherwise there are ways to extract a Drawable object from the Bitmap
you can check this previous answer. then once you have the drawable you can add it to your arraylist.
Hope I got your question right
P.S.: be sure not to do this on main thread since it is a network operation! use a thread or an asynctask

How to check android drawable type?

Can I check the type of drawable at runtime whether it is an xml shape/selector/layer-list or jpg/png/gif file?
You can get type of drawable with this:
public static String getTypeOfDrawable(int drawableId,Context context) {
Drawable resImg = context.getResources().getDrawable(drawableId);
return resImg.getClass().toString().replace("class android.graphics.drawable.","");
}
You will get result like:
BitmapDrawable
StateListDrawable
Then you if it is BitmapDrawable its not that hard to get format of file

How to get screenshot saved path by Cocos2d-x on android

I use saveToFile method to save screenshot, and I check CCLOG, it shows /data/data/com.xxx.xxx/files/xxx.png
However, when I use Java to get this file, it says "No such file or directory"....
What can I do?
I had the same problem. Apparently, cocos2dx never creates the writable path directory so the screenshot doesn't get saved.
My solution was to, instead of calling CCRenderTexture::saveToFile, copy its implementation and manually save the file to a different path:
std::string MyClass::takeScreenshot(CCScene* scene) {
cocos2d::CCSize screenSize = cocos2d::CCDirector::sharedDirector()->getWinSize();
cocos2d::CCRenderTexture* tex = cocos2d::CCRenderTexture::create(screenSize.width, screenSize.height);
tex->setPosition(ccp(screenSize.width/2, screenSize.height/2));
//use a different dir than cocos default writable path
std::string filename = "/sdcard/Android/data/screenshot.png";
tex->begin();
scene->getParent()->visit();
cocos2d::CCImage* img = tex->newCCImage(true);
img->saveToFile(filename.c_str(), true);
CC_SAFE_DELETE(img);
tex->end();
return filename;
}
I also had the same problem. When I try renderTexture->saveToFile method, I can't submit path to java. No matter, I used getWritablePath() or set the path directly "/sdcard/Android/data/com.xxx.xxx/snapshot.jpg".
I try also to solve this problem on the advice of Facundo Olano. But CCImage compose only solid black image.
Finally I combine this two methods. First, I make an image by renderTexture->saveToFile:
void MyScene::pressFaceBook()
{
...
RenderTexture* renderTexture = RenderTexture::create(sharedImage->getBoundingBox().size.width, sharedImage->getBoundingBox().size.height, Texture2D::PixelFormat::RGBA8888);
renderTexture->begin();
sharedImage->visit();
renderTexture->end();
renderTexture->saveToFile("snapshot.jpg", Image::Format::JPG);
const std::string fullpath = FileUtils::getInstance()->getWritablePath() + "snapshot.jpg";
sharedImage->setVisible(false);
this->runAction(Sequence::create(DelayTime::create(2.0f),
CallFunc::create(std::bind(&MyScene::shareFaceBook, this, fullpath)),
NULL));
}
And then I use initWithImageFile with the transferred file name:
void MyScene::shareFaceBook(const std::string& outputFile)
{
const std::string joutputFile = "/sdcard/Android/data/com.xxx.xxx/snapshot.jpg";
cocos2d::Image* img = new Image;
img->initWithImageFile(fullpath);
img->saveToFile(joutputFile);
CC_SAFE_DELETE(img);
singleton->shareFaceBook(joutputFile);
}
A delay of 2 seconds is needed to capture the screenshot.
Of course, instead com.xxx.xxx you must substitute your app name.

Android : Calling images from drawable and displaying on the screen

I am designing a Image Puzzle(JigSaw) game. I am stuck in a problem that, when I start the game it shows the option "New Image" but, when I click on that, it gives an error message, means images from the drawable folder are not loading.
I did research and i came with this, i have implemented this in my code. but, it gives an error.. "Could not Load."
protected void newImage()
{
LinkedList<Uri> availableImages = new LinkedList<Uri>();
findInternalImages(availableImages);
if(availableImages.isEmpty())
{
Toast.makeText(this, getString(R.string.error_could_not_load_image), Toast.LENGTH_LONG).show();
return;
}
int index = new Random().nextInt(availableImages.size());
loadBitmap(availableImages.get(index));
}
protected void findInternalImages(List<Uri> list)
{
Field[] fields = R.drawable.class.getFields();
for(Field field: fields)
{
//String name = field.getName();
//if(name.startsWith(FILENAME_IMAGE_PREFIX))
//{
//int id = getResources().getIdentifier(name, "drawable", getPackageName());
for(int j=1;j<13;j++)
{
Drawable drawable = getResources().getDrawable(getResources()
.getIdentifier("image_"+j, "drawable", getPackageName()));
}
//}
}
}
My Problem is,
when i run the program it should show images from drawable folder and when i choose the one then actual scrambling should start. so, one can play the jig saw game.
Start by checking that your images are in a Android compatible format, that was causing me problems to begin with. I normally stick to .png now.
This is the code you will need to modify the image
ImageView pwrSwap = (ImageView) beaconitems.findViewById(R.id.yourImageID);
pwrSwap.setImageResource(R.drawable.yourImage);
http://developer.android.com/guide/appendix/media-formats.html

Loading Images to Textview with AsyncTask

My problem is the following: I try to load images to a text view like this:
URLImageParser p = new URLImageParser(textView, this);
Spanned htmlSpan = Html.fromHtml(textWithImages, p, null);
textView.setText(htmlSpan);
I followed this example https://stackoverflow.com/a/7442725/1835251
If I load images from the web it works perfectly.
I modified to code a bit to load certain images from SDCard as well.
In the "doInBackground" Method of the async task I implemented this:
#Override
protected Drawable doInBackground(String... params) {
String source = params[0];
Drawable d = null
if(source != null) {
if(source.startsWith("/myApp/images/")) {
localImage = true;
}
}
if(localImage) {
String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
d = Drawable.createFromPath(sdcard+source);
d.setBounds(0, 0, 0 + (int)(d.getIntrinsicWidth()), 0
+ (int) (d.getIntrinsicHeight()));
localImage = false;
} else {
// load images from internet
}
return d;
localImage is a boolen which is set to determine if the current source "points" to an
image from the internet or a local image.
As stated before: Loading images from the internet works perfectly.
BUT when I load images from the SDCard it sometimes happens that not all images are displayed.
The whole text (including the images) gets cut as if it hasn't been loaded correctly.
I figured out that this happens much more often on a Samsung Galaxy S3 than on a Samsung S Plus.
On the S3 I sometimes load only 1 or 1.5 images and the rest gets cut.
The S Plus always loads all 4 images but rarely cuts the last 2 or 3 sentences of the text.
I think that it is a sort of a timing problem with the AsyncTask but I never worked with it before.
I know this is a really large post but I hope that someone still can help me.
Best regards
Siggy
Ok I am stupid... I solved it!
I forgot that I only need the AsyncTask if I load images from the internet. For local images I don't need that.
Solution for the interested:
ImageGetter imgGetter = new ImageGetter() {
#Override
public Drawable getDrawable(String source) {
String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
Drawable d = Drawable.createFromPath(sdcard+source);
d.setBounds(0, 0, 0 + (int)(d.getIntrinsicWidth()), 0
+ (int) (d.getIntrinsicHeight()));
return d;
}
};
Spanned htmlSpan = Html.fromHtml(textAndImage, imgGetter, null);
textView.setText(htmlSpan);

Categories

Resources