How can I download pdf generated by Tcpdf from my android webview - android

Need a help to solve my problem.
In my android webview a pdf which is generated using tcpdf is not working properly ...
It generates some garbage values in the pdf
//download file
myWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request myRequest = new DownloadManager.Request(Uri.parse(url));
myRequest.allowScanningByMediaScanner();
myRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//new
myRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
//create download manager
DownloadManager myManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
myManager.enqueue(myRequest);
Toast.makeText(MainActivity.this, "Downloding file....", Toast.LENGTH_SHORT).show();
}
});
//TCPDF
myWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//start download
DownloadPDF downlooadPDF = new DownloadPDF();
downlooadPDF.execute(url, userAgent, contentDisposition);
//Toast.makeText(MainActivity.this, "Downloding ...", Toast.LENGTH_SHORT).show();
}
});
}
//TCPDF
private class DownloadPDF extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
File myDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).toString() + "/myPDF");
// create the directory if it does not exist
if (!myDir.exists()) myDir.mkdirs();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.connect();
//get filename from the contentDisposition
String filename = null;
Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(sUrl[2]);
while (m.find()) {
filename = m.group(1);
}
File outputFile = new File(myDir, filename);
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
connection.disconnect();
output.flush();
output.close();
input.close();
displayPdf(); // a function to open the PDF file automatically
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void displayPdf() {
try {
Object filename = fileList();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/myPDF/" + filename);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (Exception e) {
Log.i("TAG", e.getMessage());
}
}
}

Related

How to download the files in specific folder in internal storage

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

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

Download a file with no extension from a server

