Cannot get Screenshot using Android Espresso TestFramework - android

Getting the path as of following but cannot access the screenshot, any idea?
Brings up path : /storage/emulated/0/test-screenshots/screenshot-001.png
while using the method:
Trying to capture a screenshot using the following method in Android Espresso:
takeScreenshot("screenshot-001", getActivity());
public static void takeScreenshot(String name, Activity activity)
{
// In Testdroid Cloud, taken screenshots are always stored
// under /test-screenshots/ folder and this ensures those screenshots
// be shown under Test Results
String path = Environment.getExternalStorageDirectory()+ "/test-screenshots/" + name + ".png";
Log.d("Logs", "Image Path is " + path);
View scrView = activity.getWindow().getDecorView().getRootView();
scrView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(scrView.getDrawingCache());
scrView.setDrawingCacheEnabled(false);
OutputStream out = null;
File imageFile = new File(path);
try {
out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
} catch (java.io.FileNotFoundException e) {
// exception
} catch (java.io.IOException e) {
// exception
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception exc) {
}
}
}

Related

Display an image even after the user has closed the app

How do I load the same picture the user has selected even after the user closes the app?
I currently have the following code which I call in onCreate, but the Bitmap is null every time the user closes the app.
private void loadImageFromStorage() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File myPath = new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
File f = new File(directory.getAbsolutePath(), "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView coverView = findViewById(R.id.cover_view);
coverView.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Assuming the image was actually saved as profile.jpg and it exists in the imageDir folder, all you need to do to load the image (based on your current usage) is:
private void loadImageFromStorage() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File myFile = new File(directory.getAbsolutePath(),"profile.jpg");
if(myFile.exists()){
try {
Bitmap b = BitmapFactory.decodeFile(myFile.getAbsolutePath());
ImageView coverView = findViewById(R.id.cover_view);
coverView.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d("MyApp", "The image file does not exist.");
}
}
But if the image is not yet saved or non-existence, then you may need to ask another question that details how you are currently doing it. But this setup will allow you know if that image actually existts.

Image not showing when passed as an intent extra

I'm trying to pass the screenshot of screen with an explicit intent but the screen shows black screenshot(refer image here). As soon as i click share, a toast appears saying sending failed. Here's the code to capture screenshot and send it to other app:
public void getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
f = new File(this.getFilesDir(), "screenshotFile");
try {
if (!f.exists())
f.createNewFile();
} catch (IOexception e) {
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This code sends the data to whatsapp:
public void shareWhatsapp(View view) {
try {
myVib.vibrate(50);
getScreenShot(view);
//String fileName = "screenshotFile";
//Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
try {
intent.setPackage("com.whatsapp");
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "App not installed", Toast.LENGTH_SHORT).show();
}
//TODO: APP CAN CRASH HERE
if (position > 0) {
try {
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f);
} catch (Exception e) {
e.printStackTrace();
} finally {
intent.putExtra(Intent.EXTRA_TEXT, Titles.get(position - 1) + ": " + Links.get(position - 1)); //position problems
}
} else {
try {
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f);
} catch (Exception e) {
e.printStackTrace();
} finally {
intent.putExtra(Intent.EXTRA_TEXT, Titles.get(0) + ": " + Links.get(0)); //position problems
}
}
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Can someone help me with this?
First, you are writing the file to internal storage. Third-party apps do not have access to your app's internal storage.
Second, you are using Uri.fromFile(), which is starting to be discontinued.
Your safest long-term course of action is to have a ContentProvider serve your file from its location on internal storage, then use a Uri associated with that ContentProvider.

android-how to save a view to sd card

i have a imageview , i am trying to save bitmap from imageview by this method
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
the rgb of saved image is not like that it looks in running app,so i am wondering if there is any way to save image view directly to a sd card rather getting the bitmap and then save it to sd card.
please help me i have tried everything.
You can read and write object using below code :
public static void witeObjectToFile(Context context, Object object, String filename)
{
ObjectOutputStream objectOut = null;
try
{
FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (objectOut != null)
{
try
{
objectOut.close();
} catch (IOException e)
{
// do nowt
}
}
}
}
public static Object readObjectFromFile(Context context, String filename)
{
ObjectInputStream objectIn = null;
Object object = null;
try
{
FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e)
{
// Do nothing
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
if (objectIn != null)
{
try
{
objectIn.close();
} catch (IOException e)
{
// do nowt
}
}
}
return object;
}
For example ArrayList can be saved as :
ImageView abcImage = (ImageView) readObjectFromFile(context, AppConstants.FILE_PATH_TO_DATA);
and write as :
witeObjectToFile(context, abcImage, AppConstants.FILE_PATH_TO_DATA);
Try to use this
public void onClick(View v) {
if (v.getId() == R.id.btnSaveImage) {
imageView.setDrawingCacheEnabled(true);
Bitmap bm = imageView.getDrawingCache();
storeImage(bm);
}
}
private boolean storeImage(Bitmap imageData) {
// get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/yourappname/";
File sdIconStorageDir = new File(iconsStoragePath);
// create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
File file = new File(sdIconStorageDir.toString() + File.separator + "fileName");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
MediaScannerConnection.scanFile(this, new String[] { file.getPath() },
new String[] { "image/jpeg" }, null);
Toast.makeText(this, "Snapshot Saved to " + file, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}

displaying downloaded images in my phone gallery

I'm trying to tell my app to make some images which are already downloaded appear in the gallery of my phone.
the images are well download and displayed in my app, they have no extension, their names are only a md5.
here is how i'm trying to do so:
public static void makePhotoAppearOnGallery(Activity activity, String md5) {
final String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
final String festivalDirectory_path = extStorageDirectory
+ Constants.IMAGES_STORAGE_PATH;
File imageOutputFile = new File(festivalDirectory_path, "/");
if (imageOutputFile.exists() == false) {
imageOutputFile.mkdirs();
}
File imageFile = new File(imageOutputFile, md5);
Bitmap bm = decodeFile(imageFile.getAbsoluteFile());
OutputStream outStream = null;
try {
outStream = new FileOutputStream(imageFile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
MediaStore.Images.Media.insertImage(activity.getContentResolver(), festivalDirectory_path, festivalDirectory_path+"/"+md5, "myDownloadedPics");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scanFile(imageFile,activity);
}
public static void scanFile(File downloadedFile, Context mContext){
Uri contentUri = Uri.fromFile(downloadedFile);
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
mediaScanIntent.setData(contentUri);
mContext.sendBroadcast(mediaScanIntent);
}
the app crashes on this line:
MediaStore.Images.Media.insertImage(activity.getContentResolver(), festivalDirectory_path, festivalDirectory_path+"/"+md5, "myDownloadedPics");
with this message:
java.io.FileNotFoundException: /mnt/sdcard/data/com.example.app/images: open failed: EISDIR (Is a directory)
Does anyone know from what it comes?
I had the same problem. It turns out this error happens when there is a folder with the same file name. For example I had a folder named "log.txt".

Writing to text file in "APPEND mode" in emulator-mode,

In my Android app I should store the data from user in simple text-file, that I created in the raw directory. After this, I'm trying to write file in APPEND MODE by using simple code from the Google's examples:
try
{
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_APPEND);
fos.write((nameArticle+"|"+indexArticle).getBytes());
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
But nothing happens: no exceptions, but I can see nothing in my FILE_NAME, besides the single record, which was added by me.
What am I doing wrong ? Is it possible at common to write to file in emulator ?
openFileOutput will only allow you to open a private file associated with this Context's application package for writing. I'm not sure where the file you're trying to write to is located. I mean full path. You can use the code below to write to a file located anywhere (as long as you have perms). The example is using the external storage, but you should be able to modify it to write anywhere:
public Uri writeToExternalStoragePublic() {
final String filename = mToolbar.GetTitle() + ".html";
final String packageName = this.getPackageName();
final String folderpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + packageName + "/files/";
File folder = new File(folderpath);
File file = null;
FileOutputStream fOut = null;
try {
try {
if (folder != null) {
boolean exists = folder.exists();
if (!exists)
folder.mkdirs();
file = new File(folder.toString(), filename);
if (file != null) {
fOut = new FileOutputStream(file, false);
if (fOut != null) {
fOut.write(mCurrentReportHtml.getBytes());
}
}
}
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
return Uri.fromFile(file);
} finally {
if (fOut != null) {
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
In the example you have given, try catching 'I0Exception`, I have a feeling you do not have permission where you are trying to write.
Have a Happy New Year.

Categories

Resources