How to download multiple images from urls in a single process? - android

I create app for download multi images, from url, the problem is when download all images (there's 3000 images) its multi process, not single process. Single process I mean download and then save, download and then save and so on.
It's possible to download multi image with single process ?
this is my code :
private CoordinatorLayout mCLayout;
private ProgressDialog mProgressDialog;
private LinearLayout mLLayout;
private AsyncTask mMyTask;
private final URL[] URLS = {
stringToURL("https://d1rkccsb0jf1bk.cloudfront.net/products/3d/100009884/images/I_20.jpg"),
stringToURL("https://d3inagkmqs1m6q.cloudfront.net/2280/media-photos/azk0w23602-black-new-calvin-klein-watches-k0w23602.jpg"),
stringToURL("https://www.designerswatch.com.au/media/catalog/product/cache/1/image/800x800/9df78eab33525d08d6e5fb8d27136e95/k/2/k2y211c3-1.jpg"),
stringToURL("http://demandware.edgesuite.net/sits_pod35/dw/image/v2/ABAD_PRD/on/demandware.static/-/Sites-calvinklein-hk-master/default/dw521470a6/images/hi-res/K7Y214CZ-000/K7Y214CZ-000-ITEM-1.jpg?sw=500"),
stringToURL("https://ethos-cdn1.ethoswatches.com/pub/media/catalog/product/cache/749a04adc68de020ef4323397bb5eac7/c/a/calvin-klein-party-k8u2m116.jpg")
// and so on
};
int count;
// List of url image
List<URL> imageName = new ArrayList<>();
File file;
ContextWrapper wrapper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application context
getApplicationContext();
Activity mActivity = MainActivity.this;
// Get the widget reference from XML layout
mCLayout = findViewById(R.id.coordinator_layout);
Button mButtonDo = findViewById(R.id.btn_do);
mLLayout = findViewById(R.id.ll);
//-------------------set image--------------------------
ImageView setImage = findViewById(R.id.setImage);
// Initialize ContextWrapper
wrapper = new ContextWrapper(getApplicationContext());
file = wrapper.getDir("Images",MODE_PRIVATE);
file = new File(file, "I_20.jpg");
if(file.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
setImage.setImageBitmap(myBitmap);
}
//-------------------set image--------------------------
// Initialize the progress dialog
mProgressDialog = new ProgressDialog(mActivity);
mProgressDialog.setIndeterminate(false);
// Progress dialog horizontal style
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// Progress dialog title
mProgressDialog.setTitle("AsyncTask");
// Progress dialog message
mProgressDialog.setMessage("Please wait, we are downloading your image files...");
mProgressDialog.setCancelable(true);
// Set a progress dialog dismiss listener
mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
// Cancel the AsyncTask
mMyTask.cancel(false);
}
});
// Initialize a new click listener for positive button widget
mButtonDo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Execute the async task
mMyTask = new DownloadTask().execute(URLS);
}
});
}
/*
* First parameter URL for doInBackground
* Second parameter Integer for onProgressUpdate
* Third parameter List<Bitmap> for onPostExecute
*/
#SuppressLint("StaticFieldLeak")
private class DownloadTask extends AsyncTask<URL,Integer,List<Bitmap>>{
// Before the tasks execution
protected void onPreExecute(){
// Display the progress dialog on async task start
mProgressDialog.show();
mProgressDialog.setProgress(0);
}
// Do the task in background/non UI thread
protected List<Bitmap> doInBackground(URL...urls){
Log.d("doInBackground", "doInBackground: ");
count = urls.length;
//URL url = urls[0];
HttpURLConnection connection = null;
List<Bitmap> bitmaps = new ArrayList<>();
// Loop through the urls
for(int i=0;i<count;i++){
URL currentURL = urls[i];
// So download the image from this url
try{
// Initialize a new http url connection
connection = (HttpURLConnection) currentURL.openConnection();
// Connect the http url connection
connection.connect();
// Get the input stream from http url connection
InputStream inputStream = connection.getInputStream();
// Initialize a new BufferedInputStream from InputStream
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
// Convert BufferedInputStream to Bitmap object
Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
// Add the bitmap to list
bitmaps.add(bmp);
// add the url to list URL
imageName.add(currentURL);
// Publish the async task progress
// Added 1, because index start from 0
publishProgress((int) (((i+1) / (float) count) * 100));
if(isCancelled()){
break;
}
}catch(IOException e){
e.printStackTrace();
}finally{
// Disconnect the http url connection
assert connection != null;
connection.disconnect();
}
}
// Return bitmap list
return bitmaps;
}
// On progress update
protected void onProgressUpdate(Integer... progress){
// Update the progress bar
mProgressDialog.setProgress(progress[0]);
}
// On AsyncTask cancelled
protected void onCancelled(){
Snackbar.make(mCLayout,"Task Cancelled.",Snackbar.LENGTH_LONG).show();
}
// When all async task done
protected void onPostExecute(List<Bitmap> result){
// Hide the progress dialog
mProgressDialog.dismiss();
// Remove all views from linear layout
mLLayout.removeAllViews();
Log.d("result", String.valueOf(result));
// Loop through the bitmap list
for(int i=0;i<result.size();i++){
Bitmap bitmap = result.get(i);
// Save the bitmap to internal storage
Uri imageInternalUri = saveImageToInternalStorage(bitmap, i);
// Display the bitmap from memory
addNewImageViewToLayout(bitmap);
// Display bitmap from internal storage
// addNewImageViewToLayout(imageInternalUri);
}
}
}
// Custom method to convert string to url
protected URL stringToURL(String urlString){
try{
return new URL(urlString);
}catch(MalformedURLException e){
e.printStackTrace();
}
return null;
}
// Custom method to save a bitmap into internal storage
protected Uri saveImageToInternalStorage(Bitmap bitmap, int index){
Log.d("count", String.valueOf(count));
// Initializing a new file
// The bellow line return a directory in internal storage
file = wrapper.getDir("Images",MODE_PRIVATE);
// Create a file to save the image
// First get name of image from url, and then saved with that name
file = new File(file, getFileNameFromUrl(imageName.get(index)));
Log.d("TAG", String.valueOf(file));
try{
// Initialize a new OutputStream
OutputStream stream;
// If the output file exists, it can be replaced or appended to it
stream = new FileOutputStream(file);
// Compress the bitmap
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
// Flushes the stream
stream.flush();
// Closes the stream
stream.close();
}catch (IOException e) // Catch the exception
{
e.printStackTrace();
}
// Parse the gallery image url to uri
// Return the saved image Uri
return Uri.parse(file.getAbsolutePath());
}
/**
* This function will take an URL as input and return the file name.
* Examples :
* http://example.com/a/b/c/test.txt -> test.txt
* http://example.com/ -> an empty string
* http://example.com/test.txt?param=value -> test.txt
* http://example.com/test.txt#anchor -> test.txt
*
* #param url The input URL
* #return The URL file name
*/
public static String getFileNameFromUrl(URL url) {
// String file
String urlString = url.getFile();
// Return image name
return urlString.substring(urlString.lastIndexOf('/') + 1).split("\\?")[0].split("#")[0];
}
// Custom method to add a new image view using bitmap
protected void addNewImageViewToLayout(Bitmap bitmap){
// Initialize a new ImageView widget
ImageView iv = new ImageView(getApplicationContext());
// Set an image for ImageView
iv.setImageBitmap(bitmap);
// Create layout parameters for ImageView
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, 500);
// Add layout parameters to ImageView
iv.setLayoutParams(lp);
// Finally, add the ImageView to layout
mLLayout.addView(iv);
}
// Custom method to add a new image view using uri
protected void addNewImageViewToLayout(Uri uri){
// Initialize a new ImageView widget
ImageView iv = new ImageView(getApplicationContext());
// Set an image for ImageView
iv.setImageURI(uri);
// Create layout parameters for ImageView
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, 300);
// Add layout parameters to ImageView
iv.setLayoutParams(lp);
// Finally, add the ImageView to layout
mLLayout.addView(iv);
}
my goal is to make it like this, because I got error, Clamp target GC heap I think the problem is BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); because many images.
thanks a lot

