Android App saving to SD Card - java

I'm having some trouble. I'm new to java and Android programming. I'm using a template to get started and I'm stuck.
I have a app that pulls images from my Tumblr Feed and presents them on the screen with a download button. It works fine but installs to the root of the internal storage. How do I save it to a folder in the internal storage called "/Pictures/Tumblr"?
My code is:
public void onLoadingComplete(final String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
// close button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "tumblr_"+images.get(position).getId()+".jpg");
try {
fOut = new FileOutputStream(file);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
String saved = getResources().getString(R.string.saved);
Toast.makeText(getBaseContext(), saved + " " + file.toString(), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
I've tried changing the
File file = new File(path, "tumblr_"+images.get(position).getId()+".jpg");
To
File file = new File(path+"/Pictures/Tumblr", "tumblr_"+images.get(position).getId()+".jpg");
But I know it's wrong.
Can anyone help?

Related

RelativeLayout screenshot including mapFragment saves black image

I have a RelativeLayout view which includes some TextViews and a map fragment. I want to take a screenshot of the whole screen (including the map as displayed and the text) and save it. Everything working as expected but the view with the map shows a black image. How is this possible?
I've also tried with some delay interval to be sure the map is fully loaded but didn't worked.
Bitmap bitmap = takeScreenshot();
createDirectoryAndSaveFile(bitmap,intent.getStringExtra("TEST"));
public Bitmap takeScreenshot() {
View rootView = findViewById(R.id.relative_layout);
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
private void createDirectoryAndSaveFile(Bitmap bitmap, String name) {
File folder = new File(Environment.getExternalStorageDirectory() +"/Test");
if (!folder.exists()) {
File screenshoDir = new File(Environment.getExternalStorageDirectory() + "/Test/");
screenshoDir.mkdirs();
}
File file = new File(new File(Environment.getExternalStorageDirectory() + "/Test/"), name);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
MediaScannerConnection.scanFile(this, new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
} catch (Exception e) {
e.printStackTrace();
}
}

How to send image from app via messenger?

I want to send image from my app via messenger. I was looking on Stack Overflow and I found answer which works for WhatsApp. When I tried to change "com.whatsapp" to "com.facebook.orca", it stops working. Here is my code:
public void shareImageMessenger() {
Bitmap adv = BitmapFactory.decodeResource(getResources(), R.drawable.koza);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
adv.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "temporary_file_1.jpg");
try {
f.createNewFile();
new FileOutputStream(f).write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM,
Uri.parse( Environment.getExternalStorageDirectory()+ File.separator+"temporary_file_1.jpg"));
share.setPackage("com.facebook.orca");
startActivity(Intent.createChooser(share, "Share Image"));
}
After spending a lot of time on this:
Check if permissions are given. Then:
Step 1: Create ImageView of the image you want to in the activity and then convert it itno bitmap
ImageView imageView = findViewById(R.id.image);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
//save the image now:
saveImage(bitmap);
//share it
send();
Step 2: Store the image in internal folder:
private static void saveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
Log.i("Directory", "==" + myDir);
myDir.mkdirs();
String fname = "Image-test" + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Step 3: Send the saved image:
public void send() {
try {
File myFile = new File("/storage/emulated/0/saved_images/Image-test.jpg");
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
Intent sharingIntent = new Intent("android.intent.action.SEND");
sharingIntent.setType(type);
sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
startActivity(Intent.createChooser(sharingIntent, "Share using"));
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Now after sending you can delete the saved image if you don't want it in your storage. Check other link to do that.
Referring your linked post,You could modify the share intent.
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///assets/epic/adv.png"));
this.startActivity(Intent.createChooser(share, "share_via"));
The intent launches the apps which handles Intent.ACTION_SEND. If you want specific app to be respond, make sure you are aware of the package name and you need set package name share.setPackage("");

Share screen shoot android studio(multi-times)

I have app and i am letting user to make screenshot and share it, all working fine just one problem..
When user for example make screenshot and press on Facebook icon > then he press cancel sharing ,next time when he want to do another share he will see the old screen shoot , how can make it take the last screenshot always??
** i have each image has different file name but the share always taking the last action that didn't finish.
(if user do share all will work fine ,next screen shoot will be the new one )
here is my code
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() ,
"SCREEN"
+ System.currentTimeMillis() + ".png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
private void shareIt() {
uri =Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "جرب تطبيق نكت عراقية مضحكة الان!";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "تطبيق نكت
عراقية مضحكة");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "مشاركة بواسطة"));
}
You can do something like this.Remove the System.currentTimeMillis() from the name of your image so, that you do not have multiple copies of screenshots.So when you upload the image it always have the fresh screenshots.Now when you capture another screenshot you have to check is file exist if exist then delete it.
public void saveBitmap(Bitmap bitmap)
{
File file = new File(Environment.getExternalStorageDirectory(), "SCREEN.png");
if (file.exists()) {
file.delete();
}
imagePath = new File(Environment.getExternalStorageDirectory() , "SCREEN.png");
FileOutputStream fos;
try
{
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch (IOException e)
{
Log.e("GREC", e.getMessage(), e);
}
}

Android saving images in application context

In my MainActivity onCreate() I want to populate a listview. This listview contains Strings and Bitmaps.
What's the best way to save these data to get them back when the application is restarted ?
There is my own cache solution:
public class MyCache {
private String DiretoryName;
public void OpenOrCreateCache(Context _context, String _directoryName){
File file = new File(_context.getCacheDir().getAbsolutePath() + "/" + _directoryName);
if(!file.exists()){
file.mkdir();
}
DiretoryName = file.getAbsolutePath();
}
public void SaveBitmap(String fileName, Bitmap bmp){
try {
File file = new File(DiretoryName+ "/" + fileName);
if(file.exists()){
file.delete();
}
FileOutputStream Filestream = new FileOutputStream(DiretoryName + "/" + fileName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
Filestream.write(byteArray);
Filestream.close();
bmp.recycle();
}
catch (Exception e){
e.printStackTrace();
}
}
public Bitmap OpenBitmap(String name){
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
File file = new File(DiretoryName+ "/" + name);
if(file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(DiretoryName+ "/" + name, options);
return bitmap;
}
else{
return null;
}
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
public void CleanCacheBitMap(){
File file = new File(Diretorio);
if(file.exists()){
file.delete();
}
}
}
And onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
cache = new MyCache();
cache.OpenOrCreateCache(this, "TheFolderNameForOpenOrSaveInAppCache");
}
And for save on runtime:
cache.SaveBitmap("BitMapName", YourBitmap);
And openning on runtime:
Bitmap bmp = cache.OpenBitmap("BitMapName");
This solution save any bitmap, in particular folder in your app cache (internal storage).
There are different possibilities depending on how tightly you want to hang on to these files. The most reliable is the method getFilesDir(). Each application has its own private "files directory".
All the details are here:
https://developer.android.com/training/basics/data-storage/files.html
The cache directory (getCacheDir()) is similar but the user can erase the cache contents so that's more for temporary files you don't want to hang onto.
Strings and bitmaps can both be saved to files. You can create your own name value mapping file to link them. Or use JSON objects, or many other things to organize your list of strings/bitmaps.

Error when trying to share an image

So I take a screenshot of my activity, then save it to "screenshot.png". When trying to share it via, let's say, Whatsapp, I get an error: "could not send image". Same with gmail, pushbullet and basically all other apps. Therefore, I conclude that the file somehow exists, but it is either empty, or messed up... I don't know, honestly.
Here's the code:
Taking the activity screenshot:
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
Saving the screenshot:
public void saveBitmap(Bitmap bitmap) {
FileOutputStream fos;
String filePath = getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png";
File f = new File(filePath);
try {
fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
And finally, the sharing itself:
if (id == R.id.action_share){
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("screenshot.png"));
startActivity(Intent.createChooser(share, "Teilen via"));
}
Where is my error? I don't get any errors in logcat, but I am unable to share the "screenshot".
Firstly, you should use :
share.putExtra(Intent.EXTRA_STREAM. Uri.fromFile(new File(getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png"));
But you would then get "Permission denied for the attachment" and you possibly would try but with no luck :(
share.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
So probably the best way to deal with this issue is to store the captured screenshot in media library and send the file from there.
public void share() {
String filePath=getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png";
String path;
try {
path = Images.Media.insertImage(getContentResolver(), filePath, "title", null);
Uri screenshotUri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(share, "Teilen via"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Hope it would help!

Categories