How to download the files in specific folder in internal storage - android

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);

Related

I want to download files in webview with showing progress in the activity not in the progress dialogue

public class DownloadTask {
private static final String TAG = "Download Task";
private Context context;
private Button buttonText;
private String downloadUrl = "", downloadFileName = "";
public DownloadTask(Context context, Button buttonText, String downloadUrl) {
this.context = context;
this.buttonText = buttonText;
this.downloadUrl = downloadUrl;
downloadFileName = downloadUrl.replace(Utils.mainUrl, "");//Create file name by picking download file name from URL
Log.e(TAG, downloadFileName);
//Start Downloading Task
new DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
File apkStorage = null;
File outputFile = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
buttonText.setEnabled(false);
buttonText.setText(R.string.downloadStarted);//Set Button Text when download started
}
#Override
protected void onPostExecute(Void result) {
try {
if (outputFile != null) {
buttonText.setEnabled(true);
buttonText.setText(R.string.downloadCompleted);//If Download completed then change button text
} else {
buttonText.setText(R.string.downloadFailed);//If download failed change button text
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
buttonText.setEnabled(true);
buttonText.setText(R.string.downloadAgain);//Change button text again after 3sec
}
}, 3000);
Log.e(TAG, "Download Failed");
}
} catch (Exception e) {
e.printStackTrace();
//Change button text if exception occurs
buttonText.setText(R.string.downloadFailed);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
buttonText.setEnabled(true);
buttonText.setText(R.string.downloadAgain);
}
}, 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() + "/"
+ Utils.downloadDirectory);
} 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;
}
}
}
I am using this I am downloading files with this code but the problem is that I want to show progress of downloading files in an activity not in the progress. I have checked so many articles and websites for downloading progress showing in activity where I will give this to a name of download activity. And I can pause, resume and delete files in this activity but I have not found anything.
So please check and provide me solution that how can I showing download progress in different activity.
Use download listener to download files in the web view and get your files downloaded.

How i can add a progress notification in my code for download

