Getting images from a string path to be viewed in an imageview - android

I have some picture paths stored in a datastore and i am trying to convert them into drawables and display the in my image view, for some reason im getting a null pointer exception. Can someone please help me? Thanks
String pathName = selectedPlayer.getPicture();
Toast.makeText(this, pathName, Toast.LENGTH_SHORT).show();
Drawable d = Drawable.createFromPath(pathName);
imageView.setImageDrawable(d);

You must check file name is not null
then check that first if file exists or not
if(pathName!=null && pathName!="") <--CHECK FILENAME IS NOT NULL
{
File f = new File(pathName);
if(f.exists()) <-- CHECK FILE EXISTS OR NOT
{
Drawable d = Drawable.createFromPath(pathName);
imageView.setImageDrawable(d);
}
}
EDIT :
You have to initialize your imageview first like
imageView=(ImageView)findViewById(R.id.yourimageviewid);

Look at imageView it should not be null.
And after that try this :
bm = null;
try {
bm = BitmapFactory.decodeFile(imageView);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
imageView.setImageBitmap(bm);

Related

Itextpdf: The document has no pages error

I have a problem with making a pdf file in my android app using ITextPdf. I'm trying to convert a MPAndroidChart linechart to a bitmap and save it to a pdf file.
Here's the code for saveToPdf() method:
private void saveToPdf() {
Bitmap bitmap = saveChartToBitmap();
Document doc = new Document();
File pdfCreated = new File(getBaseContext().getFilesDir() , "PDFCreated.pdf");
try {
PdfWriter.getInstance(doc, new FileOutputStream(pdfCreated));
doc.open();
Image image = Image.getInstance(bitmap);
doc.newPage();
doc.add(image);
Toast.makeText(getBaseContext(), "Pdf created", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
} finally {
doc.close();
}
And my saveChartToBitmap() method:
private Bitmap saveChartToBitmap() {
if (lineChart.getMeasuredHeight() <= 0) {
lineChart.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
Bitmap b = Bitmap.createBitmap(lineChart.getMeasuredWidth(), lineChart.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
lineChart.layout(0, 0, lineChart.getMeasuredWidth(), lineChart.getMeasuredHeight());
lineChart.draw(c);
return b;
} else {
return null;
}
}
Don't know if something with my conversion to bitmat or creating an Image object is wrong but can't figure it out. I get: The document has no pages error. So I need advice.
Thanks in advance.
Immediately after opening document, always add an empty chunk to document so that you can avoid this exception.
doc.open;
doc.add(new Chunk(''));
Check if your saveChartToBitmap() method returns null. Also did you see the toast message.
I solved my problem. Instead of passing the bitmap to the Image.getInstance() method as an argument I converted it to a byte array and now It's working. Thanks

Android - How to get current wallpaper name

I'm developing an application that sets wallpapers from com.android.launcher3 package drawable resources. At some point I need to check if the wallpaper is set correctly so I can move on to other step.
After some research in SO and googling, I wasn't able to find any information about getting current wallpaper name.
Here is how I set the drawable which I have no problem:
try {
WallpaperManager wallpaper_manager = WallpaperManager.getInstance(m_context);
Resources res = m_context.getPackageManager().getResourcesForApplication("com.android.launcher3");
int drawable_id = res.getIdentifier(wallpaper_name, "drawable", "com.android.launcher3");
Drawable drawable = res.getDrawable(drawable_id, null);
if(drawable != null) {
wallpaper_manager.setBitmap(((BitmapDrawable)drawable).getBitmap());
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I can get the current wallpaper as drawable as well:
WallpaperManager wallpaper_manager = WallpaperManager.getInstance(m_context);
Drawable drawable = wallpaper_manager.getDrawable();
but I haven't managed to get current wallpaper name.
I need help.
Thanks in advance.
I would try this two options:
1. Using wallpaperManager
You shouold be able to get the information using this:
wallpaperManager.getWallpaperInfo();
This will return a WallpaperInfo object which contains all the data about the wallpaper.
More information
https://developer.android.com/reference/android/app/WallpaperManager.html
2. Getting the drawable file
You can also try to get the URI of the drawable like this:
String imageUri = "drawable://" + R.drawable.image;
And get the file name from there.
Hope it helps you.

Print logo on top of recipe android

Hello guys i have the problem that i want to include an image in my project and when the user click the print button the image will be printet followed by other information but i dont get it to pass the image path to the PrintTool
PrintTool.printPhotoWithPath(imagePath, this);
and the first line in printtool are this
public static void printPhotoWithPath(String filePath, Context context) {
// Get the picture based on the path
File mfile = new File(filePath/*path*/);
if (mfile.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(filePath/*path*/);
byte[] command = decodeBitmap(bmp);
printPhoto(command, context);
}else{
Log.e("PrintTools_58mm", "the file isn't exists");
}
}
So my problem is, how can i get the path from my image in drawable folder to the code?
Please remove this line
File mfile = new File(filePath/*path*/);
Provided the image is currently in your drawable directory, you can get it like this:
if (mfile.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(getResources(), R.drawable.<yourDrawableName>);
byte[] command = decodeBitmap(bmp);
printPhoto(command, context);
}else{
Log.e("PrintTools_58mm", "the file isn't exists");
}
NB Replace with the name of your Drawable.
If you require the path of the Bitmap, by default it is
String imageUri = "drawable://" + R.drawable.image;
Refer to this.
i hope this helps you
File file = new File(String.valueOf(R.mipmap.imgeName));
file.getPath();

Android. How to load the picture from memory knowing its full path?

I saved the picture on phone from application. I found a file manager it and I made sure that it really remained. Further I try to load on its full path it by BitmapFactory.decodeFile() method transferring a full path to the picture, a way to pictures at me such there, I will give an example from application:
/storage/emulated/0/Android/data/com .example.home.page/files/2015218161530.jpg
But me jumps out Exception, what decoding is impossible since the file isn't found, what for nonsense? Thanks in advance
You can use this method this will work for you
just pass path of images(where your image is store and object reference of you ImageView as a second argument)
1st argument Path of images want ot display
2nd argument object reference of `ImageView`
public static void ShowPicture(String filePath, ImageView pic) {
File f = new File(filePath);
FileInputStream is = null;
try {
is = new FileInputStream(f);
} catch (FileNotFoundException e) {
Log.d("error: ",String.format( "ShowPicture.java file[%s]Not Found",fileName));
return;
}
Bitmap = BitmapFactory.decodeStream(is, null, null);
pic.setImageBitmap(bm);
}
please also put this permission in manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
try below code that might help you.
File f = new File(PathToFiles +yourFileName);
if (f.exists()) {
Drawable d = Drawable.createFromPath(f.getPath());
imageview.setImageDrawable(d);
}

creating a drawable from sd card to set as a background in android

I am trying to use an image from the sd card and set it as the background for a relativelayout. I have tried other solutions that i have found here and elsewhere but they havent seemed to work for me. here is my code. I have commented out other ways that i have tried and didnt work. the only thing that worked for me was using setBackgroudnResource and using a resource from the app, but this was just to test to make sure mRoot was set up correctly. when I have tried all the other ways, it just doesn't set anything. Anyone know what I am doing wrong, or if there is a better way to do this?
//one way i tired...
//String extDir = Environment.getExternalStorageDirectory().toString();
//Drawable d = Drawable.createFromPath(extDir + "/pic.png");
//mRoot.setBackgroundDrawable(d);
//another way tried..
//Drawable d = Drawable.createFromPath("/sdcard/pic.png");
//mRoot.setBackgroundDrawable(d);
//last way i tried...
mRoot.setBackgroundDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "pic.png").getAbsolutePath()));
//worked, only to verify mRoot was setup correctly and it could be changed
//mRoot.setBackgroundResource(R.drawable.bkg);
You do not load a drawable from SD card but a bitmap. Here is a method to load it with the reduced sampling (quality) so the program will not complain if the image is too large. Then I guess you need to process this bitmap i.e. crop it and resize for the background.
// Read bitmap from Uri
public Bitmap readBitmap(Uri selectedImage) {
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; //reduce quality
AssetFileDescriptor fileDescriptor =null;
try {
fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage,"r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
try {
bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
fileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bm;
}
The Uri here can be supplied from a gallery picker activity.
The image then can be saved into application resources and loaded into an imageView
private void saveBackground(Bitmap Background) {
String strBackgroundFilename = "background_custom.jpg";
try {
Background.compress(CompressFormat.JPEG, 80, openFileOutput(strBackgroundFilename, MODE_PRIVATE));
} catch (Exception e) {
Log.e(DEBUG_TAG, "Background compression and save failed.", e);
}
Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(BackgroundSettings.this.getFilesDir(), strBackgroundFilename));
// Load this image
Bitmap bitmapImage = BitmapFactory.decodeFile(imageUriToSaveCameraImageTo.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
//show it in a view
ImageView backgroundView = (ImageView) findViewById(R.id.BackgroundImageView);
backgroundView.setImageURI(null);
backgroundView.setImageDrawable(bgrImage);
}
File file = new File( url.getAbsolutePath(), imageUrl);
if (file.exists()) {
mDrawable = Drawable.createFromPath(file.getAbsolutePath());
}
I suggest checking that the drawable is being loaded correctly. Some things to try:
Try using a different image on the sd card
Put pic.png in R.drawable and make sure mRoot.setBackgroundResource() does what you expect
After loading the drawable, check d.getBounds() to make sure it is what you expect

Categories

Resources