I'm try to download a mp3 file from following URL. I found lot of articles and examples regarding file download. Those examples are based on URLs that end with a file extension, e.g.:- yourdomain.com/filename.mp3 but I want to download a file from following url which typically does not end with file extension.
youtubeinmp3.com/download/get/?i=1gsE32jF0aVaY0smDVf%2BmwnIZPrMDnGmchHBu0Hovd3Hl4NYqjNdym4RqjDSAis7p1n5O%2BeXmdwFxK9ugErLWQ%3D%3D
**Please note that I use the above url as-is without using Stackoverflow url formatting method to easily understand the question.
** I have tried the #Arsal Imam's solution as follows still not working
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
File cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"Folder Name");
if(!cacheDir.exists())
cacheDir.mkdirs();
File f=new File(cacheDir,"ddedddddd.mp3");
saveDir=f.getPath();
new DownloadFileFromURL().execute(fileURL);
}
});
and the async task code is as follows
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
try{
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveDir);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}
}
Although Volley library is not recommended for large download or streaming operations, however, I'd like to share my following working sample code.
Let's assume we download only MP3 files so I hard-code the extension. And of course, we should check more carefully to avoid exceptions (NullPointer...) such as checking whether headers contain "Content-Disposition" key or not...
Hope this helps!
Volley Custom class:
public class BaseVolleyRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
public BaseVolleyRequest(String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(0, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
Then in your Activity:
public class BinaryVolleyActivity extends AppCompatActivity {
private final Context mContext = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binary_volley);
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
String url = "http://www.youtubeinmp3.com/download/get/?i=3sI2yV5mJ0kQ8CnddqmANZqK8a%2BgVQJ%2Fmg3xwhHTUsJKuusOCZUzebuWW%2BJSFs0oz8VTs6ES3gjohKQMogixlQ%3D%3D";
BaseVolleyRequest volleyRequest = new BaseVolleyRequest(url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
Map<String, String> headers = response.headers;
String contentDisposition = headers.get("Content-Disposition");
// String contentType = headers.get("Content-Type");
String[] temp = contentDisposition.split("filename=");
String fileName = temp[1].replace("\"", "") + ".mp3";
InputStream inputStream = new ByteArrayInputStream(response.data);
createLocalFile(inputStream, fileName);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
volleyRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 10, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(volleyRequest);
}
private String createLocalFile(InputStream inputStream, String fileName) {
try {
String folderName = "MP3VOLLEY";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, folderName);
folder.mkdir();
File file = new File(folder, fileName);
file.createNewFile();
FileOutputStream f = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
f.write(buffer, 0, length);
}
//f.flush();
f.close();
return file.getPath();
} catch (IOException e) {
return e.getMessage();
}
}
}
Here the result screenshot:
NOTE:
As I commented below, because the direct download Url changes regularly, you should check the new url with some tools such as Postman for Chrome, if it responses binary instead of a web page (expired url), then the Url is valid and my code works for that Url.
Refer to the two following screenshots:
Expired url:
Un-expired url:
UPDATE BASIC LOGIC FOR GETTING DIRECT DOWNLOAD LINK FROM THAT SITE'S DOCUMENTATION:
According to Create Your Own YouTube To MP3 Downloader For Free
You can take a look at
JSON Example
You can also receive the data in JSON by setting the "format"
parameter to "JSON".
http://YouTubeInMP3.com/fetch/?format=JSON&video=http://www.youtube.com/watch?v=i62Zjga8JOM
Firstly, you create a JsonObjectRequest getting response from the above file link. Then, inside onResponse of this JsonObjectRequest you will get the direct download link, like this directUrl = response.getString("link"); and use BaseVolleyRequest volleyRequest
I have just told the logic for getting direct url, IMO, you should implement it yourself. Goodluck!
Use below code it works fine for encrypted URLs
public class HttpDownloadUtility {
private static final int BUFFER_SIZE = 4096;
/**
* Downloads a file from a URL
* #param fileURL HTTP URL of the file to be downloaded
* #param saveDir path of the directory to save the file
* #throws IOException
*/
public static void downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
}
The url returns a 302 redirect to the actual .mp3. The browser does the redirect in the background for you, but in your app you need to do it yourself. Here is an example on how to do that with HttpUrlConnection http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/
If you know the type of file in advance then you can download your file from url which don't have extension.
DownloadService .java
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
private Context context;
private PowerManager.WakeLock mWakeLock;
ProgressDialog mProgressDialog;
String filename;
File mypath;
String urlToDownload;
BroadcastReceiver broadcaster;
Intent intent1;
static final public String BROADCAST_ACTION = "com.example.app.activity.test.broadcast";
public DownloadService() {
super("DownloadService");
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
intent1 = new Intent(BROADCAST_ACTION);
}
#Override
protected void onHandleIntent(Intent intent) {
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
intent1 = new Intent(BROADCAST_ACTION);
urlToDownload = intent.getStringExtra("url");
filename= intent.getStringExtra("filename");
BufferedWriter out;
try {
File path=new File("/sdcard/","folder name");
path.mkdir();
mypath=new File(path,filename);
Log.e("mypath",""+mypath);
if (!mypath.exists()) {
out= new BufferedWriter(new FileWriter(mypath));
//ut = new OutputStreamWriter(context.openFileOutput( mypath.getAbsolutePath() ,Context.MODE_PRIVATE));
out.write("test");
out.close();
}
}catch(Exception e){
e.printStackTrace();
}
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream(mypath);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int) (total * 100 / fileLength));
//Log.e("mypath",""+mypath);
resultData.putString("mypath", ""+mypath);
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress" ,100);
resultData.putString("mypath", ""+mypath);
receiver.send(UPDATE_PROGRESS, resultData);
intent1.putExtra("progressbar", 100);
sendBroadcast(intent1);
}
}
DownloadReceiver.java
public class DownloadReceiver extends ResultReceiver{
private Context context;
private PowerManager.WakeLock mWakeLock;
ProgressDialog mProgressDialog;
String filename;
String mypath;
public DownloadReceiver(Handler handler ,String filename ,Context context) {
super(handler);
this.context = context;
this.filename = filename;
mProgressDialog = new ProgressDialog(context);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress");
mypath = resultData.getString("mypath");
mProgressDialog.setProgress(progress);
//Log.e("progress","progress");
mProgressDialog.setMessage("App name");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
if (progress == 100) {
mProgressDialog.dismiss();
Log.e("download","download");
}
}
}
}
Now start service in your mainactivity by below code :
Intent miIntent = new Intent(mContext, DownloadService.class);
miIntent.putExtra("url", url);
miIntent.putExtra("filename", id+".mp3");
miIntent.putExtra("receiver", new DownloadReceiver(new Handler() , id,mContext));
startService(miIntent);

