How To Save Image into Sdcard From Url android - java

i am new in android. i want to save image from url into SDcard.
File direct = new File(Environment.getExternalStorageDirectory()
+ "/.imgapp");
if (!direct.exists()) {
direct.mkdirs();
}
Calendar c = Calendar.getInstance();
int d = c.get(Calendar.DATE);
int d1 = c.get(Calendar.MONTH)+1;
File file = new File(Environment.getExternalStorageDirectory()
+ "/.imgapp/"+d+""+d1+".png" );
if (!file.exists()) {
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()
+ "/.imgapp/"+d+""+d1+".png");
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally { output.close(); }
} finally { input.close(); }
}else{
Toast.makeText(getApplicationContext(), "No Error", Toast.LENGTH_SHORT).show();
}
manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
i try This Code But App Stop and Crash please Help Me.
i want download image onCreate when user open App.

finally Done!!.
DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
String uRl = "http://bitsparrow.altervista.org/wp-content/uploads/2013/04/5.jpg";
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir("/.appimg", "test.jpg");
mgr.enqueue(request);
This Work For me..!

Related

How to create a video file path on Android 10

I tried to create a video file path as the follows :
String fileName = videoFileName = "VID" + System.currentTimeMillis() + ".mp4";
public static String createVideoPath(Context context, String fileName) {
File imageThumbsDirectory = context.getExternalFilesDir("FOLDER");
if (imageThumbsDirectory != null) {
if (!imageThumbsDirectory.exists()) {
imageThumbsDirectory.mkdir();
}
}
String appDir = context.getExternalFilesDir("FOLDER").getAbsolutePath();
File file = new File(appDir, fileName);
return file.getAbsolutePath();
}
I call the method above like this : String videoPath = createVideoPath(getApplicationContext(),fileName);
I use this library for edits :
EZFilter.input(mainBitmap).addFilter(null).enableRecord(videoPath, true, false).into(renderView);
After the edit finished, I try to save the final video to the gallery as follows :
private static Uri publicDirURI(Context context, String fileName, String dir) {
ContentValues valuesVideos;
valuesVideos = new ContentValues();
valuesVideos.put(MediaStore.Video.Media.RELATIVE_PATH, dir);
valuesVideos.put(MediaStore.Video.Media.TITLE, fileName);
valuesVideos.put(MediaStore.Video.Media.DISPLAY_NAME, fileName);
valuesVideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesVideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
valuesVideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
valuesVideos.put(MediaStore.Video.Media.IS_PENDING, 1);
ContentResolver resolver = context.getContentResolver();
Uri collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri uriSavedVideo = resolver.insert(collection, valuesVideos);
return saveFileToPublicMovies(context, valuesVideos, uriSavedVideo, fileName);
}
private static Uri saveFileToPublicMovies(Context context, ContentValues contentValues, Uri uriSavedVideo, String fileName) {
ParcelFileDescriptor pfd;
try {
pfd = context.getContentResolver().openFileDescriptor(uriSavedVideo, "w");
FileOutputStream out = null;
if (pfd != null) {
out = new FileOutputStream(pfd.getFileDescriptor());
File videoFile = new File(context.getExternalFilesDir("FOLDER"), fileName);
FileInputStream in = new FileInputStream(videoFile);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
pfd.close();
}
} catch (Exception e) {
e.printStackTrace();
}
contentValues.clear();
contentValues.put(MediaStore.Video.Media.IS_PENDING, 0);
context.getContentResolver().update(uriSavedVideo, contentValues, null, null);
return uriSavedVideo;
}
But I always get an empty saved video with 0.00b, I've tried the app with device running Android 9, but with getExternalStoragePublicDirectory, and everyting works just fine, so the issue is not related with the library.
Could anyone help me to solve this issue, I'm stuck on it almost 1 week, thank you
Edit :
private static Uri saveFileToPublicMovies(Context context, ContentValues contentValues, Uri uriSavedVideo, String fileName) {
ParcelFileDescriptor pfd;
try {
pfd = context.getContentResolver().openFileDescriptor(uriSavedVideo, "w");
FileOutputStream out = null;
if (pfd != null) {
out = new FileOutputStream(pfd.getFileDescriptor());
File videoFile = new File(context.getExternalFilesDir("AppName"), fileName);
FileInputStream in = new FileInputStream(videoFile);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
out.getFD().sync();
out.close();
in.close();
pfd.close();
}
} catch (Exception e) {
e.printStackTrace();
}
contentValues.clear();
contentValues.put(MediaStore.Video.Media.IS_PENDING, 0);
context.getContentResolver().update(uriSavedVideo, contentValues, null, null);

Android Q Create and save file

I try save a pdf file but on andorid Q I do not see a file. I added all permissions and all permissions are granded also I do this :
public static void saveFile( #NonNull String name, Context context,String base64, Uri imageUri,String path) throws IOException {
Log.e("Path",path);
OutputStream fos;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name + ".pdf");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
} else {
String imagesDir = path;
File image = new File(imagesDir, name + ".pdf");
fos = new FileOutputStream(image);
}
byte[] pdfAsBytes = Base64.decode(base64, 0);
assert fos != null;
fos.write(pdfAsBytes);
fos.flush();
fos.close();
}
FileOutputStream os;
String path;
Uri photoURI = null;
photoURI = getUriForFile(context.getApplicationContext(),
BuildConfig.APPLICATION_ID + ".provider", createImageFile(context,cardId));
File dwldsPath = new File(getDefaultTempFilesPath(context) + "/" + cardId +".pdf");
And a probleme is that I do not see a file , a this permissions is added and all is granded :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
and I add
android:requestLegacyExternalStorage="true"
if I do this steal I do not have a file butI do not have any exceptions
private static void createFile(Context ctx, String fileName, String text) {
File filesDir = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
filesDir = ctx.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
}
assert filesDir != null;
if (!filesDir.exists()){
if(filesDir.mkdirs()){
}
}
File file = new File(filesDir, fileName + ".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
throw new IOException("Cant able to create file");
}
}
OutputStream os = new FileOutputStream(file);
byte[] data = text.getBytes();
os.write(data);
os.flush();
os.close();
Log.e("TAG", "File Path= " + file.toString());
if(file.exists()){
Log.e("d","d");
}
File fileTemp = new File(file.getPath());
FileInputStream notes_xml = new FileInputStream(fileTemp);
byte fileContent[] = new byte[(int)notes_xml.available()];
//The information will be content on the buffer.
notes_xml.read(fileContent);
String strContent = new String(fileContent);
Log.e("content",strContent);
notes_xml.close();
} catch (IOException e) {
e.printStackTrace();
}
}

