android java.io.File.fixSlashes(File.java:185) - java

I got an error in console crashes & anrs. This error is showing sometimes and I couldn't find where the problem is.
java.lang.NullPointerException
at java.io.File.fixSlashes(File.java:185)
at java.io.File.<init>(File.java:134)
The function code to save picture is:
public static String sharePhoto(Context context, Bitmap bmp) {
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Folder");
boolean success = true;
String file_path = null;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
file_path = folder + "/Img_" + System.currentTimeMillis() / 1000 + ".jpg";
}
OutputStream os = null;
try {
os = new FileOutputStream(file_path);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, os);
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Do something else on failure
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(file_path);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
return file_path;
}

Try this:
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/MyFolder");
Thing is that getExternalStorageDirectory() returns File. You need to get absolute path of that file and concatenate with "/Pictures/MyFolder".

Related

How to get the name of image from url in this saveMyImage method

I use this code to save the image in the divice and it is working good
but I have problem with image name, I don't know what to tape here (I download the image from url with picasso).
Here is the code:
void saveMyImage (String appName, String imageUrl, String imageName) {
Bitmap bmImg = loadBitmap(imageUrl);
File filename;
try {
String path1 = android.os.Environment.getExternalStorageDirectory()
.toString();
File file = new File(path1 + "/" + appName);
if (!file.exists())
file.mkdirs();
filename = new File(file.getAbsolutePath() + "/" + imageName
+ ".jpg");
FileOutputStream out = new FileOutputStream(filename);
bmImg.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, appName);
image.put(Images.Media.DISPLAY_NAME, imageName);
image.put(Images.Media.DESCRIPTION, "App Image");
image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
image.put(Images.Media.MIME_TYPE, "image/jpg");
image.put(Images.Media.ORIENTATION, 0);
File parent = filename.getParentFile();
image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
.toLowerCase().hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
.toLowerCase());
image.put(Images.Media.SIZE, filename.length());
image.put(Images.Media.DATA, filename.getAbsolutePath());
Uri result = getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, image);
Toast.makeText(getApplicationContext(),
"download in " + filename, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
This is the call method in onCreate:
/* button to download the image */
download_image = findViewById(R.id.button_download);
checkPermission();
download_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
String URL = intent.getStringExtra("imageUrl");
saveMyImage ("my app",URL,"i want to get the image name from the url");
}
}
});
I want to get the image name from the url, so how can I do that?
Try this:
URI uri = new URI(URL);
URL videoUrl = uri.toURL();
File tempFile = new File(videoUrl.getFile());
String fileName = tempFile.getName();

How to save an image to the disk after is done loading it into the view from an URL

Im building an android app that needs to fetch an image from an url and, after is done displaying it into the image view, I want to store it in the hard drive of the phone so it can be use later without creating a new petition or depending on the cache.
Im using glide 4.9.0
Some of the solutions online include using some deprecated clases such as SimpleTarget and Target that wont be applicable in this project.
This is what I have so far.
File file = new File(holder.context.getExternalFilesDir(null), fileName);
if (file.exists()) {
GlideApp.with(holder.context).load(file).into(holder.ivProductImage);
} else {
GlideApp.with(holder.context).load(urlImage).into(holder.ivProductImage);
// save the image to the hard drive
}
//Step 1
Glide.with(mContext)
.load(images.get(position).getThumbnail())
.asBitmap()
.into(new Target<Bitmap>(100,100) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
saveImage(resource,position);
}
});
//Step 2
private String saveImage(Bitmap image, int position) {
String savedImagePath = null;
String imageFileName = "JPEG_" + images.get(position).getName() + ".jpg";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/Comicoid");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Add the image to the system gallery
galleryAddPic(savedImagePath);
}
return savedImagePath;
}
//Step 3
private void galleryAddPic(String imagePath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
mContext.sendBroadcast(mediaScanIntent);
}

How to write apk of an app to a folder