I have created an app in this app i have display the pdf files and when user click then file should be downloaded.I have write a code for download andt i am only able to show the ProgressDialog for downloading but i want progress notification with cancel button. I don't known how i can do that.
Here is my download code.
public class DownloadTask {
private static final String TAG = "Download Task";
private Context context;
private String downloadUrl = "", downloadFileName = "";
private ProgressDialog progressDialog;
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public DownloadTask(Context context, String downloadUrl, String downloadFileName) {
this.context = context;
this.downloadUrl = downloadUrl;
this.downloadFileName =downloadFileName;
new DownloadingTask().execute();
}
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("Loading...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
try {
if (outputFile != null) {
progressDialog.dismiss();
Toast.makeText(context, "Downloaded Successfully", Toast.LENGTH_SHORT).show();
File file = new File(Environment.getExternalStorageDirectory() + "/"
+ "android"+"/"+"data"+"/"+"FolderName"+"/"+ downloadFileName);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
if (uri.toString().contains(".pdf")) {
intent.setDataAndType(uri, "application/pdf");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed");
}
} catch (Exception e) {
e.printStackTrace();
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);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();//connect the URL Connection
if (c.getResponseCode() !=
HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = new File(
Environment.getExternalStorageDirectory() + "/"
+ "android"+"/"+"data"+"/"+"Folder name");
} else
Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
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
}
fos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
In the doInBackground method of your downloadingTask, regularly call publishProgress to transmit the progress to your UI, then update your progress bar in it's onProgressUpdate which is executed on the UI thread and can hence a progress bar in a dialog box.

Download POST method's PDF response using retrofit 2

I am new to android and JSON using retrofit. I am using retrofit 2 with my project.
This is one of post API and it gives a pdf as the response.
#POST("examples/campaign_report_new.php")
Call<ResponseBody> getAddressTrackingReport(#Body ModelCredentialsAddressTracking credentials);
I used the below code to do this function and I stuck in the response method to download and show that pdf.
private void downloadPdf() {
ModelCredentialsAddressTracking
credentials = new ModelCredentialsAddressTracking(campaign,
dateFrom, dateTo);
ApiService apiService = RetroClient.getApiService();
Call<ResponseBody> call = apiService.getAddressTrackingReport(credentials);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.d(TAG, String.valueOf(response.body().bytes()));
} catch (IOException e) {
e.printStackTrace();
}
boolean writtenToDisk = writeResponseBodyToDisk(response.body());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
Below link is the response I got from Postman:
click here
writeResponseBodyToDisk() function :
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Door Tracker");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("door tracker", "Oops! Failed create "
+ "door tracker" + " directory");
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "AddressTrackingReport "+ timeStamp + ".pdf");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(mediaFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
Somebody, please help a solution. This may contain errors Because I am new to it.Thanks.
Your API using form-data as input, So change #Body to #Multipart Type. This will give you a response. Add below snippet inside onResponse()
if (response.isSuccessful()) {
progressDialog.dismiss();
new AsyncTask<Void, Void, Void>() {
boolean writtenToDisk = false;
#Override
protected Void doInBackground(Void... voids) {
try {
writtenToDisk = writeResponseBodyToDisk(AddressTrackingActivity.this,
response.body());
} catch (IOException e) {
Log.w(TAG, "Asynch Excep : ", e);
}
Log.d(TAG, "file download was a success? " + writtenToDisk);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (writtenToDisk) {
String pdfPath = Environment.getExternalStorageDirectory().toString()
+ "/Door Tracker/" + fileName;
Log.d(TAG, "file name : " + fileName);
File file = new File(pdfPath);
Uri bmpUri;
if (Build.VERSION.SDK_INT < 24) {
bmpUri = Uri.fromFile(file);
Log.d(TAG, "bmpUri : " + bmpUri);
} else {
bmpUri = FileProvider.getUriForFile(AddressTrackingActivity.this,
getApplicationContext().getPackageName() + ".provider", file);
Log.d(TAG, "bmpUri : " + bmpUri);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(bmpUri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.d(TAG, "ActivityNotFoundException : ", e);
}
}
}
}.execute();
} else {
progressDialog.dismiss();
Toast.makeText(AddressTrackingActivity.this, "Network error, Please retry", Toast.LENGTH_SHORT).show();
Log.d(TAG, "server contact failed");
}
I think this will help you.
String fileName = "";
boolean writtenToDisk = writeResponseBodyToDisk(response.body(),fileName);
if(writtenToDisk){
String pdfPath = Environment.getExternalStorageDirectory().toString() + "/Door Tracker/"+fileName;
File file = new File(pdfPath);
Uri bmpUri;
if (Build.VERSION.SDK_INT < 24) {
bmpUri = Uri.fromFile(file);
} else {
bmpUri = FileProvider.getUriForFile(this,getApplicationContext().getPackageName() + ".provider", file);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(bmpUri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
}
}
Just get the File Name from method writeResponseBodyToDisk :
File mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "AddressTrackingReport "+ timeStamp + ".pdf");
fileName = mediaFile.getName();
Just Debug and Check your file name is correct.

How to download video from URL?

I am trying to download a video file from URL.
Below is my Code.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBack PB = new ProgressBack();
PB.execute("");
}
private class ProgressBack extends AsyncTask<String, String, String> {
ProgressDialog PD;
#Override
protected void onPreExecute() {
PD = ProgressDialog.show(MainActivity.this, null, "Please Wait ...", true);
PD.setCancelable(true);
}
#Override
protected String doInBackground(String... arg0) {
downloadFile("https://r8---sn-nhpax-ua8z.googlevideo.com/videoplayback?c=web&clen=17641691&cpn=Mf_hDzzzBYPH8N_J&cver=as3&dur=189.857&expire=1425270280&fexp=905657%2C907263%2C912333%2C926419%2C927622%2C931358%2C934947%2C936928%2C9406255%2C9406746%2C9406850%2C943917%2C945093%2C947225%2C947240%2C948124%2C951703%2C952302%2C952605%2C952612%2C952620%2C952901%2C955301%2C957201%2C959701&gcr=il&gir=yes&id=o-AM54E58Im9m8yqaerEsKkGXOx0IWge8YN4h6OhFkcDTe&initcwndbps=1488750&ip=84.228.53.86&ipbits=0&itag=135&keepalive=yes&key=yt5&lmt=1402678222642477&mime=video%2Fmp4&mm=31&ms=au&mt=1425248654&mv=m&pl=20&ratebypass=yes&requiressl=yes&signature=E8027BCB4C1EE76254FC008B0044655E58485D81.931863F3A7AD6C6B01262BCD723B37E5396D4317&source=youtube&sparams=clen%2Cdur%2Cgcr%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Ckeepalive%2Clmt%2Cmime%2Cmm%2Cms%2Cmv%2Cpl%2Crequiressl%2Csource%2Cupn%2Cexpire&sver=3&upn=moGJHdfD4Z8", "Sample.mp4");
return null;
}
protected void onPostExecute(Boolean result) {
PD.dismiss();
}
}
private void downloadFile(String fileURL, String fileName) {
try {
String rootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Video";
File rootFile = new File(rootDir);
rootFile.mkdir();
URL url = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(rootFile,
fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (IOException e) {
Log.d("Error....", e.toString());
}
}
}
But it is not downloading. and it is showing java.io.FileNotFoundException.
Is there any other way to download video file or anything wrong in my code.
Can someone please help me?
//Check if External Storage permission js allowed
if (!storageAllowed()) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(getActivity(), Constant.PERMISSIONS_STORAGE, Constant.REQUEST_EXTERNAL_STORAGE);
progressDialog.dismiss();
showToast("Kindly grant the request and try again");
}else {
String mBaseFolderPath = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "FolderName" + File.separator;
if (!new File(mBaseFolderPath).exists()) {
new File(mBaseFolderPath).mkdir();
}
if (downloadUrl == null || TextUtils.isEmpty(downloadUrl)) {
showToast("Download url not found!");
return;
}
Uri downloadUri = Uri.parse(url.trim());
if (downloadUri == null) {
showToast("Download url not found!");
return;
}
String mFilePath = "file://" + mBaseFolderPath + "/" + fname ;
DownloadManager.Request req = new DownloadManager.Request(downloadUri);
req.setDestinationUri(Uri.parse(mFilePath));
req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
dm.enqueue(req);
progressDialog.dismiss();
loadInterstitialAd();
}
}
try out this:
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}
You can use DownloadManger for downloading file in android from server.
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(videoUrl))
.setTitle(file.getName())
.setDescription("Downloading")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationUri(Uri.fromFile(file))
.setAllowedOverMetered(true)
.setAllowedOverRoaming(true);
long downloadId = mDownloadManager.enqueue(request);