My app no longer asks for the users permission to write external storage, why?

I updated my app few days ago and notice that the share function to share a sound no longer works.
I didn't changed anything on the code except I migrated to AndroidX.
Here is the Logcat message:
E/EVENTHANDLER: Failed to save file: /storage/emulated/0/appfolder/testsound.mp3 (Permission denied)
And here is the Method where it should ask for the users permission:
if (item.getItemId() == R.id.action_send){
try{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1){
if (ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions((Activity) view.getContext(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}else {
final String AUTHORITY = view.getContext().getPackageName() + ".fileprovider";
Uri contentUri = FileProvider.getUriForFile(view.getContext(), AUTHORITY, file);
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, contentUri);
intent.setType("audio/mp3");
view.getContext().startActivity(Intent.createChooser(intent, "Share sound via..."));
}
}
else {
final Intent intent = new Intent(Intent.ACTION_SEND);
Uri fileUri = Uri.parse(file.getAbsolutePath());
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
intent.setType("audio/mp3");
view.getContext().startActivity(Intent.createChooser(intent, "Share sound via..."));
}
} catch (Exception e){
Log.e(LOG_TAG, "Failed to share sound: " + e.getMessage());
}
}
Here is the method where the sound is downloaded:
if (item.getItemId() == R.id.action_send || item.getItemId() == R.id.action_ringtone){
SoundObject AND add the .mp3 tag to it
final String fileName = soundObject.getItemName() + ".mp3";
File storage = Environment.getExternalStorageDirectory();
File directory = new File(storage.getAbsolutePath() + "/appfolder/");
directory.mkdirs();
final File file = new File(directory, fileName);
InputStream in = view.getContext().getResources().openRawResource(soundObject.getItemID());
try{
Log.i(LOG_TAG, "Saving sound " + soundObject.getItemName());
OutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer, 0, buffer.length)) != -1){
out.write(buffer, 0 , len);
}
in.close();
out.close();
} catch (IOException e){
Log.e(LOG_TAG, "Failed to save file: " + e.getMessage());
}
This is the method where it asks for the storage Acess:
public void externalStorageAccess(){
final File FILES_PATH = new File(getExternalFilesDir(null)+"/files");
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w("error", "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
finish();
}
}
Of course I have these two line in Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Why is it no longer working?
Thanks for any help!

saving file in internal storage android for my app

I have audio mp3 in res/raw/suono1.mp3 and i need share(in my app) on whatapp my code is it, but when i send, don t share HELP ME PLS.
pulsante2.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//condividere
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.suono2);
fileOutputStream = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "sound.mp3"));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
inputStream.close();
fileOutputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/sound.mp3" ));
intent.setType("audio/mpeg");
startActivity(Intent.createChooser(intent, "Share audio"));
return false;
}
});
send code for android studio i need them
Have you asked permission in the manifest.xml file?

Saving File in internal memory and reading through intent

I want to download a file from URL and save it to the internal memory. Once file is saved in internal memory I want to fire an Intent to open it in apps.
**Following is the code to download the file and save in internal memory:**
private void getPDFContent(String myUrl, String sfilename) {
try {
FileOutputStream fos = this.openFileOutput(sfilename,Context.MODE_PRIVATE);
URL u = new URL(myUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
fos.write(buffer, 0, len1);
}
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
**Following is the code to read:**
public void readInternalStorageOption() {
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
String filePath = getApplication().getFilesDir().getAbsolutePath()
+ File.separator + "test.pdf";
File f = new File(filePath);
if (f.exists()) {
Uri internal = Uri.fromFile(f);
intent.setDataAndType(internal, "application/pdf");
}
startActivity(intent);
} catch (NullPointerException ex) {
}
}
Issue is that file is saved successfully but when I try to open it via intent I got an error that file cannot be opened. Please suggest any solution for the same.

Categories

Resources