Use DownloadManager to download multiple images
public static void downloadFile(String uRl, Context context) {
File myDir = new File(Environment.getExternalStorageDirectory(), "MyApp/");
if (!myDir.exists()) {
myDir.mkdirs();
}
DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE).setAllowedOverMetered(true)
.setAllowedOverRoaming(true).setTitle("Myapp - " + "Downloading " + uRl).
setVisibleInDownloadsUi(true)
.setDestinationInExternalPublicDir("MyApp" + "/", uRl);
mgr.enqueue(request);
}
Usage:-
// Initialize a new click listener for positive button widget
mButtonDo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Execute the async task
// mMyTask = new DownloadTask().execute(URLS);
for (int i = 0; i < URLS .size(); i++) {
downloadFile(urls[i],Activityname.this);
}
}
});
To change path , edit this
File myDir = new File(Environment.getExternalStorageDirectory(), "MyApp/");

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.

Download image from 'download url' Android

There are tons of download image from url codes. But is it possible to download image from url that already action download? I mean ;
Tons of codes about download the this image from that link
But I want to download image to android device from this link
Is it possible ?
Thanks
Nothing hard in this.
public class DownloadImage extends Activity {
String image_URL=http://www.hdwallpapers.in/download/minions_2015-1280x720.jpg; // give image name to save in sd card
String extStorageDirectory;
String sdCard;
Bitmap bitmap;
File file;
String savedFilePath;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonSave = (Button)findViewById(R.id.save);
ImageView bmImage = (ImageView)findViewById(R.id.image);
buttonSave.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
myAsyncTask myWebFetch = new myAsyncTask();
myWebFetch.execute();
}
});
}
class myAsyncTask extends AsyncTask<Void, Void, Void> {
TextView tv;
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
public ProgressDialog dialog;
dialog = new ProgressDialog(DownloadImage.this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.setIndeterminate(true);
dialog.show();
}
protected Void doInBackground(Void... arg0) {
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(image_URL);
//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.
File file = new File(SDCardRoot,"somefile.jpg");
//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
//updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
Now you downloaded image directly in sd card. Don't forget to give permission in manifest for external storage.
Try to check out this tutorial, was very helpful to me. He uses a custom class called ImageLoader with a public method DisplayImage(String url, int loader, ImageView imageView), you can call it this way:
int loader = R.drawable.loader;
// Imageview to show
ImageView image = (ImageView) findViewById(R.id.image);
// Image url
String image_url = "http://www.example.com/images/sample.jpg";
// ImageLoader class instance
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
imgLoader.DisplayImage(image_url, loader, image);

ImageView displaying the same image after GridView item has been clicked

I'm having a problem which is probably much simple than I think. I have a GridView that load images from URL sent in JSON. The Url are then converted to bitmap and every image is passed to a GridView item. That all works perfectly. Then when i click on the image I send the image url to another view that displays it in fulls size, my problem is that every time I click on an item in the GridView it always loads the image in the last item of that GridView, so I'm asumming that probably when I send the image url to the next view I'm always passing the url of the last image. Does someone know what I can do to display the proper image after it has been clicked in the list view? any help will be appreciated.
Code:
/**
* Background AsyncTask to load profiles images by making HTTP Request
*/
class GetProfileImages extends AsyncTask<String, String, String> {
// Progress Dialog
private ProgressDialog pDialog;
URL url = null;
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileImages.this);
pDialog.setMessage("Loading images...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Gets all the notices from URL that correspond to the current user
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// Gets JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_profile_images, "GET", params);
// Check your log cat for JSON response
Log.d("Profile images: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Image found
// Gets Array of notices
images = json.getJSONArray(TAG_IMAGES);
// Loops through all images
for (int i = 0; i < images.length(); i++) {
JSONObject image = images.getJSONObject(i);
// Storing each JSON item in variable
imagePath = ("http://gatoandroidapp.comeze.com/" + image.getString(TAG_PATH));
//Gets image path and passed the image in bitmap format
try {
url = new URL(imagePath);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
}catch (IOException e) {
}
// Creates new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// Ads child nodes to HashMap
map.put(TAG_PATH, bmp);
// Ads HashList to ArrayList
imagesList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
*/
protected void onPostExecute(String file_url) {
//Dismiss the dialog after getting images
pDialog.dismiss();
//Updates UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//Updates parsed JSON data into ListView
ListAdapter adapter = new ExtendedSimpleAdapter(
ProfileImages.this, imagesList,
R.layout.profile_images_custom_gridview, new String[] {TAG_PATH},
new int[] {R.id.profilesImages_customGridView});
//Updates ListView
gridview.setAdapter(adapter);
}
});
}
}
Code to pass the image url:
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Creates intent
Intent i = new Intent(v.getContext(), PictureView.class);
//Sends image path to next view
i.putExtra(TAG_PATH, imagePath);
startActivityForResult(i, 0);
}
});
Code that receive intent with image url (path)
// Get image path from intent
imagePath = getIntent().getStringExtra(TAG_PATH);
//Load image from server into ImageView
profilePicture = (ImageView) findViewById(R.id.pictureView_imageView);
URL url = null;
Bitmap bmp = null;
try {
url = new URL(imagePath);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
}catch (IOException e) {
}
profilePicture.setImageBitmap(bmp);
Thanks!
I guess, you have declared imagePath with Class-level scope. Since at the end of for loop imagePath is updated with the last item URL so you're always passing the url of the last image.
To resolve the issue, make use of View.setTag() and View.getTag() methods to pass the URL (or) Use the position in onItemClick() to retrieve the
JSONObject image = images.getJSONObject(position); and construct the URL.

