I am trying to take a Bitmap and display it in an ImageView.
ImageView iv = new ImageView(this);
Bitmap bMap = BitmapFactory.decodeFile("/res/drawable/" + imageFileName);
iv.setImageBitmap(bMap);
That's my code for it. I create an ImageView and a Bitmap. I want to display my Bitmap in my ImageView. But I always get these two errors on the iv.setImageBitmap(bMap); statment
Syntax error on token "bMap", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
Does anybody has an idea why this happens and what i have to change?
In OP's pastebin code I've found the following snippet:
String imageFileName =getIntent().getStringExtra("imageFileName");
//String bildquelle = "R.drawable." + imageFileName;
public class ImageChange extends Activity {
ImageView iv = new ImageView(this);
String bildquelle = "R.drawable." + imageFileName;
int id = getResources().getIdentifier(bildquelle, "drawable", getPackageName());
Bitmap bMap = BitmapFactory.decodeResource(getResources(), id);
//Bitmap bMap = BitmapFactory.decodeFile("/res/drawable/" + imageFileName);
iv.setImageBitmap(bMap);
}
There are a couple of problems with this including:
The code is not inside a method body.
The code is a Activity subclass.
The code improperly calls getResources().getIdentifier(...).
Instead of the above code I suggest MERGING the rest of activity with the following:
public class BildAnzeigen extends ActionBarActivity {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bild_anzeigen);
iv = (ImageView) findViewById(R.id.my_image_view); // replace the id with the one from layout definition
handleIntent(getIntent());
}
private void handleIntent(Intent intent) {
String imageFileName = intent.getStringExtra("imageFileName");
int id = getResources().getIdentifier(imageFileName, "drawable", null);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), id);
iv.setImageBitmap(bMap);
}
}
Note: This will not work if the images are not compiled within your apk. There's no way to add anything to drawables after building. It just doesn't work that way.
Related
I am working on a barcode reader app and I want to show product image when the barcode read, so I renamed photos with product barcode numbers and put drawables folder. Photo name is for ex 1234567, try to retrieve with barcodeNo. But I got error on barcodeNo. How can i do this ?
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageResource(R.drawable.barcodeNo);
just pass your code in getImage method to findout your image from drawable folder.
iv.setImageResource(getImage(barcodeNo));
public int getImage(String imageName) {
int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());
return drawableResourceId;
}
String uri = "#drawable/myresource"; // where myresource (without the extension) is the file
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
Drawable res = getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);
OR
imageview.setImageResource(imageResource)
#Narendra Sorathiya answer is right. you have write this code for solving the NullPointerException, which you posted on screenshot:
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageResource(getImage(barcodeNo));
.
.
.
.
public int getImage(String imageName) {
int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());
return drawableResourceId;
}
I want to get Bitmap from SimpleDraweeView of Fresco lib, and save it to SD Card.
SimpleDraweeView is child class of ImageView so it should support getDrawable() but calling this method throws ClassCastException
BitmapDrawable bitmapDrawable = (BitmapDrawable) viewHolder.drawee.getDrawable();
ClassCastException: com.facebook.drawee.generic.RootDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
What is the wayout for this?
s1rius's answer mentioned by Morrison helped me. Here's the code that I used.
ImageRequest downloadRequest = ImageRequest.fromUri(uri);
CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(downloadRequest, context);
if (ImagePipelineFactory.getInstance().getMainFileCache().hasKey(cacheKey)) {
BinaryResource resource = ImagePipelineFactory.getInstance().getMainFileCache().getResource(cacheKey);
File cacheFile = ((FileBinaryResource) resource).getFile();
File savedImageFile = new File(Constants.APP_PATH_SAVED_QUOTES, "M1iS1" + "_" + currentPosition + ".jpg");
}
Then I copied cacheFile into savedImageFile.
I have been trying with no avail to set my facebooks profile picture as a Linearlayout background in my application.
here are the two ways I tried to do this:
first way: got the uri from the profile picture and converted it to drawable
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
LinearLayout banner = (LinearLayout)findViewById(R.id.banner);
Profile profile = Profile.getCurrentProfile();
if(profile != null){
// profile_pic_id.setProfileId((profile.getId()));
Drawable d;
Uri uri = profile.getLinkUri();
//also tried profile.getProfilePictureUri(random_num,random_num)
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
d = Drawable.createFromStream(inputStream, uri.toString());
} catch (FileNotFoundException e) {
d = getResources().getDrawable(R.drawable.blue_material);
}
banner.setBackgroundDrawable(d);
}
}
now this always threw an exception so the Drawable i get is the blue_material one (the Drawable set in the catch block), so if anyone knows why its throwing an exception all the time I'd be grateful.
second way: converted the ProfilePictureView to ImageView and then used getDrawable() on the ImageView.
ProfilePictureView profilePictureFB=(ProfilePictureView)findViewById(R.id.pic);
profilePictureFB.setProfileId((profile.getId()));
ImageView fbImage = ( ( ImageView)profilePictureFB.getChildAt( 0));
banner.setBackgroundDrawable(fbImage.getDrawable());
now this resulted in having a background with the default picture facebook puts when someone has no profile pic.
AND whenever I use decodeStream an exception gets thrown.(example below)
URL img_url =new URL("https://graph.facebook.com/"+profile.getId()+"/picture?type=normal");
Bitmap bmp =BitmapFactory.decodeStream(img_url.openConnection().getInputStream());//bmp a bitmap
I didnt want to resort to asking this question on stackoverflow because I wanted to solve it myself, but I tried for so very long, so I had to get some help.
Thanks for anyone who answers :)
I solved it!!
i used imageLoader, and for some reason the url works with it, here is the code:
imageView = (ImageView) findViewById(R.id.pic);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageLoader = ImageLoader.getInstance();
Profile profile = Profile.getCurrentProfile();
if(profile != null){
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
imageLoader.displayImage("http://graph.facebook.com/" + profile.getId() + "/picture?width=400&height=400", imageView, options);
// banner.setBackgroundDrawable(imageView.getDrawable());
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
the method setScaleType stretches my imageview across all myLinearLayout.
for more information about the universal image loader visit this link:
https://github.com/nostra13/Android-Universal-Image-Loader
I m not sure but this what i used to do
img_url =new URL("https://graph.facebook.com/"+uname+"/picture?type=normal");
bmp =BitmapFactory.decodeStream(img_url.openConnection().getInputStream());//bmp a bitmap
linearlayout.setImageBitmap(bmp);//your linear layout
I want to create a dynamic image view where every image in my gallery will going to use bitmapfactory and not image drawable that binds in the image view. Is there some sites that has bitmapfactory tutorial for this? i believe that using bitmapfactory uses less memory that binding the image into image view? Is this right? I want also to minimize the risk of memory leaks thats why I want to use bitmapfactory. Please help. I cant find basic examples that teaches bitmapfactory.
Building Bitmap Objects
1) From a File
Use the adb tool with push option to copy test2.png onto the sdcard
This is the easiest way to load bitmaps from the sdcard. Simply pass the path to the image to BitmapFactory.decodeFile() and let the Android SDK do the rest.
public class TestImages extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");
image.setImageBitmap(bMap);
}
}
All this code does is load the image test2.png that we previously copied to the sdcard. The BitmapFactory creates a bitmap object with this image and we use the ImageView.setImageBitmap() method to update the ImageView component.
2) From an Input stream
Use BitmapFactory.decodeStream() to convert a BufferedInputStream into a bitmap object.
public class TestImages extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
FileInputStream in;
BufferedInputStream buf;
try {
in = new FileInputStream("/sdcard/test2.png");
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
}
This code uses the basic Java FileInputStream and BufferedInputStream to create the input stream for BitmapFactory.decodeStream(). The file access code should be surrounded by a try/catch block to catch any exceptions thrown by FileInputStream or BufferedInputStream. Also when you're finished with the stream handles they should be closed.
3) From your Android project's resources
Use BitmapFactory.decodeResource(res, id) to get a bitmap from an Android resource.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
image.setImageBitmap(bMap);
}
I'm writing an app that stores a String in an SQLite database, which represents the filepath of an image on the /sdcard/. I have this code in the onCreate() one of my activities:
final Intent receivedIntent = getIntent();
String imageStr = receivedIntent.getExtras().getString("picture");
ImageView imageView = (ImageView) findViewById(R.id.pPicture);
File file = new File (imageStr);
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imageStr);
imageView.setImageBitmap(bitmap);
}
The code works when I'm first loading the activity, but when I switch between screen orientations, it crashes my application. Any ideas on what I can do to fix this? I'd like to bee able to continue switching between orientations, but I don't need to refresh each time.
Also, I'm somewhat new, so please try to keep your answers not too complicated if possible.
Note that the file does exist in all cases.
I think your app crashes because of OutOfMemoryException. Try recylcing the bitmap in onDestroy():
#Override
public void onDestroy() {
super.onDestroy();
ImageView imageView = (ImageView) findViewById(R.id.pPicture);
Drawable drawable = imageView.getDrawable();
imageView.setImageDrawable(null);
if (drawable instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
bitmap.recycle();
bitmap = null;
}
}