Download and Share in Whatsapp - java

Video gets shared before the complete video gets downloaded.I am using the following code to download a video from the server and share in whatsapp:
AlertDialog.Builder alert1 = new AlertDialog.Builder(this);
alert1.setTitle("Share the file to Whatsapp");
alert1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
DownloadFile1 downloadFile1 = new DownloadFile1();
downloadFile1.videoToDownload = video_url;
String value = "test.mp4";
downloadFile1.fileName = value;
downloadFile1.execute();
try {
shareVideoWhatsApp(value);
} catch (IOException e) {
e.printStackTrace();
}
}
});
alert1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert1.show();
The Download part is implemented in async task.The problem is sharing to the whatsapp takes place before the complete video file gets downloaded.
Download code:
class DownloadFile1 extends AsyncTask<String, Integer, String> {
ProgressDialog bar;
public String videoToDownload;
public String fileName;
/**
* Before starting background thread
* Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... params) {
int count;
try {
mp4load(videoToDownload);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
public void mp4load(String urling) {
try {
System.out.println("Downloading");
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
// String downloadsPath = Environment.getExternalStoragePublicDirectory();
File SDCardRoot = Environment.getExternalStorageDirectory();
File outputFile = new File(SDCardRoot, fileName);
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();
InputStream is = con.getInputStream();
int fileLength = con.getContentLength();
long total = 0;
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
total += len1;
pDialog.setProgress((int) (total * 100 / fileLength));
}
fos.close();
is.close();
System.out.println("Downloaded");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
How to solve this problem?

Call shareVideoWhatsApp(value); inside onPostExecute()

Related

Trouble downloading photos

I wrote a program that
Download the photo from the url...
But I have a problem...
Some photos are downloaded.
And there is no problem.
But some of the pictures are not downloadable incompletely :(
and in the file manager I look at
it is broken
Can you help?
my code is:
public class DownloadFileFromURL_img extends AsyncTask {
private viewHolderPost holderPOST;
public DownloadFileFromURL_img(viewHolderPost holderPOST) {
Log.d(TAG, "DownloadFileFromURL_img: ");
this.holderPOST = holderPOST;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
File file = new File(Environment.getExternalStorageDirectory(), "98Diha/img");
if (!file.exists()) {
if (!file.mkdirs()) {
file.createNewFile();
}
}
InputStream input = null;
int response = -1;
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
if (!(conection instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conection;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
input = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
int lenghtOfFile = conection.getContentLength();
input = new BufferedInputStream(url.openStream());
String imgS[] = f_url[0].split("/");
String name = imgS[imgS.length - 1];
String path = Environment
.getExternalStorageDirectory().toString()
+ "/98diha/img/" + name;
File filePath = new File(path);
if (!filePath.exists()) {
OutputStream output = new FileOutputStream(path);
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();
} else {
SSToast(context, "Exist!");
holderPOST.dowload_img.setVisibility(View.GONE);
holderPOST.setWallpaper.setVisibility(View.VISIBLE);
holderPOST.setWallpaper.setText(context.getString(R.string.set_wp));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holderPOST.setWallpaper.setTextColor(ContextCompat.getColor(context, R.color.Teal_400));
} else {
holderPOST.setWallpaper.setTextColor(context.getResources().getColor(R.color.Teal_400));
}
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
holderPOST.dowload_img.setVisibility(View.GONE);
holderPOST.setWallpaper.setVisibility(View.VISIBLE);
holderPOST.setWallpaper.setText(context.getString(R.string.dowloading));
}
/**
* After completing background task Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
holderPOST.setWallpaper.setText(context.getString(R.string.set_wp));
holderPOST.setWallpaper.setTextColor(context.getResources().getColor(R.color.Teal_400));
Log.d(TAG, "onPostExecute: ");
}
}
Instead of using AsyncTask to download images from URL. You can use libraries such as Glide or Picasso to do it quickly just in one line. But if you don't want to use libraries than you could use DownloadManager to download it and save it in a file. You can check this tutorial or other tutorials on the web for the implementation of DownloadManager.

How to Update My Android app From My Server?

Please help me to add update code to my app to be update from my server thank you
nothing worked from net , i need complete guide
You can't install your app without users permission and root access but you can download your applications new version from server then ask users for install. Here is an example:
{
PackageManager manager = context.getPackageManager();
try {
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
version = info.versionName;
if (newversion.replace(".", "") < version.replace(".", "")) {
new DownloadFileFromURL().execute("http://exampl.com/Content/files/example.apk");
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = onCreateDialog();
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
if (file.exists()) {
file.delete();
}
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
pDialog.setMax(lenghtOfFile / 1024);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/example.apk");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(total / 1024 + "");
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception ignored) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
//finish() or whatever you want
}
}
}

updating horizontal ProgressDialog using Handler, while loading an image from the web

Is it possible to update the horizontal (determinate) ProgressDialog using Handler (I deliberately don't want to use AsyncTask), while loading an image from the web? and if so, how do I do that?
this is the try block:
URL url = new URL(link);
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
if(httpCon.getResponseCode()!=200) return;
InputStream inputStream = httpCon.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
Yes, it's possible. You can pass data via Message class and get them in handleMessage(Message msg) method of Handler for example this way (msg.arg1 - downloaded bytes, msg.arg2 - total bytes to download):
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Downloading Image ...");
progressDialog.setMessage("Download in progress ...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgress(0);
progressDialog.setMax(100);
progressDialog.show();
final Handler downloadProgressHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.setProgress(100 * msg.arg1 / msg.arg2);
if (progressDialog.getProgress() == progressDialog.getMax()) {
progressDialog.dismiss();
}
}
};
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL("<your_url>");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
ByteArrayOutputStream receivedBytesStream = new ByteArrayOutputStream();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0 ) {
receivedBytesStream.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Message msg = new Message();
msg.arg1 = downloadedSize;
msg.arg2 = totalSize;
downloadProgressHandler.sendMessage(msg);
}
receivedBytesStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Or if You don't want to sent data via msg.arg1 and msg.arg2 You can create custom object and add it to message like that msg.obj = new YourCustomObjectClass() // or any other object. And You can get it in handleMessage(Message msg) method like this: YourCustomObjectClass obj = (YourCustomObjectClass) msg.obj;
Instead of directly decoding the InputStream to Bitmap, Download the file to any path in your device. And from the onProgressUpdate method of the asynchtask, you can update the progress. After the file is download open the file and set to imageview.
Eg with Asynchtask
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
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);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
You can call this with
new DownloadFileFromURL().execute(link);

Updating ProgressBar when downloading using FTPClient

I'm using Apache's FTPClient to upload files to my server (images from the gallery if it matters)
I'm having a small and pretty insignificant problem, but I would still like to solve it.
The problem is that the bar is filled and reaches 100% before the upload actually completes, causing the dialog to show 100% for an extra 2-3 seconds on small files (and could be a lot more on files weighing several MBs).
I'm guessing it's because of the conversion from long to int, but that's just a guess.
Here's the code:
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(UploadActivity.this);
dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
uploadImage.cancel(true);
}
});
dialog.setMessage("Uploading...\nPlease Wait.");
dialog.setIndeterminate(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setCancelable(false);
dialog.setMax((int)(file.length()/1024));
dialog.setProgressNumberFormat ("%1dKB/%2dKB");
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
CopyStreamAdapter streamListener = new CopyStreamAdapter() {
#Override // THIS PART IS RESPONSIBLE FOR UPDATING THE PROGRESS
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
int percent = (int) (totalBytesTransferred * 100 / file.length());
publishProgress(percent);
}
};
String name = null;
ftp.setCopyStreamListener(streamListener);
FileInputStream fis = null;
try {
String extension = "";
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
if (i > p) {
extension = fileName.substring(i + 1);
}
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy-hhmmss-SSS");
name = String.format("File-%s.%s", sdf.format(new Date()), extension);
ftp.connect(FTP_SERVER);
ftp.enterLocalPassiveMode();
ftp.login(ftpUser, ftpPassword);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
fis = new FileInputStream(file);
if (!ftp.storeFile(name, fis)) {
showToast("Failed uploading");
return null;
}
ftp.logout();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return name;
}
#Override
protected void onProgressUpdate(Integer... values) {
dialog.setProgress(values[0]);
}
Thanks!

Android programming (Trying to download a file to system directory)

Dear stackOverflow members i have recently started a new project called "RootBox" and it is an app that needs "su" perms and i have successfully allowed the app "su" or "root" access and im trying to download and replace a system file in "/system/media and i have setup my downloader but the download progress dialog pops up and closes which im guessing is the result of the file not being able to written to the system directory and i have Re-mounted the system as r-w before starting the download an i have searched all over the internet and was unable to find help thats why i have come here.
This is the activity executing the download
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bootmation);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
RootTools.remount("/system/", "rw");
}
});
}
private void startDownload() {
String url = "http://www.filehosting.org/file/details/430746/bootanimation.zip";
new DownloadFileAsync().execute(url);
}
#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;
}
}
class DownloadFileAsync extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
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("/system/media/bootanimation.zip");
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]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
for this u have to allow in manifest for permission for writing as
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
URL u = new URL(fUrls[i]);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();

Categories