Android: How to create a direct download link in android

Can anyone give me an idea on how to create a textview which has a link and when the user click it, the file from that link will be automatically downloaded by the device
EDIT:
here's the code were working on:
String link = "http://www.exampleurl.com/"+pref.getString("fsfile" + count, null);
link = link.replaceAll(" ", "%20");
fsfile.setText("Attached File");
fsfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(link);
}
});
but it seems the String link is not identified inside the .setOnClickListener
Thats quite easy
http://developer.android.com/reference/android/app/DownloadManager.html
Example: http://androidtrainningcenter.blogspot.co.at/2013/05/android-download-manager-example.html
And start this method after clicking the textview (Catch with Handler or listener)
/**
* Start Download
*/
public void startDownload() {
DownloadManager mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Request mRqRequest = new Request(
Uri.parse("http://androidtrainningcenter.blogspot.in/2012/11/android-webview-loading-custom-html-and.html"));
mRqRequest.setDescription("This is Test File");
// mRqRequest.setDestinationUri(Uri.parse("give your local path"));
long idDownLoad=mManager.enqueue(mRqRequest);
}
But be sure you are min. on API 9
Please use the below code onclick of TextView:
<Your TextView>.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(<Your URL String>);
}
});
DownloadFromURL.java
public 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));
}
}

