AsyncTask does not execute in onCreate() - android

I want that If my app start first time it should download image from web and store that image in Device/Emulator, from Device/Emulator that should be displayed in ImageView.
I have tried in this way :
ImageView myImgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myImgView = (ImageView) findViewById(R.id.imageView1);
new MyAsnyc();
Log.d(MY_TAGT, "AsyncTask Executed.....");
}
private class MyAsnyc extends AsyncTask<Void, Void,Void>{
public File file ;
InputStream is;
private Bitmap bitmap;
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(BASE_URL);
/* 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);
Log.i(MY_TAGT, "Picture is readable........");
os.write(data);
Log.i(MY_TAGT, "Picture is Saved........");
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 (Exception e) {
// TODO: handle exception
}
/*Here I want to set this image in ImageView*/
bitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()+"/DemoPicture.jpg");
myImgView.setImageBitmap(bitmap);
}
}
But in this way MyAsync class is not executed, please tell how to do that.
EDIT this is my log

Use execute to call it.
new MyAsnyc().execute();

use
new MyAsnyc().execute();
instead of
new MyAsnyc();
because AsyncTask.execute(Params... params) method used for executing an AsyncTask
EDIT :
use While or for loop for writing data in file as :
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
Log.i(MY_TAGT, "Picture is readable........");
int count;
while ( (count = is.read(data)) >= 0 ) {
os.write(data,0,count)
}
Log.i(MY_TAGT, "Picture is Saved........");
is.close();
os.close();

You must try this :
public class DownloadImage {
public static File getImage(String imageUrl, String fileName){
File file = null;
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(imageUrl);
Log.d("INFORMATION..", "FILE FOUNDED....");
//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();
Log.d("INFORMATION..", "FILE CONECTED....");
//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 SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
file = new File(SDCardRoot, fileName);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
Log.d("INFORMATION..", "WRINTING TO FILE DOWNLOADED...." + 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;
//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
downloadedSize += bufferLength;
Log.d("INFORMATION..", "FILE DOWNLOADED....");
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
Log.d("INFORMATION..", "FILE DOWNLOADING COMPLETED....");
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
}
Call this DownloadImage.getImage(String imageUrl, String fileName) in MainActivity.java like this :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
String url = "http://4.bp.blogspot.com/-8v_k_fOcfP8/UQIL4ufghBI/AAAAAAAAEDo/9ffRRTM9AnA/s1600/android-robog-alone.png";
String file = DownloadImage.getImage(url, "My Image.jpg").toString();
// Get file path on device and set it to imageView
Bitmap bitmap = BitmapFactory.decodeFile(file);
imageView.setImageBitmap(bitmap);
}
}
I think this what you are looking for! hope this will help you

You forgot to execute the AsyncTask:
(new MyAsnyc()).execute();

Before line Log.d(MY_TAGT, "AsyncTask Executed.....");
you just construct new AsyncTask object but you didn't call execution on it with execute() method..
EDIT: second problem is that it is not so clear WHICH picture actually you want to display in that ImageView.. cause bitmap = BitmapFactory.decodeFile(..blahblahblah..) will probably be null after this.. It seems to me u r giving folder name and you wanted to decode that "file" to bitmap.. Make some logs about this decoding and bitmap value and show us..
Edit2:
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
bitmap = BitmapFactory.decodeFile(file);
should work a bit better..

Related

How can I share gif images to other app?

I am using glide to load GIF images into a RecyclerView.
Glide.with(context).load(imageUrl.trim())
.asGif()
.placeholder(R.drawable.coming)
.error(R.drawable.error)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(holder.gif_image);
if your GIF image on web
whatsapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
whatsappIntent.setType("image/*");
whatsappIntent.setPackage("com.whatsapp");
new Download_GIF(image).execute();
Uri imageUri = Uri.parse("file:///storage/emulated/0/downloadedFile.gif");
whatsappIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
try {
startActivity(whatsappIntent);
} catch (android.content.ActivityNotFoundException ex) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.whatsapp"));
startActivity(intent);
} catch (Exception e) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.whatsapp"));
intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
});
here whatsapp is imageButton
Download_GIF class
public class Download_GIF extends AsyncTask<String, Void, String> {
static String url_image=null;
public Download_GIF(String url) {
this.url_image = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String filepath = null;
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(url_image);
//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 SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
String filename = "downloadedFile.gif"; // you can download to any type of file ex:.jpeg (image) ,.txt(text file),.mp3 (audio file)
Log.i("Local filename:", "" + filename);
File file;
file = new File(SDCardRoot, filename);
if (file.createNewFile()) {
file.createNewFile();
}
//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;
//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
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
Log.i("Progress:", "downloadedSize:" + downloadedSize + "totalSize:" + totalSize);
}
//close the output stream when done
fileOutput.close();
if (downloadedSize == totalSize) filepath = file.getPath();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
filepath = null;
e.printStackTrace();
}
Log.i("filepath:", " " + filepath);
return filepath;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
you can't share gifs between android apps because there's not a protocol for that.
sorry friend.
maybe if you want to share between apps built for you, you can serialize the image and a flag ( headers or another parameter ) to know it's a gif.

