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");
}
}
Related
I am creating an app in which I have to play audio from a number of URL links. At the first ever run of the app I am providing user the option of either downloading all of the audio files at once. Right now I am downloading each URL individually using Async Task. The problem with this approach is that since I have some 6000 url links for audio files it takes very long.
My questions is that is there any way I can quickly download audio files from these 6000 urls.
Below I am also providing the code that I am using for downloading each url.
public class DownloadAudio extends AsyncTask<Void, Void, String> {
public static final String TAG = DownloadAudio.class.getSimpleName();
ProgressDialog mProgressDialog;
Context context;
String stringUrl;
int index;
public DownloadAudio(Context context,String url, int randomNumber) {
this.context = context;
stringUrl=url;
index = randomNumber;
}
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context, "Please wait", "Download …");
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(stringUrl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String[] path = url.getPath().split("/");
int temp = path.length - 1;
String mp3 = path[temp];
int lengthOfFile = c.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+ "/MyAudioApp/" ;
Log.v(TAG, "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = mp3;
File outputFile = new File(file , fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return "done";
}
protected void onPostExecute(String result) {
if (result.equals("done")) {
mProgressDialog.dismiss();
}
}
}
Please any suggestions would be very helpful.
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.
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);
}
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..!
I am developing an application to download pdf file in sd card with the url entered in edittext , after clicking the submit button.
Button b = (Button)findViewById(R.id.button1);
final EditText ed = (EditText)findViewById(R.id.editText1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String URL = ed.getText().toString();
WebView web1 =(WebView)findViewById(R.id.webview);
web1.getSettings().setJavaScriptEnabled(true);
web1.loadUrl(URL);
}
});
Below code may help you -
public class DownloaderThread extends Thread
{
// constants
private static final int DOWNLOAD_BUFFER_SIZE = 4096;
// instance variables
private AndroidFileDownloader parentActivity;
private String downloadUrl;
/**
* Instantiates a new DownloaderThread object.
* #param parentActivity Reference to AndroidFileDownloader activity.
* #param inUrl String representing the URL of the file to be downloaded.
*/
public DownloaderThread(AndroidFileDownloader inParentActivity, String inUrl)
{
downloadUrl = "";
if(inUrl != null)
{
downloadUrl = inUrl;
}
parentActivity = inParentActivity;
}
/**
* Connects to the URL of the file, begins the download, and notifies the
* AndroidFileDownloader activity of changes in state. Writes the file to
* the root of the SD card.
*/
#Override
public void run()
{
URL url;
URLConnection conn;
int fileSize, lastSlash;
String fileName;
BufferedInputStream inStream;
BufferedOutputStream outStream;
File outFile;
FileOutputStream fileStream;
Message msg;
// we're going to connect now
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_CONNECTING_STARTED,
0, 0, downloadUrl);
parentActivity.activityHandler.sendMessage(msg);
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";
}
// notify download start
int fileSizeInKB = fileSize / 1024;
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_DOWNLOAD_STARTED,
fileSizeInKB, 0, fileName);
parentActivity.activityHandler.sendMessage(msg);
// start download
inStream = new BufferedInputStream(conn.getInputStream());
outFile = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
fileStream = new FileOutputStream(outFile);
outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
int bytesRead = 0, totalRead = 0;
while(!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0)
{
outStream.write(data, 0, bytesRead);
// update progress bar
totalRead += bytesRead;
int totalReadInKB = totalRead / 1024;
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_UPDATE_PROGRESS_BAR,
totalReadInKB, 0);
parentActivity.activityHandler.sendMessage(msg);
}
outStream.close();
fileStream.close();
inStream.close();
if(isInterrupted())
{
// the download was canceled, so let's delete the partially downloaded file
outFile.delete();
}
else
{
// notify completion
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_DOWNLOAD_COMPLETE);
parentActivity.activityHandler.sendMessage(msg);
}
}
catch(MalformedURLException e)
{
String errMsg = parentActivity.getString(R.string.error_message_bad_url);
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
0, 0, errMsg);
parentActivity.activityHandler.sendMessage(msg);
}
catch(FileNotFoundException e)
{
String errMsg = parentActivity.getString(R.string.error_message_file_not_found);
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
0, 0, errMsg);
parentActivity.activityHandler.sendMessage(msg);
}
catch(Exception e)
{
String errMsg = parentActivity.getString(R.string.error_message_general);
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
0, 0, errMsg);
parentActivity.activityHandler.sendMessage(msg);
}
}
}
Above code extracted from this Existing project. Don't forget to give the required permission for Internet
Here urlToDownload is your edittext's text, Write Below Method into your button click event to Download pdf file.
public void downloadPdfContent(String urlToDownload){
try {
String fileName="xyz";
String fileExtension=".pdf";
//download pdf file.
URL url = new URL(urlToDownload);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName+fileExtension);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("--pdf downloaded--ok--"+urlToDownload);
} catch (Exception e) {
e.printStackTrace();
}
}
and give write_external_storage permission into your application manifest file.