Download mp4 from server and save it to sdcard - java

I simply want to download mp4 or .3gp files from server to android device. I have tried multiple ways to achieve but in some cases it gives IOException and some time give ProtocolException
First Method to download Video using DownloadVideoTask.class
public class DownloadVideoTask extends AsyncTask<String, Integer, Boolean>
{
String nameOfSong;
Context context;
Boolean flage = true;
ProgressDialog progressDialog2;
#SuppressLint("InlinedApi")
public DownloadVideoTask(Context context,String trackTitle)
{
this.context = context;
nameOfSong = trackTitle;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
progressDialog2 = new ProgressDialog(context, AlertDialog.THEME_HOLO_LIGHT);
}
else
{
progressDialog2 = new ProgressDialog(context);
}
progressDialog2.setIndeterminate(false);
progressDialog2.setMax(100);
progressDialog2.setTitle("Please wait...");
try
{
progressDialog2.setMessage("Downloding.. " + nameOfSong.substring(0, 20));
}
catch (Exception e)
{
progressDialog2.setMessage("Downloding Song...." );
}
progressDialog2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog2.show();
}
#Override
protected Boolean doInBackground(String... params)
{
/* String trackTitle = params[0];
nameOfSong = trackTitle;
*/
String trackUrl = params[0];
try
{
File root;// = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
root = Environment.getExternalStorageDirectory();
}
else
{
root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
File dir = new File(root.getAbsolutePath() + "/XarDownloder");
if (dir.exists() == false)
{
dir.mkdirs();
}
URL url = new URL(trackUrl);
File file = new File(dir, nameOfSong);
URLConnection urlConnection = url.openConnection();
int fileLength = urlConnection.getContentLength();//ye statement inputStream k bad likhi thi
InputStream inputStream = urlConnection.getInputStream();
OutputStream outputStream = new FileOutputStream(
root.getAbsolutePath() + "/XarDownloder/" + nameOfSong
+ ".mp4");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1)
{
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
try
{
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
}
else
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC))));
}
context.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
.fromFile(file)));
}
catch (Exception e)
{
}
return true;
}
catch (IOException e)
{
flage = false;
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
if (result)
{
try
{
Toast.makeText(context,
nameOfSong.substring(0, 30) + "Downloaded...",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(context,
"Song Downloaded...",
Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(context, "Sorry, song is not downloadable",
Toast.LENGTH_LONG).show();
}
progressDialog2.dismiss();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
progressDialog2.setProgress(values[0]);
}
}
Second Method using DownloadFile
public class DownloadFile extends AsyncTask<String, Integer, String>
{
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
public DownloadFile()
{
}
#Override
protected String doInBackground(String... params)
{
int count;
try
{
mp4load(videoToDownload);
}
catch (Exception e)
{
// TODO: handle exception
}
/*try
{
URL url = new URL(videoToDownload);
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("/sdcard/xarwere/firstdownload.mp4");
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)
{
e.printStackTrace();
}*/
return null;
}
public void mp4load(String urling)
{
try
{
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
//Log.v(LOG_TAG, "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "test.mp4";
File outputFile = new File(file, fileName);
if (!outputFile.exists())
{
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();//my doctory
InputStream is = con.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 (MalformedURLException e)
{
e.printStackTrace();
}
catch (ProtocolException e)
{
e.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
Where videoToDownload in DownloadFile.class is the URLi want to download. but at inputStream it gives exception.
And I call these AsyncTask like
new DownloadFile().execute();
new DownloadVideoTask(TestingActivity.this, "nameofsong").execute("http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4");

I slighthly modified your code, but it downloads the file well. Did you add the internet permission?
public class DownloadFile extends AsyncTask<String, Integer, String> {
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
#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 {
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String fileName = "test.mp4";
File outputFile = new File(downloadsPath, fileName);
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();
InputStream is = con.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();
}
}
}

Related

It saves empty when saving apk file to device

I set up HttpServer in Java. When the apk file is sent by the client, I want to save it to the device. However, when using the code below, it saves to the device in a empty way.
(0 bytes when I say empty) Where am I doing wrong?
Note:
In the log in the code, I tested that the apk file was sent properly by the client. Values ​​such as size, byte, apk name are coming in properly.
class postApkFile implements HttpHandler {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void handle(HttpExchange he) throws IOException {
he.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
if (he.getRequestMethod().equalsIgnoreCase("OPTIONS")) {
he.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
he.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
he.sendResponseHeaders(204, -1);
return;
}
DiskFileItemFactory d = new DiskFileItemFactory();
try {
ServletFileUpload up = new ServletFileUpload(d);
List<FileItem> result = up.parseRequest(new RequestContext() {
#Override
public String getCharacterEncoding() {
return "UTF-8";
}
#Override
public int getContentLength() {
return 0; //tested to work with 0 as return
}
#Override
public String getContentType() {
return he.getRequestHeaders().getFirst("Content-type");
}
#Override
public InputStream getInputStream() throws IOException {
return he.getRequestBody();
}
});
InputStream inputStream = he.getRequestBody();
String configXmlFilePath = Environment.getExternalStorageDirectory() + "test/configXml/test.apk";
File apkFile = new File(configXmlFilePath);
FileOutputStream outputStream = new FileOutputStream(apkFile);
he.getResponseHeaders().add("Content-type", "text/plain");
he.sendResponseHeaders(200, 0);
OutputStream os = he.getResponseBody();
byte[] buffer = new byte[1024];
Log.i(HttpServerManager.getHttpServerManager().TAG, "buffer1");
int bytesRead;
Log.i(HttpServerManager.getHttpServerManager().TAG, "bufferread");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
for (FileItem fi : result) {
os.write(fi.getName().getBytes());
os.write("\r\n".getBytes());
Log.i(HttpServerManager.getHttpServerManager().TAG, "File-Item: " + fi.getFieldName() + " = " + fi.getName() + " get size " + fi.getSize() );
}
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Writing the while block after the for loop solved my problem.
class postApkFile implements HttpHandler {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void handle(HttpExchange he) throws IOException {
he.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
if (he.getRequestMethod().equalsIgnoreCase("OPTIONS")) {
he.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
he.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
he.sendResponseHeaders(204, -1);
return;
}
DiskFileItemFactory d = new DiskFileItemFactory();
try {
ServletFileUpload up = new ServletFileUpload(d);
List<FileItem> result = up.parseRequest(new RequestContext() {
#Override
public String getCharacterEncoding() {
return "UTF-8";
}
#Override
public int getContentLength() {
return 0; //tested to work with 0 as return
}
#Override
public String getContentType() {
return he.getRequestHeaders().getFirst("Content-type");
}
#Override
public InputStream getInputStream() throws IOException {
return he.getRequestBody();
}
});
String configXmlFilePath = Environment.getExternalStorageDirectory() + "test/configXml/test.apk";
File apkFile = new File(configXmlFilePath);
he.getResponseHeaders().add("Content-type", "text/plain");
he.sendResponseHeaders(200, 0);
OutputStream os = he.getResponseBody();
InputStream inputStream = null;
for (FileItem fi : result) {
os.write(fi.getName().getBytes());
os.write("\r\n".getBytes());
inputStream = fi.getInputStream();
Log.i(HttpServerManager.getHttpServerManager().TAG, "File-Item: " + fi.getFieldName() + " = " + fi.getName());
}
FileOutputStream outputStream = new FileOutputStream(apkFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
Log.i(HttpServerManager.getHttpServerManager().TAG, "os.Close ve outputStream.close");
os.close();
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

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.

Android how to download zip file using soap liabrary

I want to download zip file from server by using ksoap liabry.I am getting data in base64 please give solution that how to convert base64 and save it as zip file
byte[] bytes;
byte[] data = result.getBytes("UTF-8");
File outputFile = new File(mediaStorageDir.getAbsolutePath(), + "filename.zip");
new FileOutputStream(outputFile);
bytes = Base64.decode(data, Base64.DEFAULT);
File filepath = new File(Environment.getExternalStorageDirectory(), "Folder/" + "filename.zip");
OutputStream pdffos = new FileOutputStream(filepath);
pdffos.write(bytes);
pdffos.flush();
pdffos.close();
This Code help me to downlad apk and store to sd card.
This may help you also..
public class SaveInBackground extends AsyncTask<String,Integer,String> {
View v;
OutputValue ov;
Boolean isError= false;
public SaveInBackground(View v,OutputValue ov){
this.v = v;
this.ov = ov;
}
#Override
protected void onPreExecute(){
Message.setText("Downloading...");
isToLoop =true;
new Thread(new Runnable() {
#Override
public void run() {
while (isToLoop) {
SystemClock.sleep(500);
runOnUiThread(new Runnable() {
#Override
public void run() {
int count = bar.getProgress() + 1;
bar.setProgress(count);
}
});
if(isToLoop)
break;
}
}
}).start();
}
#Override
protected void onProgressUpdate(Integer... values) {
bar.setProgress(values[0]);
}
#Override
protected String doInBackground(String... params) {InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(Globle.Infosoft_serverLink.replace("/Service.asmx/","")+ov.url);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
isError = true;
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
//publishProgress(80);
String path = Environment.getExternalStorageDirectory()+"/"+ov.Name+".apk";
output = new FileOutputStream(path );
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
return path;
}
catch (Exception e) {
isError =true;
Snackbar.make(v,"Error while accessing storage.",Snackbar.LENGTH_LONG).show();
return null;
}finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
}
#Override
protected void onPostExecute(String result){
if(!isError) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(result)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Message.setText("Downloaded");
reset(v);
}
}

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
}
}
}

For loop does not doing my async task completely

Im doing Download All of files. What I did was for loop, unfortunately my for loop does not finish my async task it continues doing all the loop regardless if it finished the first file that was downloading. Help please.
Here is my for loop
for (int i = 0; i < id.length; i++) {
Element e = (Element)nodes.item(i);
id[i] = ""+CategoriesXMLfunctions.getValue(e, "id");
name[i] = ""+CategoriesXMLfunctions.getValue(e, "name");
image[i] = ""+CategoriesXMLfunctions.getValue(e, "image");
simage[i] = ""+CategoriesXMLfunctions.getValue(e, "simage");
download[i] = ""+CategoriesXMLfunctions.getValue(e, "download");
author[i] = ""+CategoriesXMLfunctions.getValue(e, "author");
genre[i] = ""+CategoriesXMLfunctions.getValue(e, "genre");
size[i] = ""+CategoriesXMLfunctions.getValue(e, "size");
price[i] = ""+CategoriesXMLfunctions.getValue(e, "price");
mylist.add(map);
id_all = id[i];
image_all = image[i];
dload_all = download[i];
size_all = size[i];
name_all = name[i];
String response = null;
String resstring = null;
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("devid", "devid"));
String devid=null;
try {
devid = URLEncoder.encode(Global.getMac(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String nURL = "http://....url";
response = CustomHttpClient.executeHttpPost(nURL, postParameters);
resstring=response.toString();
String credit = resstring;
String priiice = price[i];
float money = Float.parseFloat(credit);
float pri = Float.parseFloat(priiice);
if(pri>money){
final AlertDialog.Builder alert = new AlertDialog.Builder(MainStore.this);
alert.setMessage("Credits not enough.");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}else{
File sd = getDir("xml",MODE_PRIVATE);
File todel = new File(sd,id[i]+".xml");
todel.delete();
String filecreat= "/"+id[i]+".xml";
File newfil = new File(sd+ filecreat);
if(newfil.exists()){
todel.delete();
}
try{
if(!newfil.exists()){
newfil.createNewFile();
}}catch(IOException e1){
}
try{
FileWriter fileWritter = new FileWriter(newfil);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write("<xml>");
bufferWritter.write("<books>");
bufferWritter.write("<id>"+id[i]+"</id>");
bufferWritter.write("<name>"+name[i]+"</name>");
bufferWritter.write("<download>"+download[i]+"</download>");
bufferWritter.write("<size>"+size[i]+"</size>");
bufferWritter.write("<author>"+author[i]+"</author>");
bufferWritter.write("<genre>"+genre[i]+"</genre>");
bufferWritter.write("<new>0</new>");
bufferWritter.write("</books>");
bufferWritter.write("</xml>");
bufferWritter.close();
Toast.makeText(getApplicationContext(), "Downloading...", Toast.LENGTH_LONG).show();
}catch(IOException e1){
e1.printStackTrace();
Toast.makeText(getApplicationContext(), "error wrting xml "+e1.toString(), Toast.LENGTH_LONG).show();
}
downloadallStarted();
downloadallfiles();
//checkdownloadall();
//downloadallFinished();
}
}catch (Exception e1){
Toast.makeText(getApplicationContext(), "Error in downloadall: " +e1.toString(), Toast.LENGTH_LONG).show();
}
}
And here is my async task
private void startDownloadall() {
String fileURL = dload_all;
fileURL = fileURL.replace(" ", "%20");
new DownloadFileAsync1().execute(fileURL);
Toast.makeText(getApplicationContext(), "Downloading...start all", Toast.LENGTH_LONG).show();
}
class DownloadFileAsync1 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
String fileURL = dload_all;
fileURL = fileURL.replace(" ", "%20");
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = getDir("ebook", MODE_PRIVATE).toString();
String ebookfile = "";
//String filename = id[index];
String filename = id_all;
if(fileURL.endsWith("pdf"))
ebookfile = filename+".pdf";
else
ebookfile = filename+".epub";
bookfile = ebookfile;
Global.setBookfile(bookfile);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, ebookfile);
FileOutputStream fos = new FileOutputStream(outputFile);
lenghtOfFilee = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
//publishProgress("" + (int)((total*100)/lenghtOfFilee));
fos.write(buffer, 0, len1);
}
fos.close();
} catch (Exception e) {
// Log.d("Downloader", e.getMessage());
}
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) {
Global.setBookfile(bookfile);
Toast.makeText(getApplicationContext(), "Downloading..."+lenghtOfFilee, Toast.LENGTH_LONG).show();
checkdownloadall();
//dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
An asynchronous task runs on a background thread, so you directly access variable dload_all in function doInBackground() that is not thread safe. Maybe you can try:
private void startDownloadall() {
//String fileURL = dload_all;
//fileURL = fileURL.replace(" ", "%20");
new DownloadFileAsync1().execute(dload_all, id_all);
Toast.makeText(getApplicationContext(), "Downloading...start all", Toast.LENGTH_LONG).show();
}
class DownloadFileAsync1 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
String fileURL = args[0];
fileURL = fileURL.replace(" ", "%20");
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = getDir("ebook", MODE_PRIVATE).toString();
String ebookfile = "";
//String filename = id[index];
String filename = args[1];
if(fileURL.endsWith("pdf"))
ebookfile = filename+".pdf";
else
ebookfile = filename+".epub";
bookfile = ebookfile;
Global.setBookfile(bookfile);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, ebookfile);
FileOutputStream fos = new FileOutputStream(outputFile);
lenghtOfFilee = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
//publishProgress("" + (int)((total*100)/lenghtOfFilee));
fos.write(buffer, 0, len1);
}
fos.close();
} catch (Exception e) {
// Log.d("Downloader", e.getMessage());
}
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) {
Global.setBookfile(bookfile);
Toast.makeText(getApplicationContext(), "Downloading..."+lenghtOfFilee, Toast.LENGTH_LONG).show();
checkdownloadall();
//dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}

Categories