how to show next image on button click if i have image urls in an array

click .. i think que is clear pls help me i am new in android and java pls pls..
**private String[] imageList = {"http://www.artealdiaonline.com/var/artealdia_com/storage/images/argentina/directorio/galerias/ruth_benzacar/artistas/martin_di_girolamo._diosas/198915-1-esl-AR/MARTIN_DI_GIROLAMO._Diosas.jpg","http://www.artealdiaonline.com/var/artealdia_com/storage/images/argentina/directorio/galerias/ruth_benzacar/artistas/jorge_macchi._la_espera/198929-1-esl-AR/JORGE_MACCHI._La_espera.jpg"};**
public class SequencerActivity extends Activity implements OnClickListener
{
private int imageCounter = 0;
private ImageView imageLoader;
**private String[] imageList = {"http://www.artealdiaonline.com/var/artealdia_com/storage/images/argentina/directorio/galerias/ruth_benzacar/artistas/martin_di_girolamo._diosas/198915-1-esl-AR/MARTIN_DI_GIROLAMO._Diosas.jpg","http://www.artealdiaonline.com/var/artealdia_com/storage/images/argentina/directorio/galerias/ruth_benzacar/artistas/jorge_macchi._la_espera/198929-1-esl-AR/JORGE_MACCHI._La_espera.jpg"};**
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.parent_frame);//this one is the common parent layout for all image views
super.onCreate(savedInstanceState);
/*requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);*/
//int image1 = R.drawable.image_w_lbl_0;
//imageLoader.setImageResource(image1);
ImageButton next = (ImageButton) findViewById(R.id.next);
ImageButton back = (ImageButton) findViewById(R.id.back);
next.setOnClickListener(this);
back.setOnClickListener(this);
back.setEnabled(false);
//show the default image
this.loadImage(imageList[imageCounter]);
}
#Override
public void onClick(View v)
{
}
private void loadImage(int imagePath)
{
imageLoader.setImageResource(imagePath);
}
}
If you have String values in your imageList array representing resource names,
private String[] imageList = { "image_wo_lbl_0", "image_wo_lbl_1", "image_wo_lbl_2" };
then you can modify the loadImage method:
private void loadImage(final String imagePath)
{
imageLoader.setImageResource(getResources().
getIdentifier(imagePath, "drawable", "your.application.package"));
}
If you have urls stored in the imageList array
private String[] imageList = { "file:///somedir/IMAG0001.jpg",
"file:///otherdir/IMAG0002.jpg",
"file:///somedir/IMAG0003.jpg" };
you can use
private void loadImage(final String imagePath)
{
imageLoader.setImageURI(Uri.parse(imagePath));
}
When loading images from the web (storing their urls in the imageList):
private String[] imageList = { "http://somedomain/IMAG0001.jpg",
"http://otherdomain/IMAG0002.jpg",
"http://somedomain/IMAG0003.jpg" };
[...]
private void loadImage(String imagePath)
{
try
{
final URL url = new URL(imagePath);
final InputStream inputStream = (InputStream)url.getContent();
Drawable drawable = Drawable.createFromStream(inputStream, "src");
imageLoader.setImageDrawable(drawable);
}
catch (Exception e)
{
Log.e("Error", "loadImage", e);
}
}
For this to work, don't forget to add the android.permission.INTERNET permission to your application in the `androidManifest.xml!
#rekaszeru i had used
private void loadImage(String imagePath)
{
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(imagePath);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
/* Apply the Bitmap to the ImageView that will be returned. */
imageLoader.setImageBitmap(bm);
//bigView.setImageBitmap(bm);
// bigView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageLoader.setImageBitmap(bm);
} catch (IOException e) {
// i.setImageResource(R.drawable.error);
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
You should take only one Imageview and set image using setImageResource properties and increase the countervalue when click on next button .
You can also use imageswitcher control for solving this problem.
You can refer to this SO question. Every time your press you have to call that method and change the URL by passing the next element in the array.

Categories

Resources