I am trying to download image on button click through Async Task but the image is not downloading. Is there any problem with the download link in the String "image_url"?
Logcat - skia: --- SkImageDecoder::Factory returned null
public class DownloadImageAsyncTask extends AppCompatActivity {
Button button;
ImageView imageView;
String image_url = "http://www.freegreatdesign.com/files/images/6/2921-large-apple-icon-png-1.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_image_async_task);
button = (Button) findViewById(R.id.bDownload);
imageView = (ImageView) findViewById(R.id.downImage);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(image_url);
}
});
}
class DownloadTask extends AsyncTask<String, Integer, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(DownloadImageAsyncTask.this);
progressDialog.setTitle("Download in progress...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String path = params[0];
int file_length = 0;
try {
URL url = new URL(path);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_length = urlConnection.getContentLength();
File new_folder = new File("sdcard/photoalbum");
if(!new_folder.exists())
{
new_folder.mkdir();
}
File input_file = new File(new_folder, "downloaded_image.jpg");
InputStream inputStream = new BufferedInputStream(url.openStream(), 8192);
byte[] data = new byte[1024];
int total = 0;
int count = 0;
OutputStream outputStream = new FileOutputStream(input_file);
while((count=inputStream.read())!=-1)
{
total+=count;
outputStream.write(data, 0, count);
int progress = (int) total*100/file_length;
publishProgress(progress);
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Download Complete...";
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(String result) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
String path = "sdcard/photoalbum/downloaded_image.jpg";
imageView.setImageDrawable(Drawable.createFromPath(path));
}
}
}
Related
I need to download zip file using multiple URL's and this is my postman
[URL's in postman]
public class downloadfile extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button starbtn;
private ProgressDialog mProgress;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startbtn = (Button)findViewById(R.id.startbtn);
startbtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDown();
}
});
}
private void startDown() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.zip";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgress = new ProgressDialog(this);
mProgress.setMessage("Downloading file..");
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setCancelable(false);
mProgress.show();
return mProgress;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#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);
inputStreamStream inputStream = new BufferedinputStreamStream(url.openStream());
outputStreamStream outputStream = new FileoutputStreamStream("/sdcard/some_photo_from_gdansk_poland.zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgress.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
My Activity Code: Note this is not my main activity, right now i am using a button to fetch images from the database but instead I need to fetch all the images when the app load.
public class QuotesPictures extends Activity implements View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY = "result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages = null;
private int TRACK = 0;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
private static final String IMAGES_URL = "http://stressreliefapp.esy.es/getAllImages.php";
private Button buttonFetchImages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes_pictures);
//Defining all the buttons
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
//Using AsyncTask to load the data in the background thread and then publishing on the UI thread
private void getImage(String urlToImage) {
class GetImage extends AsyncTask<String, Void, Bitmap> {
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(QuotesPictures.this, "Loading Images...", "Please wait...", true, true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
// Method used to get all the images from the database using AsyncTask
public void getAllImages() {
class GetAllImages extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(QuotesPictures.this, "Loading Images...", "Please wait...", true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void extractJSON() {
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage() {
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext() {
if (TRACK < arrayImages.length()) {
TRACK++;
showImage();
}
}
private void movePrevious() {
if (TRACK > 0) {
TRACK--;
showImage();
}
}
#Override
public void onClick(View v) {
if (v == buttonFetchImages) {
getAllImages();
}
if (v == buttonMoveNext) {
moveNext();
}
if (v == buttonMovePrevious) {
movePrevious();
}
}
}
Just execute your download method in onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes_pictures);
//Defining all the buttons
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
getImage("your image url");
}
Move your code at onclicklistener to onResume.
public void onResume()
{
super.onResume();
/* your code at OnClickListener */
}
I'm trying to download a zip file from an API. For this purpose I'm using this following code:
public class Download_Activity extends Activity {
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.download);
startBtn = (Button) findViewById(R.id.downloadButton);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = downloadURL;
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<String, String, String> {
#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 urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.connect();
Log.i("1111", "1111" );
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot, "hello1.zip");
Log.i("2222", "2222" );
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
Log.i("3333", "3333" );
Log.i("befferLength", "bufferLength: " + bufferLength);
Log.i("is read buffer", "is read buffer: " + inputStream.read(buffer));
while ((bufferLength = inputStream.read(buffer)) > 0) {
Log.i("inside while", "inside while ");
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
updateProgress(downloadedSize, totalSize);
}
Log.i("4444", "4444" );
fileOutput.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);
}
}
public void updateProgress(int currentSize, int totalSize) {
Toast.makeText(getApplicationContext(), "Loading Files...",
Toast.LENGTH_SHORT).show();
}
In this code, the zip file is created as "hello1.zip" but this file is empty in my mobile. Here I've various log statements to find the execution of code. To my surprise only upto "Log.i("2222", "2222" );" is printed while the rest of the logs are not printed. Can you please tell me what the problem is???
Thanks in advance..!
U can use DownloadManager class for this purpose it handles the pause and continues the dowloading in the case of network availablity and you can run a broadcast reciver to perform you actions( like pushing a notification etc) when dowloading is complete
http://developer.android.com/reference/android/app/DownloadManager.html
I'm trying to create a method within my activity that will unzip the downloaded file to a certain directory. I have tried several different ways and haven't had much luck. I've seen some people use a separate class to do this task, I want to avoid doing that, but if it's my only option then I will do it. Here is my activity:
public class lava_parkour extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lava_parkour);
startBtn = (Button)findViewById(R.id.button1);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload(v);
} });
}
private void startDownload(View v) {
String url = "https://www.dropbox.com/s/lxnizie52efq3e8/lava%20parkour.zip?
dl=1";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#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("/sdcard/games/com.mojang/lava_parkour.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);
Toast.makeText(lava_parkour.this, "Process completed! THis map has been added
to your game!", Toast.LENGTH_LONG).show();
}
}
}
Any help is appreciated!
public class ExampleActivity extends Activity {
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.main);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
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(true);
mProgressDialog.setButton("Cancel", new CancelOnClickListener());
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
private final class CancelOnClickListener implements DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
ExampleActivity.this.finish();
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
new DownloadFileAsync().cancel(true);
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#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("/sdcard/some_photo_from_gdansk_poland.jpg");
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);
}
}
}
Here if i click the start button,it will download the file automatically.but i want to cancel the download (if i don't like),so i put mProgressDialog.setButton("Cancel", new CancelOnClickListener());this exit the application.but the file is downloading.How to change the function inside doInBackground()
You are using 2 different instance of DownloadFileAsync in startDownload() and CancelOnClickListener. Try the following code:
public class ExampleActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
DownloadFileAsync dfa = new DownloadFileAsync();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
dfa.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(true);
mProgressDialog.setButton("Cancel", new CancelOnClickListener());
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
private final class CancelOnClickListener implements DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
ExampleActivity.this.finish();
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
dfa.cancel(true);
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#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("/sdcard/some_photo_from_gdansk_poland.jpg");
byte data[] = new byte[1024];
long total = 0;
if(!isCancelled()){
while (!isCancelled() && (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);
}
}
}