Unable to take screenshots - android

I have this code to take screenshots of layouts in Android. It is not throwing any errors, however, the screenshot is not being taken either. Can someone please help me figure out what I am doing wrong here? I am new with Eclipse and I am having a hard time figuring things out. Also if there is any other way to take screenshots can you post it as an answer to this thread? Thanks for your time!
private void getScreenshot()
{
View content = findViewById(R.id.testView);
content.setDrawingCacheEnabled(true);
content.buildDrawingCache(true);
Bitmap bitmap = Bitmap.createBitmap(content.getDrawingCache());
content.setDrawingCacheEnabled(false);
File file = new File( Environment.getExternalStorageDirectory() + "image.png");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}

Do you need to add path separator into your File? i.e.
File file = new File(Environment.getExternalStorageDirectory() +
File.separator + "image.png");
You should add a lot more logs and tests in your code to check whether it is behaving as you would expect, e.g.
Log the details of the file you are trying to create to be sure it is correct.
Once you've created the file, test that it exists, e.g. if (!file.exists())
The Bitmap.compress function returns a boolean, so you should check the return value and log it to see if it succeeded.
One other thought: maybe you need to call ostream.flush() (API docs here) to ensure the buffered data is written to the file?
I'm assuming you're writing this code for use within your app. You probably already know this, but DDMS provides a way to take screenshots in case you just want to take some yourself. Just make sure to select the device to enable the Screenshot menu option.

Related

Why does Bitmap.compress() return false when writing to internal storage?

I modified some code to write a Bitmap to internal storage (Android) that previously wrote to external storage successfully. But compress() is now returning false. Unfortunately the docs do not describe conditions that are likely to cause this, and of course since no exception being thrown there's no help there.
Below is my code.
// Only change made was to the line immediately below, now commented out
// File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/AIL_SCANS"); //Creates app specific folder
File directory = contextIn.getDir("my_pics", Context.MODE_PRIVATE);
if (!directory.exists())
directory.mkdirs();
File file = new File(directory, sFilenameIn + ".jpg");
FileOutputStream os = new FileOutputStream(file);
if (!imageIn.compress(Bitmap.CompressFormat.JPEG, 100, os))
Log.e("Error", " compress() failed (returned false)");
os.flush();
os.getFD().sync();
os.close();
Log.e("Success", " Profit!!");
My code created the Bitmap as ARGB_8888 (see below) so a couple of other Stack Overflow posts reporting a similar failure do not seem to apply here.
bmp = Bitmap.createBitmap(arrPixels, widh, height, Bitmap.Config.ARGB_8888);
An example of some code that apparently has worked well for a large number of Stack Overflow users looks almost exactly like mine. Saving and Reading Bitmaps/Images from Internal memory in Android
If you are running Android 6.0 >= you have to ask for permissions before you write into the storage.
Refer to this documentation Ask for permissions

Storing images in the Android filesystem

An Android novice here.
I'm trying to complete a task which involves creating a simple app containing buttons on a single page. Each button, when clicked, should display the corresponding image.
One thing I don't understand in the instructions is that "the images should be stored on the phone filesystem rather than compiled into the application under
resources". What exactly does this mean? Do I need to load the images into the phone manually every time I try running the application? Any guidance would be appreciated.
private void saveImage(Bitmap finalBitmap, int i ) {
File file = new File (path+name.jpg);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This method will save bitmap as a jpeg file on your phone.
P.S.
path - path of place where you want to save
name - name of image
Apps can include images in their resources/drawable folder that get added into the actual app .apk file. That makes them retrievable using R.drawable.image_name. Sounds like the instructions you are following does not want you do this. They want you to store them on the phone in the data/data/package file structure. If this is the case you can find plenty of examples on how to do this. The answer by Arsen Sench here does this.

Why i am getting this IOException from Below Code?

i have my bitmap and I want to convert my bitmap to save as image in another new file by below code.
Note: Its Working fine in all devices Except Galaxy S3. can any one help me to make this code workable in S3. i always getting this Toast while converting to new file. anyone have idea what the problem might occurring.
Bitmap photo = (Bitmap) extras.get("data");
selectedImagePath = String.valueOf(System.currentTimeMillis())
+ ".jpg";
Log.i("TAG", "new selectedImagePath before file "
+ selectedImagePath);
File file = new File(Environment.getExternalStorageDirectory(),
selectedImagePath);
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
photo.compress(Bitmap.CompressFormat.PNG, 95, fos);
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(this,
"Sorry, Camera Crashed-Please Report as Crash A.",
Toast.LENGTH_LONG).show();
}
Thanks in Advance.
It is possible the storage is not in a state to be written to, there are a number of reason this could happen. You should be checking getExternalStorageState prior to accessing the external storage. Even if it is not happening on other devices, it could happen, so best to guard against it.
If external storage is MEDIA_MOUNTED, and your problem still persists, you can get a better handle on what is happening by looking at what caused your exception by adding e.getMessage() to your Toast or logs.
You also appear to be using the top-level directory for storing your files. This should not cause a technical problem, but is considered best to create a subdirectory for your app and store files there. From the getExternalStorageDirectory docs --
Applications should not directly use this top-level directory, in
order to avoid polluting the user's root namespace.