How to download file/image from url to your android app

I need my android app to make request to url to download an image from this url
so I have built this class to help me, BUT it didn't work ???
public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;
protected void doInBackground() throws IOException {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try{
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
// Open a connection to that URL.
URLConnection ucon = url.openConnection();
// Define InputStreams to read from the URLConnection.
is = ucon.getInputStream();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
try {
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(
null,
new String[] { file.toString() },
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
}
);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And I have, in the Activity class on onclick(), this function:
public void down(View v) {
// ImageManager ob=new ImageManager();
// ob.DownloadFromUrl("");
new MyAsnyc().execute();
}
Although I have written the permissions in the manfiest.xml
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
try this
public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;
protected void doInBackground() throws IOException {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
is = ucon.getInputStream();
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
try {
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(null,
new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Define these on the top side
Button BtnDownload;
DownloadManager downloadManager;
After, You should write on create inside :
BtnDownload = (Button)findViewById(R.id.button1);
Later, You should write to the button's click event
downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("your url");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
Finally, you need to add this onto the application tag to the manifest.xml :
<uses-permission android:name="android.permission.INTERNET"/>
new DownloadImageFromUrlTask().execute(imagePath);
//add glide dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'
public class DownloadImageFromUrlTask extends AsyncTask<String, Void, Bitmap> {
String downloadPath = "";
#Override
protected Bitmap doInBackground(String... args) {
try {
downloadPath = args[0];
return BitmapFactory.decodeStream((InputStream) new URL(downloadPath).getContent());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
String photoFileName = downloadPath.substring(downloadPath.lastIndexOf('/') + 1);
String root_Path = Environment.getExternalStorageDirectory().toString();
String saveImagePath = root_Path + "/" + photoFileName;
saveBitmapToJPEGFile(MainActivity.this, bitmap, new File(saveImagePath), 900);
loadImageWithGlide(MainActivity.this, myImageView, saveImagePath);
} else {
myImageView.setImageResource(R.drawable.default_photo);
}
}
}
public static Boolean saveBitmapToJPEGFile(Context ctx, Bitmap theTempBitmap, File theTargetFile, int i) {
Boolean result = true;
if (theTempBitmap != null) {
FileOutputStream out = null;
try {
out = new FileOutputStream(theTargetFile);
theTempBitmap.compress(Bitmap.CompressFormat.JPEG, CommonUtils.JPEG_COMPRESION_RATIO_DEFAULT, out); //kdfsJpegCompressionRatio
} catch (FileNotFoundException e) {
result = false;
e.printStackTrace();
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
result = false;
}
return result;
}
public static void loadImageWithGlide(Context theCtx, ImageView theImageView, String theUrl) {
Glide.with(theCtx)
.load(theUrl)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(theImageView);
}
The problem with your code is you have not read the InputStream.
You should try this
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
and make the Asynctask return type as Bitmap.
Or,
As you have used that is in postExecute() your doInBackground() should return that InputStream object is. But you are returning void.
Okey.Try this edited Asynctask.
private class MyAsnyc extends AsyncTask <Void,Void,File> {
File file;
#Override
protected File doInBackground( Void... params ) {
InputStream is = null;
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File( path , "Demo Picture.jpg" ) ;
try { // Make sure the Pictures directory exists.path.mkdirs() ; URL url = new URL ( "http: / /androidsaveitem .appspot.com/download.jpg") ; URLConnection ucon = url.openConnection ( ) ;
path.mkdirs();
OutputStream os = new FileOutputStream(file) ;
byte [ ] data = new byte [ is.available ( ) ] ;
is.read ( data ) ; os.write (data );is.close ( ) ; os.close ( ) ;
return file;
}
catch (Exception e){
Log .d ( "ImageManager " , " Error: " + e ) ;
}
return null;
}
protected void onPostExecute (File file) {
try{
MediaScannerConnection.scanFile( null , new String [] {file.toString( ) } , null , new MediaScannerConnection.OnScanCompletedListener ( ) { public void onScanCompleted (String path, Uri uri) {
Log.i ( " External Storage" , " Scanned " + path + " : " ) ; Log.i ( " E x t e r n a l S t o r a g e " , " - > u r i = " + uri ) ; } } ) ;
}catch (Exception e) {
// TODO: handle exception
}
}}

Categories

Resources