Android - Saving image into SD Card through AsyncTask fails

I have images in my drawables folder. Activity opens them, I choose the needed images and click on button. They must be saved on my SD Card through ImageSavingTask class instance execution which extends AsyncTask.
Here is my onClick code:
#Override
public void onClick(View v) {
for (int i = 0; i < 26; i++)
if (checkBoxes[i].isChecked()) {
imageIndex = new ImageIndex(); //ImageIndex-a class with single index field which reserves the checked checkbox indexes.
imageIndex.index = i;
Bitmap bitmap = ((BitmapDrawable) (images[i].getDrawable())).getBitmap();
SaveImageTask saveImageTask = new SaveImageTask();
saveImageTask.execute(bitmap); //The class SaveImageTask extends AsyncTask<Bitmap, Void, Void>
}
}
Then the selected images are handled in doInBackground method.
#Override
protected Void doInBackground(Bitmap... params) {
FileOutputStream outStream = null;
try {
Bitmap bitmap = params[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageBytes = stream.toByteArray();
File sdCard = Environment.getExternalStorageDirectory();
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
File dir = new File(sdCard.getAbsolutePath());
dir.mkdirs();
String fileName = "Saved image " + imageIndex.index; //The reserved index of checkbox creates a name for the new file.
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(imageBytes);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> line is added in my manifest.
After I connect the USB to my phone, no error happens, but no images are saved to my SD Card. And I can't find images on my phone using windows search. Debugging doesn't give any answer. What kind of problem this could be?
It seems you have not asked runtime permissions for writing file on SD Card. From Android M and above you need to ask write permission at runtime to save any file on external sd card.
Check this link on how to request runtime permissions- https://developer.android.com/training/permissions/requesting.html
Also you can use google library - https://github.com/googlesamples/easypermissions
to request permissions.
I add the selected indexes into 2 ArrayLists of indexes and bitmaps. In the doInBackground method I created a loop.
For appearing the images on the card immediately I used the MediaScannerConnection.scanFile method.
for (int i = 0; i < 26; i++)
if (checkBoxes[i].isChecked()) {
index.add(i);
bitmap.add(bitmaps[i]);
}
if (bitmap.size() > 0)
new SaveImageTask().execute();
The doInBackground method:
protected Void doInBackground(Void... params) {
for (int i = 0; i < bitmap.size(); i++) {
try {
fname = "Saved image " + (index.get(i)) + ".jpg";
file = new File(myDir, fname);
if (file.exists()) file.delete();
FileOutputStream out = new FileOutputStream(file);
bitmap.get(i).compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
MediaScannerConnection.
scanFile(getApplicationContext(), new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
I left the ImageSavingTask without fields and parameters.
I think problem where you try to write bytes.
Use Following Solution..
#Override
protected Void doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
saveToInternalStorage(bitmap, "MyImage"); // pass bitmap and ImageName
return null;
}
//Method to save Image in InternalStorage
private void saveToInternalStorage(Bitmap bitmapImage, String imageName) {
File mypath = new File(Environment.getExternalStorageDirectory(), imageName + ".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NOTE : Make sure you have added storage read/write permission and don't forget to ask permission on Marshmallow and higher version.

Saving the Images from string array to SD card and Phone gallery

I am using string array to hold images, i am fetching the imaes from the URLs. I have one imageview which when swipped changes the images in it. Now i want to download and save any image i want on the SD card and want it to appear in the phone gallery in a new folder.
I am using the following code but it is not working, it is showing no error at all.
private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... arg0) {
downloadImagesToSdCard("", "");
return null;
}
private void downloadImagesToSdCard(String downloadUrl, String imageName) {
try {
URL url = new URL(thumb[j]);
/* making a directory in sdcard */
String sdCard = Environment.getExternalStorageDirectory()
.toString();
File myDir = new File(sdCard, "test.jpg");
/* if specified not exist create new */
if (!myDir.exists()) {
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = imageName;
File file = new File(myDir, fname);
if (file.exists())
file.delete();
/* Open a connection */
URLConnection ucon = url.openConnection();
InputStream inputStream = null;
HttpURLConnection httpConn = (HttpURLConnection) ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
FileOutputStream fos = new FileOutputStream(file);
int totalSize = httpConn.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:", "downloadedSize:" + downloadedSize
+ "totalSize:" + totalSize);
}
fos.close();
Log.d("test", "Image Saved in sdcard..");
} catch (IOException io) {
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And i am executing it by
new ImageDownloadAndSave().execute("");
the name of my string array is "thumb" which is holding all the URLs. What am i doing wrong?
You should add image to gallery after save and then scan it. Please check the following topics:
Image, saved to sdcard, doesn't appear in Android's Gallery app
MediaScannerConnection
The file needs to be added to the Android MediaStore. This can be done easily by using below function.
public void scanFile(final File file) {
try {
new MediaScannerConnectionClient() {
private MediaScannerConnection mMs;
public void init() {
mMs = new MediaScannerConnection(myContext, this);
mMs.connect();
}
#Override
public void onMediaScannerConnected() {
mMs.scanFile(file.getAbsolutePath(), null);
mMs.disconnect();
}
#Override
public void onScanCompleted(String path, Uri uri) {
}
}.init();
} catch(Exception e) {
// Device does not support adding files manually.
// Sending Broadcast to start MediaScanner (slower than adding manually)
try {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
} catch(Exception ee) {
// Something went terribly wrong.
// Can't add file to MediaStore and can't send Broadcast to start MediaScanner.
}
}
}
You just need to add one line to your code:
// .....
fos.close();
Log.d("test", "Image Saved in sdcard..");
scanFile(file); // <------------- add this

Download PDF file android

i have An Error while download PDF file From Server and save it on SD
i have permission To Access internet and external storage ..
It`s working fine on android 2.3.6
But on Tab 4.1.1 its create the file with 0 byte
URL url = new URL("https://docs.google.com/"+direct);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type", "application/xml");
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 SDCardRoot = new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/folder/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,book.getBook_name()+".pdf");
//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
totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
//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
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
publishProgress((downloadedSize*100)/totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Try this:
private String getExternalSDPath() {
File file = new File("/system/etc/vold.fstab");
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
// handle
}
String path = null;
try {
if (fr != null) {
br = new BufferedReader(fr);
String s = br.readLine();
while (s != null) {
if (s.startsWith("dev_mount")) {
String[] tokens = s.split("\\s");
path = tokens[2]; // mount_point
if (Environment.getExternalStorageDirectory()
.getAbsolutePath().equals(path)) {
break;
}
}
s = br.readLine();
}
}
} catch (IOException e) {
// handle
} finally {
try {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
} catch (IOException e) {
// handle
}
}
return path;
}
The code is made specifically for Samsung Devices with both internal, an internal that acts as external, and SD.
I needed to access the SD and came up with the above code, so you can try it and possibly modify it to work on all devices.
Edit: My download AsyncTask
private class DownloadFile extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String filename = "somefile.pdf";
HttpURLConnection c;
try {
URL url = new URL("http://someurl.com/" + filename);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File myFilesDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Download");
File file= new File(myFilesDir, filename);
if (file.exists()) {
file.delete();
}
if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
try {
InputStream is = c.getInputStream();
FileOutputStream fos = new FileOutputStream(myFilesDir
+ "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (Exception e) {
return e.getMessage();
}
} else {
return "Unable to create folder";
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
super.onPostExecute(result);
}
}

Can someone help me put this download code that I use in ASyncTask?

It works just fine when I run it in a thread, but I want to use Asynctask and when I execute my version of it, nothing happens:
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(filename2);
//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,filename3);
//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;
//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
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
//publishProgress((int)(total*100/lenghtOfFile));
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
THIS IS MY ATTEMPT AS REQUESTED:
private class DownloadFile extends AsyncTask<Void, Integer, Long> {
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
Intent in = new Intent(mainmenu.this, DownloadService.class);
stopService(in);
}
#Override
protected Long 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(filename2);
//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,filename3);
//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;
//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
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
//publishProgress((int)(total*100/lenghtOfFile));
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
here you go
public class WebRequest extends AsyncTask<URL, Void, String> {
ProgressDialog dialog;
Context _context;
String _title;
String _message;
public WebRequest(Context context,
String ProgressTitle, String ProgressMessage) {
this._context = context;
this._title = ProgressTitle;
this._message = ProgressMessage;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog = new ProgressDialog(_context);
dialog.setTitle(_title);
dialog.setMessage(_message);
dialog.show();
}
#Override
protected String doInBackground(URL... params) {
// TODO Auto-generated method stub
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = params[0];
//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,filename3);
//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;
//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
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
//publishProgress((int)(total*100/lenghtOfFile));
}
//close the output stream when done
fileOutput.close();
return "Success";
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
return "Failed";
} catch (IOException e) {
e.printStackTrace();
return "Failed";
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (dialog.isShowing())
dialog.cancel();
Toast.makeText(_context,result,Toast.LENGTH_LONG);
}
}
//using this
WebRequest request = new WebRequest(context,"Downloading","Please wait..");
request.Execute(object of URL);

Categories

Resources