I want to download MP3 audio and images from server.File is downloaded but not goes into sd card folder.Below my code is correct or not or something wrong in downloading on store into sd card folder.How to work with download media files and save into sd card folder.Thanks in advanced.
Here is my MP3 download code.
public void DownLoadAudioFile(final String mp3Url , final String strImageName) {
new AsyncTask<String, String, String>()
{
#Override
protected String doInBackground(String... f_url) {
int count;
try
{
f_url[0] = mp3Url;
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Get Music file length
int lenghtOfFile = conection.getContentLength();
Log.e("lenghtOfFile "," = " + lenghtOfFile);
// input stream to read file - with 8k buffer
if(lenghtOfFile > 0)
{
InputStream input = new BufferedInputStream(url.openStream(),10*1024);
// Output stream to write file in SD card
newFolder = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "classnkk_audio");
File file = new File(newFolder, strImageName);
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();
Log.e("Audio Files", "DownLoad ans save in SD card Fully !!!");
Log.e("======================"," DownloadMusicfromInternet ======================");
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
}.execute();
}
and here is my image download code
void download_PngFile(String fileUrl, String ImageName) {
try {
URL ImgUrl = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) ImgUrl.openConnection();
conn.connect();
int lenghtOfImage_File = conn.getContentLength();
Log.e("lenghtOfImage_File "," = "+lenghtOfImage_File);
if(lenghtOfImage_File > 0)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap imagenObtenida = BitmapFactory.decodeStream(conn.getInputStream(), null, options);
File file = new File(newFolder, ImageName);
if (file.exists()) file.delete();
try
{
FileOutputStream out = new FileOutputStream(file);
imagenObtenida.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
int imagenObtenidaW = imagenObtenida.getWidth();
int imagenObtenidaH = imagenObtenida.getHeight();
Log.e("imagenObtenidaW " ," = +" + imagenObtenidaW + " imagenObtenidaH = " + imagenObtenidaH);
} catch (Exception e) {
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (imageName.endsWith(mp3_Pattern))
{
str_DownLoadUrl = namespace + "/DownloadFile/FileName/"+imageName;
DownLoadAudioFile(str_DownLoadUrl ,imageName);
strDownLoadStatus = "1";
dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
}
if (imageName.endsWith(png_Pattern) || imageName.endsWith(jpg_pattern) || imageName.endsWith(bmp_pattern) || imageName.endsWith(gif_pattern) || imageName.endsWith(jpeg_pattern))
{
str_DownLoadUrl = namespace + "/DownloadFile/FileName/" + imageName;
download_PngFile(str_DownLoadUrl,imageName);
strDownLoadStatus = "1";
dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
}
Related
I have used a videoview to play the video from raw folder locally, but now im trying to download a list of videos first on sdcard and after to play it to media player. Here is my videoview.
public class MainActivity extends Activity {
/* Full Screen Mode-Sticky */
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
View decorView = getWindow().getDecorView();
if (hasFocus) {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);}
}
public void downloadVideoFile(String url, String dest_file_name) {
try {
URL domain = new URL("http://192.168.0.22");
String video_folder = "video";
String sdcard_path = Environment.getExternalStorageDirectory().getAbsolutePath();
String dest_video_path = sdcard_path + File.separator + video_folder + File.separator + dest_file_name;
File dest_file = new File(dest_video_path);
URL u = new URL(domain + "/files/video/");
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return;
} catch (IOException e) {
return;
}
}
private VideoView myVideo1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.activity_main);
String video_folder = "myvideos";
String sdcard_path = Environment.getExternalStorageDirectory().getAbsolutePath();
File fvideo_path = new File(sdcard_path + File.separator + video_folder);
File videolist[] = fvideo_path.listFiles();
String play_path = videolist[0].getAbsolutePath();
myVideo1=(VideoView)findViewById(R.id.myvideoview);
myVideo1.setVideoPath(play_path);
myVideo1.start();
myVideo1.requestFocus();
myVideo1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
}
}
Step 1: build video list from a specific path on sdcard
String video_folder = "myvideos";
String sdcard_path = Environment.getExternalStorageDirectory();
File fvideo_path = new File(sdcard_path + File.separator + video_folder);
File videolist[] = fvideo_path.listFiles();
Step 2: play any video in list by index
//you can next or prev index from 0 - list lenght;
String play_path = videolist[0].getAbsolutePath();
Step 3: you set play_path to media player
myVideo1.setVideoPath(play_path);
myVideo1.start();
myVideo1.requestFocus();
Example code to download file from server:
public void downloadVideoFile(String url, String dest_file_name) {
try {
String video_folder = "myvideos";
String sdcard_path = nvironment.getExternalStorageDirectory();
String dest_video_path = sdcard_path + File.separator + video_folder + File.separator + dest_file_name;
File dest_file = new File(dest_video_path);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return;
} catch (IOException e) {
return;
}
}
I am using below code to get download videos from Server
class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onCancelled() {
super.onCancelled();
}
/**
* Downloading file in background thread
* */
#Override
protected Integer doInBackground(Object... params) {
try {
URL url = new URL((String) params[1]);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
// Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
File download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
byte data[] = new byte[1024];
long total = 0;
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return 0;
}
protected void onPostExecute(String file_url) {
// Do after downloaded file
}
}
I want to download all mp3 files from server one by one and save into sd card folder. I have no any errors or exception but mp3 does not downloaded and does not show in SD card. Can someone help how to solve this issue.Here is my code.
if (imageName.endsWith(mp3_Pattern))
{
str_DownLoadUrl = namespace + "/DownloadFile/FileName/" + imageName;
Log.e("######### ", "str_DownLoadUrl = " + str_DownLoadUrl);
download_Mp3File(str_DownLoadUrl);
strDownLoadStatus = "1";
dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
}
void download_Mp3File(final String fileUrl) {
new AsyncTask<String, Integer, String>()
{
#Override
protected String doInBackground(String... arg0)
{
int count;
File file = new File(newFolder, System.currentTimeMillis() + imageName);
try
{
URL url = new URL(fileUrl);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
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;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
}.execute();
}
place a breakpoint in inputstream object to see is there any stream. then debug output stream to see the results.
How to attach image in email? I am able to attach text in email but not attach image properly,
so only send the Text but not send the Image.
Problem with,
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
so Control direct put in catch statement after urlConnection.connect();, Image not save in SDACRD.so not attach the image. How to do?
My code in Below,
urlShare = "http://example.com/share.php?id="+ strId;
public class sendImageThroughEmail extends AsyncTask<Void, Void, Void> {
/** Hashmap for Share */
ArrayList<HashMap<String, String>> arrDataList = null;
String strMessage = null, strImageLocator = null;
ProgressDialog progressDialog;
String filePath, strImageName;
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(false);
progressDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
arrDataList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONFunctions.getJSONfromURL(urlShare);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
strMessage = jsonobject.getString(TAG_MESSAGE);
strImageLocator = jsonobject.getString(TAG_DATA);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
URL url = new URL(strImageLocator);
//URL url = new URL("http://example.com/upload/images (8).jpg");
strImageName = strImageLocator.substring(strImageLocator
.lastIndexOf('/') + 1);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = strImageName;
Log.i("Local File:", filename);
File file = new File(SDCardRoot, filename);
if (file.createNewFile()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:", "downloadSize:" + downloadedSize
+ "totalSize:" + totalSize);
}
fileOutput.close();
if (downloadedSize == totalSize) {
filePath = file.getPath();
}
} catch (Exception e) {
e.printStackTrace();
}
Intent email = new Intent(Intent.ACTION_SEND);
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = strImageName;
File file = new File(SDCardRoot, filename);
Uri markPath = Uri.fromFile(file);
email.putExtra(Intent.EXTRA_STREAM, markPath);
email.putExtra(Intent.EXTRA_SUBJECT, "Share");
email.putExtra(Intent.EXTRA_TEXT, strMessage);
email.setType("image/png");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email Client"));
}
};
My ImageLocator Like this,
1) http://example.com/upload/images (8).jpg
2) http://example.com/upload/11_2134_232222_33.png
Please Guide me.
Thanks in advance...
Edit following strings in your email intent:
//...
email.setType("image/jpeg");
email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+file.getAbsolutePath()));
//...
For more info you can see this answer.
EDIT
To download file use this code:
private final static String SD_CARD = Environment
.getExternalStorageDirectory().getAbsolutePath();
private final static String PNG = ".png";
private final static String APP_FOLDER = "Folder Name";
/**
* Checking if the SD card is mounted
*
* #return SD card existence
*/
public static boolean isSdPresent()
{
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
* Downloads image file onto SD card in specific folder
*
* #param fileUrl URL for downloading of file
* #throws IOException
*/
private static void downloadImage(String fileUrl) throws IOException
{
if (isSdPresent())
{
if (fileUrl.length() > 0)
{
URL url = new URL(fileUrl);
InputStream input = url.openStream();
File folder = new File(SD_CARD, APP_FOLDER);
if (!folder.exists())
folder.mkdir();
OutputStream output = new FileOutputStream(new File(folder,
fileUrl.substring(fileUrl.indexOf("=") + 1, fileUrl.length())
+ PNG));
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
{
output.write(buffer, 0, bytesRead);
}
output.close();
input.close();
}
}
else
{
if (BuildConfig.DEBUG)
Log.e("SD card", "not mounted");
}
}
This is my doInBackground method:
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
HttpURLConnection conection = null;
BufferedOutputStream bout = null;
FileOutputStream fos = null;
int downloaded = 0;
try {
URL url = new URL(sUrl[0]);
conection = (HttpURLConnection)url.openConnection();
int lenghtOfFile = conection.getContentLength();
if(STATUS) {
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/myapp.apk");
if (file.exists()) {
downloaded = (int) file.length();
conection.setRequestProperty("Range", "bytes=" + (file.length()) + "-");
}
}
else {
conection.setRequestProperty("Range", "bytes=" + downloaded + "-");
}
conection.setDoInput(true);
conection.setDoOutput(true);
conection.connect();
input = new BufferedInputStream(url.openStream(), 8192);
fos=(downloaded==0)? new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/myapp.apk"): new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/myapp.apk",true);
bout = new BufferedOutputStream(fos, 1024);
byte data[] = new byte[1024];
long total = 0;
int count = 0;
while ((count = input.read(data, 0, 1024)) >= 0) {
if (isCancelled()) {
input.close();
return null;
}
bout.write(data, 0, count);
downloaded += count;
publishProgress((int)(downloaded * 100/ lenghtOfFile) );
total += count;
}
bout.flush();
input.close();
fos.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
if (fos != null)
fos.close();
if (bout != null)
bout.close();
} catch (IOException ignored) {
}
if (conection != null)
conection = null;
}
return null;
}
I start download task with this code (resume flag is false -> STATUS = FALSE):
dt = new DownloadTask(DownloadsActivity.this, false);
dt.execute("myurl.something.apk");
then when downloaded completely I launch apk file and all thing work correctly and apk installed correctly. But when pause my download with this code:
dt.cancel(true);
and then resume it with this code (resume flag is true-> STATUS = TRUE):
dt = new DownloadTask(DownloadsActivity.this, true);
dt.execute("myurl.something.apk");
This time apk size is equal to last downloaded before pause + apk total size, therefore my apk file is corrupted. Which means connection.setRequestProperty() not working for me. What is my code problem? Thanks in advance.
I want to download different types of file and there is possibility of link like
https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRpDmM-KiKgR-wcFtJnXUYVua-2409t5z7pjqski5wQ9pYZfOJG7nklFnc
where I don't know the file name, type and any of the description. then How to get those information. so I make that file name as default?
Thank You.
You have to use async task for downloading file
Call it with
String Your_Url = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRpDmM-KiKgR-wcFtJnXUYVua-2409t5z7pjqski5wQ9pYZfOJG7nklFnc";
new downloadProcess(Your_Url, Your_Context).execute();
public downLoadProcess(String Url , Context context)
{
context.Url = Url ;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayList<String> result)
{
super.onPostExecute(result);
}
#Override
protected ArrayList<String> doInBackground(Void... Params)
{
ArrayList<String> Data = new ArrayList<String>();
boolean flag = false;
URL url;
URLConnection conn;
int fileSize, lastSlash;
String fileName, path = null;
BufferedInputStream inStream;
BufferedOutputStream outStream;
File outFile;
FileOutputStream fileStream;
WebServiceMethods objWSMethod = new WebServiceMethods();
String downloadUrl = Url ;
try
{
url = new URL(downloadUrl);
conn = url.openConnection();
conn.setUseCaches(false);
fileSize = conn.getContentLength();
// get the filename
lastSlash = url.toString().lastIndexOf('/');
fileName = "file.bin";
if(lastSlash >=0)
{
fileName = url.toString().substring(lastSlash + 1);
}
if(fileName.equals(""))
{
fileName = "file.bin";
}
int DOWNLOAD_BUFFER_SIZE = fileSize;
// start download
inStream = new BufferedInputStream(conn.getInputStream());
path = Environment.getExternalStorageDirectory().toString() ;
File file = new File(path + "/Download");
file.mkdir();
path = Environment.getExternalStorageDirectory() + "/Download/" + fileName;
outFile = new File(path);
fileStream = new FileOutputStream(outFile);
outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
int bytesRead = 0, totalRead = 0;
while((bytesRead = inStream.read(data, 0, data.length)) >= 0)
{
if(Check_your_Internet_is_on?)
{
outStream.write(data, 0, bytesRead);
totalRead += bytesRead;
flag = true;
}
else
{
flag = outFile.delete();
flag = false;
}
}
outStream.close();
fileStream.close();
inStream.close();
}
catch(MalformedURLException e)
{
}
catch(FileNotFoundException e)
{
}
catch(Exception e)
{
}
return Data;
}
}
Hope it will help you..!