I am trying to get the APK of an app and save it in a folder on storage directory. I have got the apk but I am not able to save it to my desired folder.
Here is how I am generating apk file:
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> apps = getPackageManager().queryIntentActivities(mainIntent, 0);
for (ResolveInfo info : apps) {
File fileToSave = new File(info.activityInfo.applicationInfo.publicSourceDir)
}
Here is the code to Save the APK file where I am passing the same file to save:
private void createDirectoryAndSaveFile(File fileToSave) {
try {
String folderName = "MyCreatedFolder";
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + folderName);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
File path = new File(context.getFilesDir(), folderName);
File mypath = new File(path, fileToSave.getName());
new BufferedWriter(new FileWriter(mypath));
Toast.makeText(context, "Created", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
System.out.println("----" + e.getLocalizedMessage());
}
}
The fileToSave is the APK file but writing it says no such file or directory.
java.io.FileNotFoundException: ..../MyCreatedFolder/base.apk: open
failed: ENOENT (No such file or directory)
All the required permissions are there and runtime permissions not required as TargetSDK is 21.
How to save this file to my storage directory.?
Try this code because you want to create a folder (if it does not exist),then write into the same exact folder you created/specified hence the omission of this line File path = new File(context.getFilesDir(), folderName); but instead the path of the folder we created.
private void createDirectoryAndSaveFile(File fileToSave) {
try {
String folderName = "MyCreatedFolder";
String dire = Environment.getExternalStorageDirectory().toString();
File dir = new File(dire +"/"+ folderName);
boolean success = true;
if (!dir.exists()) {
success=dir.mkdirs();
}
if (success) {
File mypath = new File(dir + "/"+folderName+"/", fileToSave.getName());
new BufferedWriter(new FileWriter(mypath));
Toast.makeText(context, "Created", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
System.out.println("----" + e.getLocalizedMessage());
}
}

I am having error to display the image file save in memory in android,

Here is the code:
public void Displayimg(View v) {
File path = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
ipath[0] = String.valueOf(((TextView) v).getText());
String sifile = ipath[0].substring(45,52); // extracting the filename from the view eg: abc.jpg
File imgfile = new File(path,sifile); // it fails on this line with unfortunately, main application has stopped.
// if the sifile conatians a name of the file that exist, it give error and comes out
// if I give file name in sifile that does not exisit, if give file does on exisit and comes our with error.
// Basically I am having problem to open an image file that exisit and dispaly.
// File("/storage/sdcard0/Pictures/MyCameraApp/Zimg20151105_1535133.Jpg");
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.mc_imgview);
if(imgfile.exists()){
Toast.makeText(getApplicationContext(),file.getAbsolutePath() + "File Exisit", Toast.LENGTH_SHORT).show();
myImage.setImageBitmap(myBitmap);
}
else
{
Toast.makeText(getApplicationContext(),file.getAbsolutePath() + " File Does not Exisit", Toast.LENGTH_SHORT).show();
}
}
Display image :
Try to Search Volley or Universal-Image-Loader or Glide.
Save Image:
public static String getSdPath(){
//todo test path
return Environment.getExternalStorageDirectory().getAbsolutePath();
// return "";
}
public static String getImageDir (String type,Activity activity){
if(type.equalsIgnoreCase("pure")){
return getSdPath()+ activity.getDir("pure", Context.MODE_PRIVATE).getAbsolutePath();
}else{
return getSdPath()+activity.getDir("deal", Context.MODE_PRIVATE).getAbsolutePath();
}
}
private static final String APPLICATION_NAME = "test";
private static final Uri IMAGE_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
private static final String PATH = getImageDir("deal", mActivity);
public static Uri savePngImage(ContentResolver cr, Bitmap bitmap) {
long dateTaken = System.currentTimeMillis();
String name = String.valueOf(dateTaken) + ".png";
return savePngImage(cr, name, dateTaken, PATH, name, bitmap);
}
public static Uri savePngImage(ContentResolver cr, String name, long dateTaken, String directory,
String filename, Bitmap source) {
OutputStream outputStream = null;
String filePath = directory + File.separator + filename;
try {
File dir = new File(directory);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(directory, filename);
if (file.createNewFile()) {
outputStream = new FileOutputStream(file);
if (source != null) {
source.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
} else {
}
}
// FileUtils.updateFile(file);
} catch (FileNotFoundException ex) {
return null;
} catch (IOException ex) {
return null;
} catch (NullPointerException ex) {
return null;
}finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (Throwable t) {
}
}
}
ContentValues values = new ContentValues(7);
values.put(MediaStore.Images.Media.TITLE, name);
values.put(MediaStore.Images.Media.DISPLAY_NAME, filename);
values.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA, filePath);
// FileUtils.updateFile(filePath);
return cr.insert(IMAGE_URI, values);
}

"Invalid File" error when the images in sdcard are clicked

To share the image via Email and mms first step I need to save the image in sdcard but for me the saved image is not getting opened instead "Invalid File" error, I checked with the extension format everything is correct but don't know where I'm going wrong.
Below is the java code.
public class Share extends CordovaPlugin {
public static final String ACTION_POSITION = "ShareImage";
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
throws JSONException {
if (ACTION_POSITION.equals(action)) {
try {
JSONObject arg_object = args.getJSONObject(0);
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("image/jpg");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, arg_object.getString("image"));
String name = arg_object.getString("image");
String defType = "drawable";
String defPackage = "com.picsswipe";
int drawableId = this.cordova.getActivity().getResources().getIdentifier( name , defType, defPackage );
// Bitmap bbicon = BitmapFactory.decodeFile( arg_object.getString("image") );
Bitmap bbicon = BitmapFactory.decodeResource( this.cordova.getActivity().getResources(),drawableId );
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File f = new File(extStorageDirectory + "/Download/",
"jj.jpg" );
try {
outStream = new FileOutputStream(f);
bbicon.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
}
File r1 = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Download/", "jj.jpg");
//RETRIEVING IMAGES FROM SDCARD
Uri uri1 = Uri.fromFile(r1);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri1);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(r1));
Uri uris = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "jj.jpg"));
this.cordova.getActivity().startActivity(sendIntent);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
return true;
}
}
File file;
File rootPath = android.os.Environment
.getExternalStorageDirectory();
File directory = new File(rootPath.getAbsolutePath()
+ "/Download");
if (!directory.exists())
directory.mkdir();
file = new File(directory, "filename.PNG");//.png/.jpg anything you want
try {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.pincheck);
FileOutputStream outStream;
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and you should add this permission in your manifest file..Then only file will copied to your external sd card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Categories