I am trying to use my download code that works perfectly fine in my other app, but it is acting very strange in this new app I am trying to make.
public class DownloadFile extends AsyncTask<Void, Integer, String> {
String SDCardRoot;
String mixtapeurl = "http://xxxxxx.com/xxxxxxxxxxxx/Mixtapes/NCredible/J.%20Cole%20-%20Cole%20World.zip";
NotificationManager notificationManager;
Notification notification2;
ProgressBar progressBar;
#Override
protected void onPreExecute() {
// configure the intent
Intent intent = new Intent();
final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
// configure the notification
notification2 = new Notification(R.drawable.download, "DOWNLOADING: " + mixtapeurl, System
.currentTimeMillis());
notification2.flags = notification2.flags | Notification.FLAG_ONGOING_EVENT;
notification2.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_progress);
notification2.contentIntent = pendingIntent;
notification2.contentView.setTextViewText(R.id.percentage, 0 + "%" );
notification2.contentView.setTextViewText(R.id.status_text, "DOWNLOADING: " + mixtapeurl);
notification2.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
getApplicationContext();
notificationManager = (NotificationManager) getApplicationContext().getSystemService(
Context.NOTIFICATION_SERVICE);
notificationManager.notify(2, notification2);
}
#Override
protected String doInBackground(Void... params) {
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(mixtapeurl);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
SDCardRoot = Environment.getExternalStorageDirectory() + "/download/";
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,mixtapeurl);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
int myProgress;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
int previousProgress = 0;
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
//publishProgress((int)(total*100/lenghtOfFile));
myProgress = (int) ((downloadedSize/(double)totalSize) * (double)100);
if ((myProgress) > 1 && (myProgress) > ((previousProgress ))) {
previousProgress= myProgress;
publishProgress(myProgress);
}
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "success";}
#Override
protected void onProgressUpdate(Integer... progression) {
String percent;
percent = progression[0].toString();
notification2.contentView.setProgressBar(R.id.status_progress, 100, progression[0], false);
notification2.contentView.setTextViewText(R.id.percentage, percent + "%" );
notificationManager.notify(2, notification2);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(getApplicationContext(), mixtapeurl + " downloaded to: " + SDCardRoot, Toast.LENGTH_LONG);
toast.show();
}
}
Here is how I implement it:
new DownloadFile().execute();
And what i get is "http://xxxxxx.com/xxxxxxxxxxxx/Mixtapes/NCredible/J.%20Cole%20-%20Cole%20World.zip download to null" for my toast right after I click the button and the file does not download at all.
This sounds like a very common issue: Forgot to set permission in manifest.
<uses-permission android:name="android.permission.INTERNET" />
Related
I have a video that plays on my application from a server. I want to make it possible to share the video to WhatsApp when the shared button is clicked.
I understand that I have to download load the video to the device storage before sharing through Intent. Below is my code, when the shared button is click the progress bar keeps loading and nothing else happens, I'm also using FileProvider. How do I go about this?
The getVideoUrl() method below takes in the video url and returns the Uri (file path) after the video has been downloaded
private Uri getVideoUrl(String fileURL) {
Uri videoUri = null;
try {
File rootFile = new File(getCacheDir(), "share_video_" + System.currentTimeMillis() + ".mp4");
URL url = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
FileOutputStream f = new FileOutputStream(rootFile);
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
videoUri = FileProvider.getUriForFile(this,
getPackageName() + ".provider", rootFile);
f.close();
} catch (IOException e) {
Log.d("Error....", e.toString());
}
return videoUri; // returns the file path to the video from storage
}
method to share the video,which is called is onClick of the share button. Then I receive the resultCode in onActivityResult() and make the progressBar invisible and display a message that the video has been shared.
public void shareVideo(String videoUrl, String desc){
progressBar.setVisibility(View.VISIBLE);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("*/*");
i.setPackage("com.whatsapp");
i.putExtra(Intent.EXTRA_TEXT, desc ); //to share text
i.putExtra(Intent.EXTRA_STREAM, getVideoUrl(videoUrl)); //to share video
i = Intent.createChooser(i, "Share video");
startActivityForResult(i, POSTED_VIDEO);
}
shareVideo() is now called in the shareButtonOnClickListner()
#Override
public void onClick(View v) {
String videoUrl = "https://linktoVideo.mp4"; //just an example link
String desc = "Shared Video;
switch (v.getId()) {
case R.id.post_image:
shareVideo(videoUrl, desc);
}
}
What am I doing wrongly?
I am creating an app that is downloading a file then loads it onto an imageview but I am getting this error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
and this is my download code
class DownloadFileFromURL extends AsyncTask<String, String, String> {
// Show Progress bar before downloading Music
#Override
protected void onPreExecute() {
super.onPreExecute();
// Shows Progress Bar Dialog and then call doInBackground method
showDialog(progress_bar_type);
}
// Download File from Internet
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Get Music file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),10*1024);
// Output stream to write file in SD card
int imageNr = sharedPreferences.getInt("ImageNr", 1);
OutputStream output = new FileOutputStream(getApplicationInfo().dataDir+"/files/"+imageNr+".jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
total += count;
// Publish the progress which triggers onProgressUpdate method
publishProgress("" + (total));
// Write data to file
}
// Flush output
output.flush();
// Close streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
// While Downloading Music File
protected void onProgressUpdate(String... progress) {
// Set progress percentage
prgDialog.setProgress(Integer.parseInt(progress[0]));
}
// Once File is downloaded
#Override
protected void onPostExecute(String file_url) {
// Dismiss the dialog after the Music file was downloaded
dismissDialog(progress_bar_type);
int imageNr = sharedPreferences.getInt("ImageNr", 1);
File imgFile = new File(getApplicationInfo().dataDir+"/files/"+imageNr+".jpg");
imageNr++;
SharedPreferences.Editor editorsave = sharedPreferences.edit();
editorsave.putInt("ImageNr", imageNr);
editorsave.apply();
if(imgFile.exists()){
Toast.makeText(getApplicationContext(), "Bild laddad!", Toast.LENGTH_LONG).show();
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
}else{
Toast.makeText(getApplicationContext(), "Bild ej hittad!", Toast.LENGTH_LONG).show();
}
// Do stuff here
}
}
yeah it uses some deprecated code but this is working for me in my other application, though I am not using bitmap in that one but the AsyncTask works.
your imageViewis null
to stay way from the exception itself
if(imgFile.exists() && imageView != null) {
....
check your imageView reference assignment. It seems imageView reference is not assigned properly, hence returns null
I getting issue while downloading a PDF file on click of button click in webview.
File is downloaded but the file is partly downloaded that's why i am getting below error
"The document cannot be opened because it is not a valid PDF document"
Below is Asyncetask activity of my to download file:
public class DownloadPDFTask extends AsyncTask<String, Void, Integer>
{
protected ProgressDialog mWorkingDialog; // progress dialog
protected String mFileName; // downloaded file
protected String mError; // for errors
#Override
protected Integer doInBackground(String... urls)
{
String filename = "";
String str[] = urls[2].split(";");
String st[] =str[1].split("=");
filename = st[1];
String extStorageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
File myDir = new File(extStorageDirectory, "NCR");
File file = new File(extStorageDirectory+"/NCR/"+filename);
// create the directory if it does not exist
if (!myDir.exists())
myDir.mkdirs();
if (file.exists()) {
System.out.println("INSIDE FILE EXIST");
file.delete();
}
try
{
byte[] dataBuffer = new byte[4096];
int nRead = 0;
mFileName = filename;
System.out.println("mFileName<><><> " +mFileName);
// download URL and store to strFileName
// connection to url
java.net.URL urlReport = new java.net.URL(urls[0]);
URLConnection urlConn = urlReport.openConnection();
urlConn.setRequestProperty("User-Agent", urls[1]);
urlConn.setRequestProperty("Content-Disposition", urls[2]);
urlConn.setRequestProperty("Content-Type", "application/pdf");
urlConn.setRequestProperty("Accept", "*/*");
InputStream streamInput = urlReport.openStream();
BufferedInputStream bufferedStreamInput = new BufferedInputStream(streamInput,8192);
FileOutputStream outputStream = new FileOutputStream(extStorageDirectory+"/NCR/"+mFileName);
while ((nRead = bufferedStreamInput.read(dataBuffer)) > 0)
outputStream.write(dataBuffer, 0, nRead);
streamInput.close();
outputStream.close();
// displayPdf(mFileName);
}
catch (Exception e)
{
Log.e("myApp", e.getMessage());
mError = e.getMessage();
return (1);
}
return (0);
}
#Override
protected void onPreExecute()
{
// show "Downloading, Please Wait" dialog
mWorkingDialog = ProgressDialog.show(context, "", "Downloading PDF Document, Please Wait...", true);
return;
}
#Override
protected void onPostExecute (Integer result)
{
if (mWorkingDialog != null)
{
mWorkingDialog.dismiss();
mWorkingDialog = null;
}
switch (result)
{
case 0: // a URL
try
{
displayPdf(mFileName);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(context, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
}
break;
case 1: // Error
Toast.makeText(context, mError, Toast.LENGTH_LONG).show();
break;
}
}
}
Friends I am stuck on this, Please help me out.
Hope this will help you. I tested this code and this is working fine.
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
int count;
try{
URL url=new URL(params[0]);
URLConnection connection=url.openConnection();
connection.connect();
//getting file length
long lengthOfFile=connection.getContentLength();
//input stream to read file with 8k buffer
InputStream input=new BufferedInputStream(url.openStream(),8192);
//out stream to write file
OutputStream output=new FileOutputStream(Environment.getExternalStorageDirectory()+"/Download/Test/software_testing.pdf");
byte data[]= new byte[1024];
long total =0;
while ((count = input.read(data)) != -1){
if(isCancelled())
return null;
total +=count;
//publishing the progress
//After this onProgressUpdate will be called
if(lengthOfFile > 0){
//System.out.println((int)((total*100)/lengthOfFile)+"First Line");
//Call onProgressUpdate() for display status
publishProgress((int)((total*100)/lengthOfFile));
}
//writing data to file
output.write(data,0,count);
}
//flushing output
output.flush();
//closing stream
output.close();
input.close();
}catch(Exception e){
Log.e("Error", e.getMessage());
System.out.println("Exception :"+e.getMessage());
}
return null;
}
EDITED:
Extend your class from AsyncTask<String, Integer, String> and override its' methods.
`
onPreExecute() used to do process before start the download.
doInBackground(String... params) used to do the process while
downloading the file. The above code is for this method.
onProgressUpdate(Integer... progress) used to do setting the
progress bar according to the current download percentage. Once you use publishProgress (), this method will invoke.
onPostExecute(String file_url) This method can used to dismiss the
dislog after the file was downloaded.
So what you have to do is set your progress bar to update according to the downloading percentage inside onProgressUpdate (Integer... progress). You can use setProgress() method for that.
I hope now you understand the process well :)
This might not be an issue, but your while loop isn't correct:
while ((nRead = bufferedStreamInput.read(dataBuffer)) > 0)
outputStream.write(dataBuffer, 0, nRead);
The BufferedInputStream.read() returns a -1 when it reaches the end of the stream.
Rather, your terminating condition should be:
while ((nRead = bufferedStreamInput.read(dataBuffer)) != -1)
outputStream.write(dataBuffer, 0, nRead);
I hope this helps.
I am trying to download multiple file using AsyncTask.
I start each download in one AsyncTask with progress bar in notification bar but i face many problems.
If i download 4 or 5 files at the same time the one or more files
interrupted without any reason.
If i download 4 or 5 images the one or more images corrupted.
this is the code i used.
private class DownloadFile extends AsyncTask<String, Integer, Long>
{
int nID = 0;
int nDownloadCounter = 0;
public DownloadFile(String sFileName, int nNotificationID) {
this.nID = nNotificationID;
this.NotificationName = sFileName;
this.nDownloadCounter = 0;
}
protected void onPreExecute(){
this.sDownloadPath = sFilePathWithSubDir;
notification = new Notification(R.drawable.app_icon, "Download File", System.currentTimeMillis());
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
Intent notificationIntent = new Intent();
File file = new File(this.sDownloadPath + this.NotificationName);
sMediaDataType = GSUtilities.sGetFileMIMEType(this.NotificationName);
notificationIntent.setAction(android.content.Intent.ACTION_VIEW);
notificationIntent.setDataAndType(Uri.fromFile(file), sMediaDataType);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
contentView.setTextViewText(R.id.status_percent, "0%");
contentView.setTextViewText(R.id.status_fileName, this.NotificationName);
contentView.setProgressBar(R.id.status_progress, 100, 0, false);
notification.contentView = contentView;
notification.contentIntent = contentIntent;
mNotificationManager.notify(nID, notification);
}
protected Long doInBackground(String... urls) {
long retData = 0;
OutputStream fosXSPDatabse = null;
InputStream inServerResponse = null;
URLConnection oURLConnection = null;
URL oURL = null;
try
{
oURL = new URL(oFileManager.sExpiryLink);
oURLConnection = oURL.openConnection();
if (!(oURLConnection instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
oURLConnection.connect();
inServerResponse = new BufferedInputStream(oURL.openStream());
if (inServerResponse != null)
{
File fDirectory = new File(oFileManager.sAppFlesDirectory);
if (!fDirectory.exists())
{
if (!fDirectory.mkdir())
{}
}
fosXSPDatabse = new FileOutputStream(oFileManager.sAppFlesDirectory + "/" + oFileInfo.getFileName());
byte data[] = new byte[BUFFER_SIZE];
int nCount = 0;
long lTotalDownloaded = 0;
int nTotalSize = oURLConnection.getContentLength();
while ((nCount = inServerResponse.read(data)) != -1)
{
Log.d(String.valueOf(nID) + " - DoInBackground", String.valueOf(dNotificationbarProgress));
nDownloadCounter ++;
lTotalDownloaded += nCount;
dNotificationbarProgress = lTotalDownloaded * 100.0 / nTotalSize;
if (this.nDownloadCounter == 20 || dNotificationbarProgress == 100) {
publishProgress(Integer.parseInt(new DecimalFormat("#.##").format(dNotificationbarProgress).split("\\.")[0]));
nDownloadCounter = 0;
}
fosXSPDatabse.write(data, 0, nCount);
}
inServerResponse.close();
fosXSPDatabse.flush();
fosXSPDatabse.close();
}
}
catch (MalformedURLException e)
{}
catch (IOException e)
{}
catch (Exception e)
{}
finally
{
try
{
inServerResponse.close();
fosXSPDatabse.flush();
fosXSPDatabse.close();
}
catch (IOException e)
{}
}
return retData;
}
protected void onProgressUpdate(Integer... progress) {
try
{
Log.d(String.valueOf(nID),"onProgressUpdate");
notification.contentView.setProgressBar(R.id.status_progress, 100, progress[0], false);
notification.contentView.setTextViewText(R.id.status_fileName, this.NotificationName);
notification.contentView.setTextViewText(R.id.status_percent, String.valueOf(progress[0]) + "%");
Intent notificationIntent = new Intent();
File file = new File(this.sDownloadPath + this.NotificationName);
sMediaDataType = GSUtilities.sGetFileMIMEType(this.NotificationName);
notificationIntent.setAction(android.content.Intent.ACTION_VIEW);
notificationIntent.setDataAndType(Uri.fromFile(file), sMediaDataType);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
mNotificationManager.notify(this.nID, notification);
}
catch(Exception e)
{}
}
protected void onPostExecute(Long result) {
notification.contentView.setTextViewText(R.id.status_fileName, "Successfully installed " + this.NotificationName);
notification.contentView.setTextViewText(R.id.status_percent, "100%");
mNotificationManager.notify(this.nID, notification);
}
}
First, it's never a good idea to silently ignore Exceptions. You should at minumum log them to logcat. It think this is the problem.
Second, you're closing the streams multiple times.
Where are you calling the AsyncTask from?
If it's from an activity and the user navigates away from it, that might be terminated any time the OS wants to free up memory.
If it's from a service, that could be terminated too, but at least it is restarted later. If the service was started from a different process, such as a Sync Adapter, you should also post the PreExecute and PublishProgress and PostExecute code to the UI thread with the application looper handler as a message.
In adition, try limiting the number of concurrent downloads to max 3. Otherwise, an OutOfMemory might occur. You can do this with a BlockingQueue. If concurrency is not important, consider using an IntentService instead of an AsyncTask.
The Best way to handle download multiple files is to use the Service.
What I would like to do is give my app the ability to download my mp3 of my server. So far I have the download mp3 into a audio file working but it's very finicky and cannot be disturbed in order for it to work properly. That being said I would love to have a progress dialog pop up that cannot be canceled so the user can't interrupt the progress while downloading the file to the folder in the background. After reading it seemed that AsyncTask would be the best way to do this but I cannot get it to work. Below is one of the buttons from my code.
public class music extends Activity {
public static int mProgress = 0;
static String filename;
MediaPlayer buttonclicker;
static Toast msg;
public static int totalSize = 0;
public ProgressDialog dialog;
public static boolean isFinished;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
buttonclicker = MediaPlayer.create(this, R.raw.button );
Button boomFullDownload = (Button) findViewById(R.id.boomfull);
boomFullDownload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonclicker.start();
filename = "boomboom.mp3";
new downloadPumphouseShow().execute(filename);
}
class downloadPumphouseShow extends AsyncTask<String , Void, Void> {
ProgressDialog dialog;
Toast msg;
protected void onPreExecute (){
dialog = new ProgressDialog(context);
msg = Toast.makeText(context, " File Exist ", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
dialog.setMessage("Please Wait Loading");
dialog.setCancelable(false);
dialog.show();
}
}
});
protected void onPostExecute(Void result) {
dialog.hide();
dialog.dismiss();
}
protected Void doInBackground(String... params) {
String filename = params[0];
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL("http://lepumphouse.com/media/" + filename );
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File Music = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "/Pumphouse/Party Cake");
//create a new file, specifying the path, and the filename
if(Music.exists())
msg.show();
else
Music.mkdirs();
//which we want to save the file as.
File file = new File(Music, filename);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int mProgress = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
mProgress += bufferLength;
//this is where you would do something to report the pr0gress, like this maybe
}
//close the output stream when done
// progressDialog.dismiss();
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
So if I stripped out all the code dealing with asynctask it works it's just extremely un-user friendly but the files do download. When I try to add the progress dialog and background task it quits on me. I have a feeling it has to do with the parameters.
protected void onPreExecute() {
dialog=ProgressDialog.show(mContext, "", "Fetching book oversight");
msg = Toast.makeText(context, " File Exist ", Toast.LENGTH_LONG).show;
super.onPreExecute();
}
protected void onPostExecute(Void result) {
if(dialog!=null)
{
dialog.dismiss();
}
}
Try this, a alternate way to show Dialog
Just a quick scan, I don't think you should be calling msg.show(); from the background thread.