how send a parametr from a method to another android - android

hi i have a DownloadFileAsync class for download file from url
i download file perfect from web but when download complete i want to play mp3 file from system but i cant send address file from doInBackground to onPostExecute
my code is :
protected String doInBackground(String... aurl) {
try {
File root = Environment.getExternalStorageDirectory();
URL u = new URL(aurl[0]);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
File myFolder = new File( root + "/download/"+aurl[1]+"/" );
myFolder.mkdir();
FileOutputStream f = new FileOutputStream(new File(root + "/download/"+aurl[1]+"/", aurl[2]+".mp3"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[512];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
publishProgress("" + (int)((total*100)/lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
and onPostExecute code is :
protected void onPostExecute(String unused) {
mProgressDialog.dismiss();
File musicFile2Play = new File("/sdcard/download/بابالنگ دراز/شماره یک.mp3");
Intent i2 = new Intent();
i2.setAction(android.content.Intent.ACTION_VIEW);
i2.setDataAndType(Uri.fromFile(musicFile2Play), "audio/mp3");
context.startActivity(i2);
// intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "hamrahtest.apk")), "application/vnd.android.package-archive");
}
how send aurl[1] and aurl[2] from doInBackground to onPostExecute file name ?

You should fill your return from your doInBackground with the objects you wish your OnPostExecute need. For example:
protected List<String> doInBackground(String... aurl) {
List<String> list = new ArrayList<String>();
try {
File root = Environment.getExternalStorageDirectory();
...
list.add(aurl[0]);
list.add(aurl[1]);
list.add(aurl[2]);
list.add(aurl[3]);
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return list;
}
protected void onPostExecute(List<String> list) {
mProgressDialog.dismiss();
for (String url : list) {
// Do you handling here
}
}
You should declare your AsyncTask like this:
public class MyAsyncTask extends AsyncTask<Void, Void, List<String>> {

First:
DownloadFileAsync extends AsyncTask<String, String, String[]>
Second change
protected String doInBackground(String... aurl) {
to
protected String[] doInBackground(String... aurl) {
.....
......
return aurl;
}
Third change
protected void onPostExecute(String unused)
to
protected void onPostExecute(String[] aurl) {

A simple solution would be to make these instance variables on your AsyncTask class. Set them in doInBackgroound, read them in onPostExecute().

Related

Percentage Progress bar not running in java

Am use this code progress bar show but percentage bar not running
I am fairly new to android development, so what I am trying to make is app that can show pdf from url,
Am use this code progress bar show but percentage bar not running
I am using com.github.barteksc.pdfviewer.PDFView to show pdf
here is my pdf show activity
public class test2 extends AppCompatActivity {
PDFView pdfView; //pdfView object
String URL;
String fileName;
File directory; //path of created File
// Container for all parameters of DownloadAsync
private static class AsyncParameters {
String URL;
File directory;
AsyncParameters(String URL, File directory) {
this.URL = URL;
this.directory = directory;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent(); //whatever calls this activity, gather the intent
URL = intent.getStringExtra("File URL"); // in this case, get the file name of the "extra" passed through
fileName = intent.getStringExtra("File Name");
setContentView(R.layout.activity_test2);
File intDirectory = getFilesDir();
File folder = new File(intDirectory, "pdf");
boolean isDirectoryCreated = folder.exists();
//setDownloadButtonListener();
if (!isDirectoryCreated) {
isDirectoryCreated= folder.mkdir();
}
if(isDirectoryCreated) {
directory = new File(folder, fileName);
try {
directory.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
//See if file already exists (reduces wait time)
boolean empty = directory.length() == 0;
if (empty) {
/**Call class to create parameter container **/
AsyncParameters param = new AsyncParameters(URL, directory);
DownloadAsync Downloader = new DownloadAsync();
Downloader.execute(param);
}
showPdf();
}
}
public void showPdf()
{
pdfView = (PDFView) findViewById(R.id.pdfViewPager);
pdfView.fromFile(directory).load();
}
public class DownloadAsync extends AsyncTask<AsyncParameters, Void, Void> {
// Container for all parameters of DownloadAsync
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
//Create a progress bar that details the program downloading
super.onPreExecute();
pDialog = new ProgressDialog(test2.this);
pDialog.setMessage("Downloading ");
String message= "please wait don't push back";
SpannableString ss2 = new SpannableString(message);
ss2.setSpan(new RelativeSizeSpan(1f), 0, ss2.length(), 0);
ss2.setSpan(new ForegroundColorSpan(Color.BLACK), 0, ss2.length(), 0);
pDialog.setMessage(ss2);
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.show();
}
#Override
protected Void doInBackground(AsyncParameters... params) {
int count;
String fileURL = params[0].URL;
File directory = params[0].directory;
try {
FileOutputStream f = new FileOutputStream(directory);
java.net.URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.connect();
InputStream in = c.getInputStream();
int length=c.getContentLength();
byte[] data;
data = new byte[1024];
long total = 0;
while ((count = in.read(data)) != -1) {
total += count;
f.write(data, 0, count);
}
f.flush();
in.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
pDialog.setMessage(new SpannableString("ERROR DOWNLOADING"));
}
onPostExecute();
return null;
}
private void onPostExecute() {
pDialog.dismiss();
showPdf();
}
}
}
I don't see that you are calling publishProgress in doing background to invoke OnProgressUpdate.I don't see that you are setting the percentage in onProgressUpdate.I don't see that you have oveerriden onProgressUpdate anywhere.
OnPostExecute() is automatically called when background execution finishes.You don't need to call explicitly in doInBackGround and should not call it explicitly.
Note: AsyncTask is deprecated for API level 30.

Delete file if AsyncTask Fail

Currently
I am downloading a file from a URL, I'm doing this within AsyncTask inside a Adapter. The problem I have is that when I press back onBackPressed the download stops but the file remains in the folder FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/file.mp4");
My Question
Is it possible to delete the file if AsyncTask does not complete?
I have tried to do file.delete(); in the catch of doinbackground but I get error file.delete(); is ignored
Here is a summary of my adapter----
When Item in holder is clicked I call AsyncTask:
holder.setItemClickListener(new ItemClickListener() {
if (pos == 1) {
if(manager.fetchVideoPath(pos)==null) {
DownloadFileFromURL p = new DownloadFileFromURL();
p.execute(pos + "", "https://www.dropbox.com/s/xnzw753f13k68z4/Piper%20First%20Look%20%282016%29%20-%20Pixar%20Animated%20Short%20HD.mp4?dl=1");
a = "one";
bars.set(pos,new ProgressModel(pos,1));
//This is what is causing the issue
RecyclerVideoAdapter.this.notifyItemChanged(pos);
}
My AsyncTask:
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
((CircularProgressBar)vview.findViewById(R.id.circularProgressBar)).setProgress(1);
}
#Override
protected String doInBackground(String... f_url) {
int count;
String pathreference = f_url[0]+",";
positionnumber = Integer.parseInt(f_url[0]);
try {
URL url = new URL(f_url[1]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
if (a.equals("one")) {
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/file.mp4");
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();
pathreference = pathreference+Environment.getExternalStorageDirectory().toString()+"/file.mp4";
output.close();
input.close();
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return pathreference;
}
protected void onProgressUpdate(String... progress) {
bars.get(positionnumber).setProgress_(Float.parseFloat(progress[0]));
((CircularProgressBar)vview.findViewById(R.id.circularProgressBar)).setProgress(bars.get(positionnumber).getProgress_());
}
#Override
protected void onPostExecute(String file_url) {
String []split = file_url.split(",");
int index1 = Integer.parseInt(split[0]);
videoHolderClass.set(index1,new VideoHolderClass(index1,imgres[0]));
bars.get(index1).setProgress_(0);
manager.insertVideoPath(index1+"",split[1]);
RecyclerVideoAdapter.this.notifyItemChanged(index1);
}
}
Building on the answer on this post, try to put the logic of deleting the file inside isCancelled() like this:
if (isCancelled() && file.exists())
file.delete();
else
{
// do your work here
}
Then you can call p.cancel(true) inside onBackPressed

Ekito Simple KML read source

I have one KML at this link:
http://myurl.com/mykml.kml
I want to get the com.ekito.simpleKML.model KML object from it.
I'm trying with this:
String url = "http://myurl.com/mykml.kml";
Serializer kmlSerializer = new Serializer();
Kml kml = kmlSerializer.read(url);
But the kml object is still null.
This is the link to the Ekito Simple KML library: https://github.com/Ekito/Simple-KML
I see the Ekito he can not read a file on the internet. Test this example!
private ProgressDialog progressBar;
public static final int KML_PROGRESS = 0;
public String fileURL ="http://myurl.com/mykml.kml";
// set in OnClick Button
new DownloadKML().execute(fileURL);
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case KML_PROGRESS:
progressBar = new ProgressDialog(this);
progressBar.setMessage("Downloading file…");
progressBar.setIndeterminate(false);
progressBar.setMax(100);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setCancelable(true);
progressBar.show();
return progressBar;
default:
return null;
}
}
class DownloadKML extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(KML_PROGRESS);
}
#Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL( url[0] );
URLConnection connect = url.openConnection();
connect.connect();
int progressOfFile = connect.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/KML_Samples.kml");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/progressOfFile) );
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
progressBar.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
String pathKML = Environment.getExternalStorageDirectory().toString() + "/KML_Samples.kml";
// load
Serializer kmlSerializer = new Serializer();
Kml kml = kmlSerializer.read(url);
}
}

how to download file in android download service

i have this url http://translate.google.com/translate_tts?ie=UTF-8&q=hi&tl=en&total=1&idx=0&textlen=2
when i place it to pc and android browser it makes me force to download
how can i make it download in my android application without browser.
i tried to make to download using this tutorial how can i download audio file from server by url
.but it did not work.
anyone please help
Thank you Kristijana Draca think it is working but where it save in emulator here is my code public class Main extends Activity {
EditText inputtext;
Button listen;
Button shareButton;
TextView tv;
ProgressBar proBar;
//ProgressDialog progress;
MediaPlayer player;
public Boolean isPlaying=true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
downloadContent();
}
private void downloadContent() {
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http://translate.google.com/translate_a/t?client=t&source=baf&sl=ar&tl=en&hl=en&q=%D9%85%D8%B1%D8%AD%D8%A8%D8%A7&sc=1 ");
}
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(
connection.getInputStream());
// Create db
OutputStream output = new FileOutputStream(
Environment.getDataDirectory() + "/data/"
+ "com.jony.com" + "/file.mp3");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
Toast.makeText(getApplicationContext(), "download complete", 1000).show();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "download complete", 1000).show();
}
}
});
You can download any file using AsyncTask.
downloadContent();
private void downloadContent() {
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http://somehost.com/file.mp3");
}
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(
connection.getInputStream());
// Create db
OutputStream output = new FileOutputStream(
Environment.getDataDirectory() + "/data/"
+ PACKAGE_NAME + "/file.mp3");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}

android 2.1 AsyncTask file download not working for multiple thread work fine when call single instance

i am using android 2.1 ,api level 7 and try to implement asynchronous file download from LAN server
for this i am trying to implement AsyncTask .When i am trying to call a single thread it works find but when call multiple its just stop both the thread
/* AsyncTask class*/
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
Log.i("count","in");
URLConnection conexion = url.openConnection();
Log.i("count","in1");
conexion.connect();
Log.i("count","in2");
File root = android.os.Environment.getExternalStorageDirectory();
Log.i("count","in3");
int lenghtOfFile = conexion.getContentLength();
Log.i("count","in4");
BufferedInputStream input = new BufferedInputStream(url.openStream());
Log.i("count","in5");
OutputStream output = new FileOutputStream(root.getAbsolutePath() + "/video" +aurl[1] +".mp4");
byte data[] = new byte[1024];
long total = 0;
Log.i("count","in6");
while ((count = input.read(data)) != -1) {
//Log.i("count","in7");
total += count;
Log.i("count",aurl[1]);
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.i("progress",progress[0]);
}
#Override
protected void onPostExecute(String unused) {
Log.i("process","end");
}
}
/*main method call*/
private void startDownload() {
Log.v("count","out");
String url = lanurl+"titanic/video"+1+"_en.m4v";
new DownloadFileAsync().execute(url,"1");
url = lanurl+"titanic/video"+2+"_en.m4v";
new DownloadFileAsync().execute(url,"2");
}
output :
download both file in sd card
but no file downloading properly
I didn't understand the complete Question. But seems like your problem is with AsyncTask.
Single Object created for an AsyncTask can be used only once. If you want to use it again, you need to create an another object for the same AsyncTask.

Categories

Resources