I need my android app to make request to url to download an image from this url
so I have built this class to help me, BUT it didn't work ???
public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;
protected void doInBackground() throws IOException {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try{
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
// Open a connection to that URL.
URLConnection ucon = url.openConnection();
// Define InputStreams to read from the URLConnection.
is = ucon.getInputStream();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
try {
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(
null,
new String[] { file.toString() },
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
}
);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And I have, in the Activity class on onclick(), this function:
public void down(View v) {
// ImageManager ob=new ImageManager();
// ob.DownloadFromUrl("");
new MyAsnyc().execute();
}
Although I have written the permissions in the manfiest.xml
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
try this
public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;
protected void doInBackground() throws IOException {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
is = ucon.getInputStream();
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
try {
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(null,
new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Define these on the top side
Button BtnDownload;
DownloadManager downloadManager;
After, You should write on create inside :
BtnDownload = (Button)findViewById(R.id.button1);
Later, You should write to the button's click event
downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("your url");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
Finally, you need to add this onto the application tag to the manifest.xml :
<uses-permission android:name="android.permission.INTERNET"/>
new DownloadImageFromUrlTask().execute(imagePath);
//add glide dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'
public class DownloadImageFromUrlTask extends AsyncTask<String, Void, Bitmap> {
String downloadPath = "";
#Override
protected Bitmap doInBackground(String... args) {
try {
downloadPath = args[0];
return BitmapFactory.decodeStream((InputStream) new URL(downloadPath).getContent());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
String photoFileName = downloadPath.substring(downloadPath.lastIndexOf('/') + 1);
String root_Path = Environment.getExternalStorageDirectory().toString();
String saveImagePath = root_Path + "/" + photoFileName;
saveBitmapToJPEGFile(MainActivity.this, bitmap, new File(saveImagePath), 900);
loadImageWithGlide(MainActivity.this, myImageView, saveImagePath);
} else {
myImageView.setImageResource(R.drawable.default_photo);
}
}
}
public static Boolean saveBitmapToJPEGFile(Context ctx, Bitmap theTempBitmap, File theTargetFile, int i) {
Boolean result = true;
if (theTempBitmap != null) {
FileOutputStream out = null;
try {
out = new FileOutputStream(theTargetFile);
theTempBitmap.compress(Bitmap.CompressFormat.JPEG, CommonUtils.JPEG_COMPRESION_RATIO_DEFAULT, out); //kdfsJpegCompressionRatio
} catch (FileNotFoundException e) {
result = false;
e.printStackTrace();
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
result = false;
}
return result;
}
public static void loadImageWithGlide(Context theCtx, ImageView theImageView, String theUrl) {
Glide.with(theCtx)
.load(theUrl)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(theImageView);
}
The problem with your code is you have not read the InputStream.
You should try this
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
and make the Asynctask return type as Bitmap.
Or,
As you have used that is in postExecute() your doInBackground() should return that InputStream object is. But you are returning void.
Okey.Try this edited Asynctask.
private class MyAsnyc extends AsyncTask <Void,Void,File> {
File file;
#Override
protected File doInBackground( Void... params ) {
InputStream is = null;
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File( path , "Demo Picture.jpg" ) ;
try { // Make sure the Pictures directory exists.path.mkdirs() ; URL url = new URL ( "http: / /androidsaveitem .appspot.com/download.jpg") ; URLConnection ucon = url.openConnection ( ) ;
path.mkdirs();
OutputStream os = new FileOutputStream(file) ;
byte [ ] data = new byte [ is.available ( ) ] ;
is.read ( data ) ; os.write (data );is.close ( ) ; os.close ( ) ;
return file;
}
catch (Exception e){
Log .d ( "ImageManager " , " Error: " + e ) ;
}
return null;
}
protected void onPostExecute (File file) {
try{
MediaScannerConnection.scanFile( null , new String [] {file.toString( ) } , null , new MediaScannerConnection.OnScanCompletedListener ( ) { public void onScanCompleted (String path, Uri uri) {
Log.i ( " External Storage" , " Scanned " + path + " : " ) ; Log.i ( " E x t e r n a l S t o r a g e " , " - > u r i = " + uri ) ; } } ) ;
}catch (Exception e) {
// TODO: handle exception
}
}}
Related
I am trying to create a separate folder in internal storage of a phone for an app to download files on it. But the folder is not created in the phone. What is the reason? Also I have another issue in my app that is photos are not downloaded when I click thee download button.
Here is the download function
public void download() {
for (MediaModel item : Items) {
if (item.isSelected) {
Log.d("check", "download");
final String url = item.getFullDownloadURL();
BaseDownloadTask task = FileDownloader.getImpl().create(url);
task.setListener(mFileDownloadListener)
.setPath(Environment.getDataDirectory() + "/" + Constants.STORED_FOLDER, true)
.setAutoRetryTimes(1)
.setCallbackProgressTimes(0)
.asInQueueTask()
.enqueue();
if (FileDownloader.getImpl().start(mFileDownloadListener, true)) {
item.setTaskId(task.getId());
item.setStatus(ItemStatus.DOWNLOADING);
Logging.e(TAG, "start download task: " + task.getId());
} else {
item.setTaskId(task.getId());
item.setStatus(ItemStatus.NORMAL);
Logging.e(TAG, "error download task: " + task.getId());
}
}
}
}
In Android studio to use internal Storage First of all add permission in manifest
Like this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
then to make new directory in internal storage use this line of code:
File sdCardRoot = new File(Environment.getExternalStorageDirectory(), "MyProfile");
if (!sdCardRoot.exists()) {
sdCardRoot.mkdirs();
}
Log.e("check_path", "" + sdCardRoot.getAbsolutePath());
This is my full code:
In this code check directory is exist or not if directory is not exist then create directory
and use asyntask to download images from url
In this example i have use Java Language
Code
MyAsyncTasks asyncTasks = new MyAsyncTasks();
asyncTasks.execute(Imageurl);
and AsyncClass:
class MyAsyncTasks extends AsyncTask<String, String, String> {
File sdCardRoot;
#Override
protected String doInBackground(String... strings) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
sdCardRoot = new File(Environment.getExternalStorageDirectory(), "MyProfile");
if (!sdCardRoot.exists()) {
sdCardRoot.mkdirs();
}
Log.e("check_path", "" + sdCardRoot.getAbsolutePath());
String fileName =
strings[0].substring(strings[0].lastIndexOf('/') + 1, strings[0].length());
Log.e("dfsdsjhgdjh", "" + fileName);
File imgFile =
new File(sdCardRoot, fileName);
if (!sdCardRoot.exists()) {
imgFile.createNewFile();
}
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
FileOutputStream outPut = new FileOutputStream(imgFile);
int downloadedSize = 0;
byte[] buffer = new byte[2024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
outPut.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.e("Progress:", "downloadedSize:" + Math.abs(downloadedSize * 100 / totalSize));
}
Log.e("Progress:", "imgFile.getAbsolutePath():" + imgFile.getAbsolutePath());
Log.e(TAG, "check image path 2" + imgFile.getAbsolutePath());
mImageArray.add(imgFile.getAbsolutePath());
outPut.close();
} catch (IOException e) {
e.printStackTrace();
Log.e("checkException:-", "" + e);
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
imagecount++;
Log.e("check_count", "" + totalimagecount + "==" + imagecount);
if (totalimagecount == imagecount) {
pDialog.dismiss();
imagecount = 0;
}
Log.e("ffgnjkhjdh", "checkvalue checkvalue" + checkvalue);
}
}
Try This code:
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
File apkStorage = null;
File outputFile = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(context);
progressDialog.setMessage("Downloading...");
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
try {
if (outputFile != null) {
progressDialog.dismiss();
CDToast.makeText(context, context.getResources().getString(R.string.downloaded_successfully), CDToast.LENGTH_SHORT, CDToast.TYPE_SUCCESS).show();
Notification();
vibrateDevice(100);
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
CDToast.makeText(context, context.getResources().getString(R.string.download_failed), CDToast.LENGTH_SHORT, CDToast.TYPE_ERROR).show();
}
} catch (Exception e) {
e.printStackTrace();
//Change button text if an exception occurs
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
}
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(downloadUrl);//Create Download URl
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.connect();//connect the URL Connection
//If Connection response is not OK then show Logs
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = new File(
Environment.getExternalStorageDirectory() + "/"
+ "New_Folder_Name_Here");
} else
Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();
//If File is not present create directory
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.close();
is.close();
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
For Checking SD card :
public class CheckForSDCard {
//Check If SD Card is present or not method
public boolean isSDCardPresent() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return true;
}
return false;
}
}
For creating folder
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Your Folder Name";
File folder = new File(path);
if (!folder.exists()) {
folder.mkdir();
}
also refer to this answer: https://stackoverflow.com/a/35471045/9060917
Update
public void download() {
for (MediaModel item : Items) {
if (item.isSelected) {
File file = new File(getFilesDir(),"Your directory name");
if(!file.exists()){
file.mkdir();
}
try{
Log.d("check", "download");
final String url = item.getFullDownloadURL();
BaseDownloadTask task = FileDownloader.getImpl().create(url);
task.setListener(mFileDownloadListener)
.setPath(file.getAbsolutePath(), true)
.setAutoRetryTimes(1)
.setCallbackProgressTimes(0)
.asInQueueTask()
.enqueue();
}catch (Exception e){
e.printStackTrace();
}
if (FileDownloader.getImpl().start(mFileDownloadListener, true)) {
item.setTaskId(task.getId());
item.setStatus(ItemStatus.DOWNLOADING);
Logging.e(TAG, "start download task: " + task.getId());
} else {
item.setTaskId(task.getId());
item.setStatus(ItemStatus.NORMAL);
Logging.e(TAG, "error download task: " + task.getId());
}
}
}
}
I hope you add these permissions in manifests
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Update
When saving a file to internal storage, you can acquire the appropriate directory as a File by calling method
getFilesDir()
File directory = context.getFilesDir();
File file = new File(directory, filename);
Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here's how to write some text to a file:
String filename = "myfile";
String fileContents = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContents.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
More reference
https://developer.android.com/training/data-storage/files#java
pass the URL of the image you want to download in this method.
/*--Download Image in Storage--*/
public void downloadImage(String URL) {
final Long reference;
downloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(URL);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle("AppName");
request.setDestinationInExternalPublicDir(String.format("%s/%s", Environment.getExternalStorageDirectory(),
getString(R.string.app_name)), "FileName.jpg");
Log.i("myi", "downloadImage: " + request.setDestinationInExternalPublicDir(String.format("%s/%s", Environment.getExternalStorageDirectory(),
getString(R.string.app_name)), "FileName.jpg"));
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
reference = downloadManager.enqueue(request);
Log.d("download", "Image Download : " + reference);
BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try {
Toast.makeText(this, "Image Downloaded Successfully ", Toast.LENGTH_LONG);
} catch (Exception e) {
}
}
};
getApplicationContext().registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
Add the required permissions to the AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Add requestLegacyExternalStorage for the application.
<application
android:requestLegacyExternalStorage="true">
</application>
Add the following snippet to the MainActivity.java
File f = new File(Environment.getExternalStorageDirectory(), "My folder");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
Files.createDirectory(Paths.get(f.getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
} else {
f.mkdir();
f.mkdirs();
Toast.makeText(getApplicationContext(), f.getPath(), Toast.LENGTH_LONG).show();
}
Now, the code to trigger the download would be something like:
String url="Here download Url paste";
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url.toString()));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.allowScanningByMediaScanner();
request.setDestinationInExternalPublicDir("/My folder", fileName);
downloadManager.enqueue(request);
I am getting image from server and display it in my application,and I download that image and downloading is working fine,but when I check my gallery image is not showing there,then in dev tools-Media Scanner I scan my SD card and again check my gallery and then image is showing..so how can I solve it..even I tried it Samsung phone,but with device i need to reboot my device...following is my snippet code...
public class bBusinessCardDL extends Activity{
String[] NAMES = new String[1];
String[] CurID = new String[1];
String[] Detail = new String[1];
String[] Photo = new String[1];
ListView listview;
String BCard;
ImageView image;
Button btnDownload;
ProgressDialog mProgressDialog;
private String Id;
private ImageView bcks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_bu_dl);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + "/mnt/sdcard/")));
bcks=(ImageView)findViewById(R.id.bck_from_bcard);
bcks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intss=new Intent(bBusinessCardDL.this,FirstPage.class);
startActivity(intss);
}
});
Id=this.getIntent().getStringExtra("userids");
System.out.println("checkd advertisement "+Id);
FillData();
btnDownload = (Button) findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDownloadAndSave();
Toast msgd = Toast.makeText(getBaseContext(),
"Business card Downloaded..!", Toast.LENGTH_LONG);
msgd.show();
}
});
}
public void mDownloadAndSave() {
File f = new File("/mnt/sdcard/" + Id
+ ".jpg");
//"/mnt/sdcard/"
InputStream is;
try {
is = new URL(BCard).openStream();
// Set up OutputStream to write data into image file.
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MediaScannerConnection.scanFile(this, new String[] { "ur_file_path" },
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 2048;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
public static String getJsonFromServer(String url) throws IOException {
BufferedReader inputStream = null;
URL jsonUrl = new URL(url);
URLConnection dc = jsonUrl.openConnection();
dc.setConnectTimeout(5000);
dc.setReadTimeout(5000);
inputStream = new BufferedReader(new InputStreamReader(
dc.getInputStream()));
// read the JSON results into a string
String jsonResult = inputStream.readLine();
return jsonResult;
}
static class ViewHolder {
TextView VHName;
ImageView VHPhoto;
int position;
}
public void FillData() {
String url = "";
url = "http://www.asdffsfd.com/web-service/b_card.php?user_id="
+ Id;
String jsonString;
jsonString = "";
try {
jsonString = getJsonFromServer(url);
} catch (IOException e) {
}
BCard = "";
try {
JSONArray earthquakes = new JSONArray(jsonString);
NAMES = new String[earthquakes.length()];
Photo = new String[earthquakes.length()];
for (int i = 0; i < earthquakes.length(); i++) {
JSONObject e = earthquakes.getJSONObject(i);
NAMES[i] = e.getString("b_card");
BCard = "http://" + e.getString("b_card");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
BCard = BCard.replace("\\", "");
BCard = BCard.replace(" ", "%20");
ImageView i = (ImageView) findViewById(R.id.BUCARD);
Log.d("Bcard", BCard);
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
BCard).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
after save the image, use below code for scanning file:
MediaScannerConnection.scanFile(this, new String[] { f.getAbsolutePath()},
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
I am working on an app in which I save image(s) to a directory but the Images wont show up in gallery until I restart the phone.
Here's My Code Snippet
public class SaveTask extends AsyncTask<String , String , String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl;
String myFileUrl1;
Bitmap bmImg = null;
File file ;
public SaveTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Downloading Image ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/mydownloaddir/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
Toast.makeText(SlideImageActivity.this, "Image Saved Succesfully to Folder 'mydownloaddir'", Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
}
What code should I use next to make the Images showup in gallery using medisscanner
I got something like this on here But unable to use it properly:
MediaScannerConnection.scanFile(ApplicationContext.context, new String[] { imageFile.getPath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.i(TAG, "Scanned " + path);
}
});
Please Help
Use
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
//but it only works on API <19
Second Method
private void scanFile(String path) {
MediaScannerConnection.scanFile(MainActivity.this,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
Call it like
scanFile(yourFile.getAbsolutePath());
Also see this Answer
I am trying to write an application that downloads files in the background. The code crashes when it tries to reenter doInBackground(). This happens when doing is set to false before returning. Code follows -
public class DownloadFile extends AsyncTask<String, Integer, String> {
private boolean doing;
private Activity activity;
private Intent intent;
private File beta;
private File alpha;
public DownloadFile(Activity act, Intent intent) {
this.activity = act;
this.intent = intent;
doing = false;
}
#Override
protected String doInBackground(String... sUrl) {
int fileCount = 0;
if (!download(sUrl[0] + "list.txt",
Environment.getExternalStorageDirectory() + "/alpha/list.txt")){
setDoing(false);
return "Download failed";//list.txt could not be downloaded. return error message.
}
fileCount++;
beta = new File(Environment.getExternalStorageDirectory() + "/beta/");
File betalist = new File(beta + "/list.txt");
alpha = new File(Environment.getExternalStorageDirectory() + "/alpha/");
File alphalist = new File(alpha + "/list.txt");
//verify that the file is changed.
if (alphalist.lastModified() == betalist.lastModified()// these two are
// never equal.
|| alphalist.length() == betalist.length()) { // better to check
// the length of
// the files.
setDoing(false);
return "Nothing to download.";
}
try {
FileReader inAlpha = new FileReader(alphalist);
BufferedReader br = new BufferedReader(inAlpha);
String s;
// read the name of each file in a loop
while ((s = br.readLine()) != null) {
// if(fileExistsInBeta(s)){
// copyFromBetaToAlpha(s);
// continue;
// }
// download the file.
//Url will truncate the trailing / so keep if statement as is.
if (!download(sUrl[0] + s,
Environment.getExternalStorageDirectory() + "/alpha/"
+ s)){
setDoing(false);
return "Failed at " + s;// the given file could not be downloaded. return error.
}
fileCount++;
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("Pankaj", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Pankaj", e.getMessage());
} catch (Exception e) {
Log.e("Pankaj", e.getMessage());
}
Log.d("Pankaj", "Download Done");
activity.overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
activity.finish();
Log.d("Pankaj", "MainActivity Killed");
// rename alpha to beta
deleteSubFolders(beta.toString());
beta.delete();
alpha.renameTo(beta);
if (!alpha.exists()) {
alpha.mkdir();
}
File upper = new File(alpha + "/upper/");
if (!upper.exists())
upper.mkdirs();
File lower = new File(alpha + "/lower/");
if (!lower.exists())
lower.mkdirs();
// ConfLoader.getInstance().reload();//to refresh the settings
// restart the activity
activity.overridePendingTransition(0, 0);
activity.startActivity(intent);
Log.d("Pankaj", "MainActivity restarted");
// now reset done status so we can start again.
setDoing(false);
return "Download finished.";// return the status for onPostExecute.
}
private void copyFromBetaToAlpha(String fileName) {
File beta=new File(Environment.getExternalStorageDirectory()+"/beta/"+fileName);
File alpha=new File(Environment.getExternalStorageDirectory()+"/alpha/"+fileName);
try {
FileInputStream fis=new FileInputStream(beta);
FileOutputStream fos=new FileOutputStream(alpha);
byte[] buf=new byte[1024];
int len;
while((len=fis.read(buf))>0){
fos.write(buf, 0, len);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
public boolean download(String url, String file) {
boolean successful = true;
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
conn.connect();
int filelen = conn.getContentLength();
File f = new File(file);
// skip download if lengths are same
// because the file has been downed fully.
if (f.exists() && filelen == f.length()) {
return successful;
}
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
FileOutputStream fos = new FileOutputStream(f);
while ((length = dis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
buffer = null;
dis.close();
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
successful = false;
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
successful = false;
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
successful = false;
}
return successful;
}
private void deleteSubFolders(String uri) {
File currentFolder = new File(uri);
File files[] = currentFolder.listFiles();
if (files == null) {
return;
}
for (File f : files) {
if (f.isDirectory()) {
deleteSubFolders(f.toString());
}
// no else, or you'll never get rid of this folder!
f.delete();
}
}
public static int getFilesCount(File file) {
File[] files = file.listFiles();
int count = 0;
for (File f : files)
if (f.isDirectory())
count += getFilesCount(f);
else
count++;
return count;
}
public boolean isDoing() {
return doing;
}
/**
* #param doing
*/
public void setDoing(boolean doing) {
this.doing = doing;
}
private boolean fileExistsInBeta(final String fileName){
boolean exists=false;
File beta=new File(Environment.getExternalStorageDirectory()+"/beta/"+fileName);
if(beta.exists()){
String[] ext=beta.getName().split(".");
String extName=ext[ext.length-1];
exists=(extName!="txt" && extName!="tmr" && extName!="conf");
}
return exists;
}
in the main activity -
public void run() {
if (!downloadFile.isDoing()) {
downloadFile.execute(ConfLoader.getInstance().getListUrl());
downloadFile.setDoing(true);
}
// change the delay so that it covers the time for download and
// doesn't overlap causing multiple downloads jamming the bandwidth.
h.postDelayed(this, 1000);//check after 60 sec.
}
in the onCreate() -
downloadFile = new DownloadFile(this, getIntent());
h = new Handler();
h.postDelayed(this, 1000);
Any help is appreciated. Thanks in advance.
EDIT:
The logcat error is Cannot execute task the task is already running.
Cannot execute task: Task has already been executed(A task can only be executed once).
EDIT:
Is it possible that the error is because I am trying to execute the asynchtask again in run(). Perhaps AsynchTask does not allow re-entry.
Try using this
1. First create a dialogue
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
The download async task
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
File root = android.os.Environment.getExternalStorageDirectory();
//
File dir = new File (root.getAbsolutePath()+"/Downl");
if(dir.exists()==false) {
dir.mkdirs();
}
File file = new File(dir, url.substring(url.lastIndexOf("/")+1)); //name of file
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Toast.makeText(DisplayActivity.this,"Successfully downloaded in phone memory.", Toast.LENGTH_SHORT).show();
}
}
Call the async new DownloadFileAsync().execute(url); //pass ur url
I created this AsyncTask to download an image and save it to the phone. If the image already exists is should just skip the code that downloads the image, yet every time it gets to f.exists() it's false even when the image has already been saved previously. Why would this be?
private class fanartDownloader extends AsyncTask<String, Integer, String> {
//First argument is image url and the second is the show id
#Override
protected String doInBackground(String... args) {
String fanartUrl = args[0];
fanartUrl = fanartUrl.substring(0, fanartUrl.length() - 4);
//Add proper end for small image
fanartUrl += SMALL_FANART_URL_END;
try {
String path = getApplicationContext().getFilesDir().toString();
path = path + "/" + args[1] + "/";
File f = new File(path, "fanart.jpg");
if (f.exists()) {
}
else {
f.mkdir();
URL url_value = new URL(fanartUrl);
Bitmap fanart = BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
FileOutputStream out = new FileOutputStream(path);
fanart.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
Now I've solved the issue with this slightly different iteration:
private class fanartDownloader extends AsyncTask<String, Integer, String> {
//First argument is image url and the second is the show id
#Override
protected String doInBackground(String... args) {
String fanartUrl = args[0];
fanartUrl = fanartUrl.substring(0, fanartUrl.length() - 4);
//Add proper end for small image
fanartUrl += SMALL_FANART_URL_END;
try {
String file = args[1] + "_" + "fanart.jpg";
String path = getApplicationContext().getFilesDir().toString();
path = path + "/" + file;
File f = new File(path);
if (f.exists()) {
}
else {
URL url_value = new URL(fanartUrl);
Bitmap fanart = BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
FileOutputStream out = getApplicationContext().openFileOutput(file, MODE_PRIVATE);
fanart.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
Does anyone know why the first AsyncTask wouldn't work?