I am trying to create a separate folder in internal storage of a phone for an app to download files on it. But the folder is not created in the phone. What is the reason? Also I have another issue in my app that is photos are not downloaded when I click thee download button.
Here is the download function
public void download() {
for (MediaModel item : Items) {
if (item.isSelected) {
Log.d("check", "download");
final String url = item.getFullDownloadURL();
BaseDownloadTask task = FileDownloader.getImpl().create(url);
task.setListener(mFileDownloadListener)
.setPath(Environment.getDataDirectory() + "/" + Constants.STORED_FOLDER, true)
.setAutoRetryTimes(1)
.setCallbackProgressTimes(0)
.asInQueueTask()
.enqueue();
if (FileDownloader.getImpl().start(mFileDownloadListener, true)) {
item.setTaskId(task.getId());
item.setStatus(ItemStatus.DOWNLOADING);
Logging.e(TAG, "start download task: " + task.getId());
} else {
item.setTaskId(task.getId());
item.setStatus(ItemStatus.NORMAL);
Logging.e(TAG, "error download task: " + task.getId());
}
}
}
}
In Android studio to use internal Storage First of all add permission in manifest
Like this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
then to make new directory in internal storage use this line of code:
File sdCardRoot = new File(Environment.getExternalStorageDirectory(), "MyProfile");
if (!sdCardRoot.exists()) {
sdCardRoot.mkdirs();
}
Log.e("check_path", "" + sdCardRoot.getAbsolutePath());
This is my full code:
In this code check directory is exist or not if directory is not exist then create directory
and use asyntask to download images from url
In this example i have use Java Language
Code
MyAsyncTasks asyncTasks = new MyAsyncTasks();
asyncTasks.execute(Imageurl);
and AsyncClass:
class MyAsyncTasks extends AsyncTask<String, String, String> {
File sdCardRoot;
#Override
protected String doInBackground(String... strings) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
sdCardRoot = new File(Environment.getExternalStorageDirectory(), "MyProfile");
if (!sdCardRoot.exists()) {
sdCardRoot.mkdirs();
}
Log.e("check_path", "" + sdCardRoot.getAbsolutePath());
String fileName =
strings[0].substring(strings[0].lastIndexOf('/') + 1, strings[0].length());
Log.e("dfsdsjhgdjh", "" + fileName);
File imgFile =
new File(sdCardRoot, fileName);
if (!sdCardRoot.exists()) {
imgFile.createNewFile();
}
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
FileOutputStream outPut = new FileOutputStream(imgFile);
int downloadedSize = 0;
byte[] buffer = new byte[2024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
outPut.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.e("Progress:", "downloadedSize:" + Math.abs(downloadedSize * 100 / totalSize));
}
Log.e("Progress:", "imgFile.getAbsolutePath():" + imgFile.getAbsolutePath());
Log.e(TAG, "check image path 2" + imgFile.getAbsolutePath());
mImageArray.add(imgFile.getAbsolutePath());
outPut.close();
} catch (IOException e) {
e.printStackTrace();
Log.e("checkException:-", "" + e);
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
imagecount++;
Log.e("check_count", "" + totalimagecount + "==" + imagecount);
if (totalimagecount == imagecount) {
pDialog.dismiss();
imagecount = 0;
}
Log.e("ffgnjkhjdh", "checkvalue checkvalue" + checkvalue);
}
}
Try This code:
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
File apkStorage = null;
File outputFile = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(context);
progressDialog.setMessage("Downloading...");
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
try {
if (outputFile != null) {
progressDialog.dismiss();
CDToast.makeText(context, context.getResources().getString(R.string.downloaded_successfully), CDToast.LENGTH_SHORT, CDToast.TYPE_SUCCESS).show();
Notification();
vibrateDevice(100);
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
CDToast.makeText(context, context.getResources().getString(R.string.download_failed), CDToast.LENGTH_SHORT, CDToast.TYPE_ERROR).show();
}
} catch (Exception e) {
e.printStackTrace();
//Change button text if an exception occurs
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
}
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(downloadUrl);//Create Download URl
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.connect();//connect the URL Connection
//If Connection response is not OK then show Logs
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = new File(
Environment.getExternalStorageDirectory() + "/"
+ "New_Folder_Name_Here");
} else
Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();
//If File is not present create directory
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.close();
is.close();
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
For Checking SD card :
public class CheckForSDCard {
//Check If SD Card is present or not method
public boolean isSDCardPresent() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return true;
}
return false;
}
}
For creating folder
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Your Folder Name";
File folder = new File(path);
if (!folder.exists()) {
folder.mkdir();
}
also refer to this answer: https://stackoverflow.com/a/35471045/9060917
Update
public void download() {
for (MediaModel item : Items) {
if (item.isSelected) {
File file = new File(getFilesDir(),"Your directory name");
if(!file.exists()){
file.mkdir();
}
try{
Log.d("check", "download");
final String url = item.getFullDownloadURL();
BaseDownloadTask task = FileDownloader.getImpl().create(url);
task.setListener(mFileDownloadListener)
.setPath(file.getAbsolutePath(), true)
.setAutoRetryTimes(1)
.setCallbackProgressTimes(0)
.asInQueueTask()
.enqueue();
}catch (Exception e){
e.printStackTrace();
}
if (FileDownloader.getImpl().start(mFileDownloadListener, true)) {
item.setTaskId(task.getId());
item.setStatus(ItemStatus.DOWNLOADING);
Logging.e(TAG, "start download task: " + task.getId());
} else {
item.setTaskId(task.getId());
item.setStatus(ItemStatus.NORMAL);
Logging.e(TAG, "error download task: " + task.getId());
}
}
}
}
I hope you add these permissions in manifests
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Update
When saving a file to internal storage, you can acquire the appropriate directory as a File by calling method
getFilesDir()
File directory = context.getFilesDir();
File file = new File(directory, filename);
Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here's how to write some text to a file:
String filename = "myfile";
String fileContents = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContents.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
More reference
https://developer.android.com/training/data-storage/files#java
pass the URL of the image you want to download in this method.
/*--Download Image in Storage--*/
public void downloadImage(String URL) {
final Long reference;
downloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(URL);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle("AppName");
request.setDestinationInExternalPublicDir(String.format("%s/%s", Environment.getExternalStorageDirectory(),
getString(R.string.app_name)), "FileName.jpg");
Log.i("myi", "downloadImage: " + request.setDestinationInExternalPublicDir(String.format("%s/%s", Environment.getExternalStorageDirectory(),
getString(R.string.app_name)), "FileName.jpg"));
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
reference = downloadManager.enqueue(request);
Log.d("download", "Image Download : " + reference);
BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try {
Toast.makeText(this, "Image Downloaded Successfully ", Toast.LENGTH_LONG);
} catch (Exception e) {
}
}
};
getApplicationContext().registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
Add the required permissions to the AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Add requestLegacyExternalStorage for the application.
<application
android:requestLegacyExternalStorage="true">
</application>
Add the following snippet to the MainActivity.java
File f = new File(Environment.getExternalStorageDirectory(), "My folder");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
Files.createDirectory(Paths.get(f.getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
} else {
f.mkdir();
f.mkdirs();
Toast.makeText(getApplicationContext(), f.getPath(), Toast.LENGTH_LONG).show();
}
Now, the code to trigger the download would be something like:
String url="Here download Url paste";
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url.toString()));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.allowScanningByMediaScanner();
request.setDestinationInExternalPublicDir("/My folder", fileName);
downloadManager.enqueue(request);
I am trying to upload a image to google drive using API. I ve searched so much but i didn't find a way. I ve got a demo code which uploads a text file and it works. i need to change it to upload image.
This is the code...
public void CreateFileOnGoogleDrive(DriveContentsResult result){
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
#Override
public void run() {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
try {
writer.write("Hello abhay!");
writer.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("abhaytest2")
.setMimeType("text/plain")
.setStarred(true).build();
// create a file in root folder
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
How can i change this code to upload a image from file.(by given location of the image in device).?
I ve found few tutorials but those are deprecated methods.
Use this code to upload image to google drive...
new Thread() {
#Override
public void run() {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
// Write the bitmap data from it.
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle(title)
.build();
Bitmap image = BitmapFactory.decodeFile(location));
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 80, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i("E", "Unable to write file contents.");
}
image.recycle();
outputStream = null;
String title = "noisy";
Log.i("E", "Creating new pic on Drive (" + title + ")");
Drive.DriveApi.getFolder(mGoogleApiClient,driveId)
.createFile(mGoogleApiClient, metadataChangeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
First, you need t create a file then write the content in to it.
private void saveFiletoDrive(final File file, final String mime) {
Drive.DriveApi.newDriveContents(mDriveClient).setResultCallback(
new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
Log.i(TAG, "Connection successful, creating new contents...");
OutputStream outputStream = result.getDriveContents()
.getOutputStream();
FileInputStream fis;
try {
fis = new FileInputStream(file.getPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
byte[] photoBytes = baos.toByteArray();
outputStream.write(photoBytes);
outputStream.close();
outputStream = null;
fis.close();
fis = null;
} catch (FileNotFoundException e) {
Log.w(TAG, "FileNotFoundException: " + e.getMessage());
} catch (IOException e1) {
Log.w(TAG, "Unable to write file contents." + e1.getMessage());
}
String title = file.getName();
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType(mime).setTitle(title).build();
if (mime.equals(MIME_PHOTO)) {
if (VERBOSE)
Log.i(TAG, "Creating new photo on Drive (" + title
+ ")");
Drive.DriveApi.getFolder(mDriveClient,
mPicFolderDriveId).createFile(mDriveClient,
metadataChangeSet,
result.getDriveContents());
} else if (mime.equals(MIME_VIDEO)) {
Log.i(TAG, "Creating new video on Drive (" + title
+ ")");
Drive.DriveApi.getFolder(mDriveClient,
mVidFolderDriveId).createFile(mDriveClient,
metadataChangeSet,
result.getDriveContents());
}
if (file.delete()) {
if (VERBOSE)
Log.d(TAG, "Deleted " + file.getName() + " from sdcard");
} else {
Log.w(TAG, "Failed to delete " + file.getName() + " from sdcard");
}
}
});
}
I am facing the issue in uploading the list of audio to google drive.
I can upload the single audio file from a directory but i tried to upload the list of audio files is failed.
This is the path for the single audio file
final String path = new String(Environment.getExternalStorageDirectory() + "/CallLogs/Yaendi Yaendi.mp3");
How to upload the all the audio files in the CallLogs directory.
public void CreateFileOnGoogleDrive(DriveApi.DriveContentsResult result) {
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
#Override
public void run() {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
final String path = new String(Environment.getExternalStorageDirectory() + "/CallLogs/Yaendi Yaendi.mp3");
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(path));
} catch (FileNotFoundException e) {
showErrorDialog();
e.printStackTrace();
}
byte[] buf = new byte[1024];
int bytesRead;
try {
if (inputStream != null) {
while ((bytesRead = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, bytesRead);
}
}
} catch (IOException e) {
showErrorDialog();
e.printStackTrace();
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("callLog")
.setMimeType("audio/mpeg")
.setStarred(true).build();
// create a file in root folder
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, driveContents).setResultCallback(fileCallback);
}
}.start();
Toast.makeText(getActivity(), "Created Successfully", Toast.LENGTH_SHORT).show();
}
The above code is for uploading the single audio file to google drive.
Please help me how to upload the all the files to the google drive.
Place your code inside AsyncTask's doInBackground() method.
I'm trying to solve this problem for a long time.
This part of code download image to GDrive.
public void UploadFileOnGoogleDrive(DriveContentsResult result){
final DriveContents driveContents=result.getDriveContents();
new Thread(){
#Override
public void run(){
OutputStream outputStream = driveContents.getOutputStream();
// Write the bitmap data from it.
String photo = "IMG23.jpg";
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),photo);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
int numOfbytes = myBitmap.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(numOfbytes);
myBitmap.copyPixelsToBuffer(buffer);
//imageInByte = buffer.array();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
//outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg")
.setTitle(photo)
.setIndexableText(photo)
.build();
Log.d("Description",metadataChangeSet.getIndexableText());
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, metadataChangeSet, driveContents).
setResultCallback(fileCallback);
//Drive.DriveApi.fetchDriveId(mGoogleApiClient,EXISTING_FILE_ID).setResultCallback(idfileCallback);
}
}.start();
}
Here I try to get file ID
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (result.getStatus().isSuccess()) {
Toast.makeText(getApplicationContext(), "file created: "+""+
result.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show();
//DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, result.getDriveFile().getDriveId());
//file.getMetadata(mGoogleApiClient)
// .setResultCallback(metadataRetrievedCallback);
//String id=file.getDriveId().encodeToString();
Log.d("Fileidis",result.getDriveFile().getDriveId().encodeToString());
//final DriveId fileid = result.getDriveFile().getDriveId();
//DriveFile driveFile=Drive.DriveApi.getFile(mGoogleApiClient,fileid);
}
return;
}
};
But we find not fully ID in logs
07-06 15:15:50.939 19899-19899/valery.pankov.gdriveapp D/Fileidis: DriveId:CAESABj4XSCG9Oqbt1EoAA==
I thought set idResultCallback on UploadFileOnGoogleDrive but it was not successfull.
Thanks in advance
I want to make local copy(external storage) of a '.ppt' file present on Google Drive using Google Drive android Api.
I am reading one byte and writing it to my local file. But when I am trying to open it shows that file is corrupt. Please help me to resolve my problem.
final DriveFile file = Drive.DriveApi.getFile(getClient(), fileid);
final Metadata[] metadata = new Metadata[1];
file.getMetadata(getClient())
.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(DriveResource.MetadataResult metadataResult) {
metadata[0] = metadataResult.getMetadata();
L.b(EditorWindow.this, metadata[0].getMimeType(), 0);
}
});
file.open(getClient(), DriveFile.MODE_READ_ONLY, null)
.setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
L.c("Error in creating new file");
return;
}
DriveContents contents = result.getDriveContents();
String filename = metadata[0].getTitle();
File localFile = new File(Environment.getExternalStorageDirectory(), filename);
OutputStream out = null;
InputStream in = null;
try {
out = new BufferedOutputStream(new FileOutputStream(localFile));
in = contents.getInputStream();
int b;
while ( (b = in.read()) > 0) {
out.write(b);
}
in.close();
out.close();
} catch (Exception e) {L.c("Error in writing to SD card");}
contents.discard(getClient());
}
});
Can you try changing your while condition to ( (b = in.read()) >= 0)? Note that 0 is a valid byte to be read from an InputStream.
http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()