How can I open pdf in my webview using google Docs? (Suddenly it's not work)

Not long age, I can open pdf in my webview using below my code.
view.loadUrl("https://docs.google.com/gview?embedded=true&url=" + str);
But suddenly it's not work.
I don't know the reason.
How can I open pdf in my webview??
Create a downloader class
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
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) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
In your activity after setContentView(R.layout.main);write these lines
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("URL", file);
showPdf();
Write this method
public void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+"/Mypdf/Read.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
add these permissions in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I think this question is repeated, I get the solution
1) Type:
webView.loadUrl("https://docs.google.com/gview?url="+pdfUrl.get(position).url);
2) Don't forget to set webview client
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(getActivity());
progressDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}
});

Android - DownloadListener or AsyncTask

am trying to download from web page some files by clinking the url with webview handling the download not the browser
if i use DownloadListener it works perfectly with one problem i cant see the progressbar
if i use the AsyncTask i have to put the url in the code to download it i can just click the url and start downloading
my question is how can i let the AsyncTask download any url from the web without sitting the
downloadFile.execute("the url to the file you want to download");
or how i can create progressbar for DownloadListener
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
myProgressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
new Thread(myThread).start();
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.setInitialScale(50);
webview.getSettings().setUseWideViewPort(true);
webview.setVerticalScrollBarEnabled(false);
webview.setHorizontalScrollBarEnabled(false);
webview.loadUrl("http://localhost/index.php");
webview.setWebViewClient(new DownloadWebViewClient());
webview.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
InputStream is;
try {
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.connect();
is = con.getInputStream();
// Path and File where to download the APK
String path = Environment.getExternalStorageDirectory() + "/apdroid/";
String fileName = url.substring(url.lastIndexOf('/') + 1);
File dir = new File(path);
dir.mkdirs(); // creates the download directory if not exist
File outputFile = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
// Save file from URL to download directory on external storage
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
Intent intent = new Intent(Intent.ACTION_VIEW);
String name = Environment.getExternalStorageDirectory() + "/apdroid/" + url.substring(url.lastIndexOf('/') + 1);
intent.setDataAndType(Uri.fromFile(new File(name)), "application/vnd.android.package-archive");
startActivity(intent);
}catch (IOException e) {
e.printStackTrace();
}
}
});
}
protected void install(String fileName) {
// TODO Auto-generated method stub
}
private Runnable myThread = new Runnable() {
#Override
public void run() {
while (myProgress < 100) {
try {
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
} catch (Throwable t) {
}
}
}
Handler myHandle = new Handler() {
#Override
public void handleMessage(Message msg) {
myProgress++;
myProgressBar.setProgress(myProgress);
}
};
};
private class HelloWebViewClient extends WebViewClient {
#Override
public void onReceivedError(WebView view,int errorCode,String description,String failingUrl) {
try {view.stopLoading();} catch(Exception e){}
try {view.clearView();} catch(Exception e){}
view.loadUrl("file:///android_asset/wifi.html");
}
}
i just want to have ProgressBar when i download any file from my page
and i cant use asyncTask because i have to put the files in the code not by clicking at them
You should probably be overriding the URL loading process, and recognize by some way if any URL is being loaded whose resource you would want to download.
As soon as you detect this, stop loading the page and start the AsyncTask with this URL.

Categories

Resources