IllegalArgumentException while writing on sdcard

I saw this problem has been met many times, but strangely I was not able to find a solution.
I am trying to write a binary file to the SDcard. This is the source code:
private void saveDataLongs() {
try
{
ObjectOutputStream oos = new ObjectOutputStream(ctx.openFileOutput(Environment.getExternalStorageDirectory().getAbsolutePath()+"/longs.bin", ctx.MODE_WORLD_WRITEABLE));
for (int w=0; w<longCount; w++)
oos.writeLong(longs[w]);
oos.close();
}
catch(IOException e)
{ e.printStackTrace(); }
}
The Manifest contains
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and I receive this error:
01-21 22:19:57.323: E/AndroidRuntime(13713): java.lang.RuntimeException: Unable to start activity ComponentInfo{it.ccc.ccc/it.ccc.ccc.Ccc}: java.lang.IllegalArgumentException: File /sdcard/longs.bin contains a path separator
From other posts I could understand that some functions are meant to write only in the private storage of the app, so they don't expect to manage directories and paths.
Is some one able to help me? Whall I use a different method to write the data to the sd, or just make some other action before doing it? I'm trying to write to the sdcard a simple binary file (btw it's a precalculated sequence of number, and I need to pass it to my PC and then move it back to the assets, so, if there is a different way to obtain this goal, it's ok anyway).
Thank you very much.
You say that you are trying to write to external storage, but you are calling openFileOutput(), which is for internal storage.
Change:
new ObjectOutputStream(ctx.openFileOutput(Environment.getExternalStorageDirectory().getAbsolutePath()+"/longs.bin", ctx.MODE_WORLD_WRITEABLE));
to:
new ObjectOutputStream(new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "longs.bin")));
or, better yet, to:
new ObjectOutputStream(new FileOutputStream(new File(ctx.getExternalFilesDir(null), "longs.bin")));
I like CommonsWare's answer. I would simply like to add that if you ever DO want to go down a path, don't use /. Use File.separator. I don't think I've ever had any errors come up when simply using / but still.
So if you made a sub-folder called "To-dos" in the sdcard's directory, you would do something like the following:
new ObjectOutputStream(new File(Environment.getExternalStorageDirectory() + File.separator + "To-dos", "longs.bin"));

Android moving a photo from one folder to another

I'm using the below code to transfer an image from one folder on external memory, to another..as specified by the user. The problem is, the photo gets copied to the destination folder fine..but I can't open or view it. I use a file manager named Astro to see if it was successfully moved, and it is..but I'm unable to open it both in Astro and in the resident Gallery app. I'm thinking something is wrong with my code and maybe I need read and/or decode to photo before I can move it, from what I understand about the File class it is just an abstraction. Any guidance on this would be greatly appreciated, here is the code I'm currently using.
File img = new File(imgViewPath);
File output = new
File(Environment.getExternalStorageDirectory().toString() + "/MyAppPics/" + moved,
img.getName());
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(output));
}
finally {
if (out != null) {
out.close();
}
}
}catch(Exception e){
e.printStackTrace();
}
You are not writing anything to the output stream. Read the bytes from the input stream and write it to the output stream, only then the files will get copied.

Categories

Resources